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

本站现有博文320篇,共被浏览756992

本站已经建立2421天!

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