EADST

Transformers Llama 参数配置代码中文注释 configuration_llama.py

# coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# 此代码基于EleutherAI的GPT-NeoX库以及此库中的GPT-NeoX和OPT实现。
# 它已从原始形式修改,以适应与Meta AI团队训练模型时使用的GPT-NeoX和OPT相比的
# 微小架构差异。
#
# 根据Apache许可证2.0版("许可证")获得许可;
# 除非符合许可证,否则不得使用此文件。
# 您可以在以下位置获取许可证副本:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 除非适用法律要求或书面同意,否则依据许可证分发的软件
# 是基于"按原样"分发的,没有任何明示或暗示的担保或条件。
# 有关许可证下特定语言的权限和限制,请参阅许可证。
# 中文代码注释 XD
# 源码请参考 https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/configuration_llama.py
"""LLaMA模型配置"""

from ...configuration_utils import PretrainedConfig
from ...modeling_rope_utils import rope_config_validation


class LlamaConfig(PretrainedConfig):
    r"""
    这是用于存储[`LlamaModel`]配置的配置类。它用于根据指定的参数实例化LLaMA模型,
    定义模型架构。使用默认值实例化配置将产生与LLaMA-7B类似的配置。

    配置对象继承自[`PretrainedConfig`],可用于控制模型输出。
    有关更多信息,请阅读[`PretrainedConfig`]的文档。


    参数:
        vocab_size (`int`, *可选*, 默认为32000):
            LLaMA模型的词汇表大小。定义调用[`LlamaModel`]时可以通过`inputs_ids`表示的不同标记数量。
        hidden_size (`int`, *可选*, 默认为4096):
            隐藏表示的维度。
        intermediate_size (`int`, *可选*, 默认为11008):
            MLP表示的维度。
        num_hidden_layers (`int`, *可选*, 默认为32):
            Transformer解码器中的隐藏层数。
        num_attention_heads (`int`, *可选*, 默认为32):
            Transformer解码器中每个注意力层的注意力头数。
        num_key_value_heads (`int`, *可选*):
            这是实现分组查询注意力(GQA)时应使用的key_value头数。如果
            `num_key_value_heads=num_attention_heads`,模型将使用多头注意力(MHA);如果
            `num_key_value_heads=1`,模型将使用多查询注意力(MQA);否则使用GQA。
            将多头检查点转换为GQA检查点时,每个组的key和value头应通过
            对该组内所有原始头进行平均池化来构造。更多详细信息请查看
            [这篇论文](https://arxiv.org/pdf/2305.13245.pdf)。如果未指定,将默认为
            `num_attention_heads`。
        hidden_act (`str` 或 `function`, *可选*, 默认为 `"silu"`):
            解码器中的非线性激活函数(函数或字符串)。
        max_position_embeddings (`int`, *可选*, 默认为2048):
            此模型可能曾经使用的最大序列长度。Llama 1支持最多2048个token,
            Llama 2最多4096个,CodeLlama最多16384个。
        initializer_range (`float`, *可选*, 默认为0.02):
            用于初始化所有权重矩阵的truncated_normal_initializer的标准差。
        rms_norm_eps (`float`, *可选*, 默认为1e-06):
            rms归一化层使用的epsilon值。
        use_cache (`bool`, *可选*, 默认为 `True`):
            模型是否应返回最后的key/values注意力(并非所有模型都使用)。
            仅当`config.is_decoder=True`时相关。
        pad_token_id (`int`, *可选*):
            填充标记ID。
        bos_token_id (`int`, *可选*, 默认为1):
            流开始标记ID。
        eos_token_id (`int`, *可选*, 默认为2):
            流结束标记ID。
        pretraining_tp (`int`, *可选*, 默认为1):
            实验性功能。预训练期间使用的张量并行等级。请参阅
            [此文档](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism)
            以了解更多相关信息。该值对于确保预训练结果的精确复现是必要的。
            请参阅[此问题](https://github.com/pytorch/pytorch/issues/76232)。
        tie_word_embeddings (`bool`, *可选*, 默认为 `False`):
            是否绑定权重嵌入。
        rope_theta (`float`, *可选*, 默认为10000.0):
            RoPE嵌入的基本周期。
        rope_scaling (`Dict`, *可选*):
            包含RoPE嵌入缩放配置的字典。注意:如果您应用新的rope类型,
            并且您希望模型在更长的`max_position_embeddings`上工作,
            我们建议您相应地更新此值。
            预期内容:
                `rope_type` (`str`):
                    要使用的RoPE子变体。可以是['default', 'linear', 'dynamic', 'yarn', 'longrope',
                    'llama3']之一,其中'default'是原始RoPE实现。
                `factor` (`float`, *可选*):
                    除'default'之外的所有rope类型都使用。应用于RoPE嵌入的缩放因子。在
                    大多数缩放类型中,x的`factor`将使模型能够处理长度为x *
                    原始最大预训练长度的序列。
                `original_max_position_embeddings` (`int`, *可选*):
                    与'dynamic', 'longrope'和'llama3'一起使用。预训练期间使用的原始最大位置嵌入。
                `attention_factor` (`float`, *可选*):
                    与'yarn'和'longrope'一起使用。应用于注意力计算的缩放因子。
                    如果未指定,它将默认为实现推荐的值,使用`factor`字段推断建议的值。
                `beta_fast` (`float`, *可选*):
                    仅与'yarn'一起使用。参数,用于在线性斜坡函数中设置外推(仅)的边界。
                    如果未指定,默认为32。
                `beta_slow` (`float`, *可选*):
                    仅与'yarn'一起使用。参数,用于在线性斜坡函数中设置插值(仅)的边界。
                    如果未指定,默认为1。
                `short_factor` (`List[float]`, *可选*):
                    仅与'longrope'一起使用。应用于短上下文(<
                    `original_max_position_embeddings`)的缩放因子。必须是长度与隐藏
                    大小除以注意力头数除以2相同的数字列表。
                `long_factor` (`List[float]`, *可选*):
                    仅与'longrope'一起使用。应用于长上下文(<
                    `original_max_position_embeddings`)的缩放因子。必须是长度与隐藏
                    大小除以注意力头数除以2相同的数字列表。
                `low_freq_factor` (`float`, *可选*):
                    仅与'llama3'一起使用。应用于RoPE低频分量的缩放因子。
                `high_freq_factor` (`float`, *可选*):
                    仅与'llama3'一起使用。应用于RoPE高频分量的缩放因子。
        attention_bias (`bool`, *可选*, 默认为 `False`):
            是否在自注意力期间的查询、键、值和输出投影层中使用偏置。
        attention_dropout (`float`, *可选*, 默认为0.0):
            注意力概率的dropout比率。
        mlp_bias (`bool`, *可选*, 默认为 `False`):
            是否在MLP层中的up_proj、down_proj和gate_proj层中使用偏置。
        head_dim (`int`, *可选*):
            注意力头维度。如果为None,将默认为hidden_size // num_attention_heads。

    ```python
    >>> from transformers import LlamaModel, LlamaConfig

    >>> # 初始化LLaMA llama-7b风格的配置
    >>> configuration = LlamaConfig()

    >>> # 从llama-7b风格配置初始化模型
    >>> model = LlamaModel(configuration)

    >>> # 访问模型配置
    >>> configuration = model.config
    ```"""

    model_type = "llama"
    keys_to_ignore_at_inference = ["past_key_values"]
    # 基础模型`LlamaModel`的默认张量并行计划
    base_model_tp_plan = {
        "layers.*.self_attn.q_proj": "colwise",
        "layers.*.self_attn.k_proj": "colwise",
        "layers.*.self_attn.v_proj": "colwise",
        "layers.*.self_attn.o_proj": "rowwise",
        "layers.*.mlp.gate_proj": "colwise",
        "layers.*.mlp.up_proj": "colwise",
        "layers.*.mlp.down_proj": "rowwise",
    }
    base_model_pp_plan = {
        "embed_tokens": (["input_ids"], ["inputs_embeds"]),
        "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
        "norm": (["hidden_states"], ["hidden_states"]),
    }

    def __init__(
        self,
        vocab_size=32000,
        hidden_size=4096,
        intermediate_size=11008,
        num_hidden_layers=32,
        num_attention_heads=32,
        num_key_value_heads=None,
        hidden_act="silu",
        max_position_embeddings=2048,
        initializer_range=0.02,
        rms_norm_eps=1e-6,
        use_cache=True,
        pad_token_id=None,
        bos_token_id=1,
        eos_token_id=2,
        pretraining_tp=1,
        tie_word_embeddings=False,
        rope_theta=10000.0,
        rope_scaling=None,
        attention_bias=False,
        attention_dropout=0.0,
        mlp_bias=False,
        head_dim=None,
        **kwargs,
    ):
        self.vocab_size = vocab_size
        self.max_position_embeddings = max_position_embeddings
        self.hidden_size = hidden_size
        self.intermediate_size = intermediate_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads

        # 为了向后兼容
        if num_key_value_heads is None:
            num_key_value_heads = num_attention_heads

        self.num_key_value_heads = num_key_value_heads
        self.hidden_act = hidden_act
        self.initializer_range = initializer_range
        self.rms_norm_eps = rms_norm_eps
        self.pretraining_tp = pretraining_tp
        self.use_cache = use_cache
        self.rope_theta = rope_theta
        self.rope_scaling = rope_scaling
        self.attention_bias = attention_bias
        self.attention_dropout = attention_dropout
        self.mlp_bias = mlp_bias
        self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
        # 验证旋转位置嵌入参数的正确性
        # 向后兼容:如果存在'type'字段,将其复制到'rope_type'。
        if self.rope_scaling is not None and "type" in self.rope_scaling:
            self.rope_scaling["rope_type"] = self.rope_scaling["type"]
        rope_config_validation(self)

        super().__init__(
            pad_token_id=pad_token_id,
            bos_token_id=bos_token_id,
            eos_token_id=eos_token_id,
            tie_word_embeddings=tie_word_embeddings,
            **kwargs,
        )


