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

本站现有博文337篇,共被浏览961351次

本站已经建立2673天!

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