__all__ = ["LlamaConfig"]
相关标签
About Me
XD
Goals determine what you are going to be.
Category
标签云
BTC Google Baidu OpenCV VSCode Breakpoint Claude Windows WAN Base64 uwsgi Augmentation Hilton Logo tqdm Translation LeetCode Sklearn Vmess Diagram 财报 Jupyter PyTorch Domain Streamlit Cloudreve Vim Firewall 搞笑 腾讯云 C++ Quantize Django JSON Random Nginx GPTQ 顶会 继承 Safetensors 云服务器 UI 多进程 Knowledge Llama UNIX 报税 Food 域名 论文 Attention FP64 CLAP OCR git FP16 LLAMA ONNX Password RL LoRA Quantization Datetime torchinfo Hungarian LLM Pytorch CEIR YOLO Bitcoin Search Mixtral tar Website FastAPI VPN SQLite FlashAttention SQL CSV git-lfs GPT4 GIT Excel AI Video ms-swift Permission FP8 公式 Image2Text SPIE Ubuntu Qwen2 Ptyhon SVR icon Github RGB 论文速读 Bipartite Docker OpenAI Pickle 关于博主 Distillation 图标 XGBoost CTC Pillow Markdown LaTeX hf News HuggingFace QWEN PDB Freesound Interview Qwen CC Git Pandas Plotly Heatmap 强化学习 PDF Web 音频 Input Numpy SAM Animate Bin TensorRT FP32 RAR ModelScope DeepSeek COCO GoogLeNet v2ray Bert HaggingFace CAM Plate Jetson Tiktoken v0.dev diffusers 飞书 API网关 算法题 EXCEL Card transformers XML Clash Proxy DeepStream Algorithm NameSilo Agent NLP 版权 Land Rebuttal MD5 Conda 净利润 Paper scipy Anaconda 阿里云 ResNet-50 NLTK Python Linux WebCrawler Disk Tracking BeautifulSoup Miniforge Michelin Hotel uWSGI Template Dataset llama.cpp Statistics Data PyCharm logger Transformers Math Zip TSV PIP CV Crawler Magnet InvalidArgumentError IndexTTS2 Gemma printf Use TensorFlow GGML Review Paddle ChatGPT 证件照 API Jev 第一性原理 mmap Tensor BF16 TTS CUDA Harness Qwen2.5 图形思考法 VGG-16 Shortcut 多线程 签证 Color 递归学习法
站点统计

本站现有博文338篇,共被浏览977806次

本站已经建立2690天!

热门文章
文章归档
回到顶部