Transformers documentation

构建用于推理的兼容模型后端

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

构建用于推理的兼容模型后端

Transformers 模型与 vLLM 和 SGLang 等推理引擎兼容。您可以在任何地方使用相同的 Transformers 模型,而无需为每个推理引擎从头重新实现模型。只要模型支持下文所述的注意力后端接口,这也有助于处理引擎未原生重新实现的模型。

本指南将向您展示如何在 Transformers 中实现一个模型,使其能够作为任意推理引擎的后端。

模型实现

  1. 请遵循模型贡献指南或自定义模型贡献指南。该模型的目录中必须包含有效的config.json,并且配置中必须包含一个有效的auto_map字段,指向模型类。

  2. 使用 AttentionInterface 类来实现自定义和优化的注意力函数。该接口可解锁各推理引擎的性能特性。

    在定义注意力层时使用 ALL_ATTENTION_FUNCTIONS,并将 **kwargs 从基类 MyModel 传递到注意力层。在 PreTrainedModel 中将 _supports_attention_backend 设置为 True。

    展开以下代码以查看示例。

    modeling_my_model.py
    from transformers import PreTrainedModel
    from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
    from torch import nn
    
    class MyAttention(nn.Module):
    
        def forward(self, hidden_states, **kwargs):
            ...
            attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
            attn_output, attn_weights = attention_interface(
                self,
                query_states,
                key_states,
                value_states,
                **kwargs,
            )
            ...
    
    class MyModel(PreTrainedModel):
        _supports_attention_backend = True
  3. 通过向 PreTrainedConfig 添加以下键,启用可选的张量并行或流水线并行。

    • base_model_tp_plan 通过将完全限定的层名称模式映射到张量并行样式来启用 张量并行。仅支持 "colwise" 和 "rowwise" 分区策略。
    • base_model_pp_plan 通过将直接子层名称映射到字符串列表的元组来启用流水线并行。元组的第一个元素包含输入参数的名称。最后一个元素包含建模代码中层输出的变量名。

    展开以下代码以查看示例。

    configuration_my_model.py
    
    from transformers import PreTrainedConfig
    
    class MyConfig(PreTrainedConfig):
        base_model_tp_plan = {
            "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"]),
        }

多模态模型

多模态模型除了需要遵循视觉语言模型贡献指南外,还需要进行额外的更改。这些更改可确保多模态输入得到正确处理。

  1. ProcessorMixin 类必须包含 self.image_token 和 self.image_token_ids 属性。这些占位符 token 用于指示输入中图像的位置。相同的 token 会出现在输入提示的图像部分以及模型代码中,用于将图像特征分散到相应位置。

  2. ProcessorMixin 类必须包含一个 self._get_num_multimodal_tokens 方法。该方法用于计算给定尺寸的多模态输入所需的占位符 token 数量。它返回一个 MultiModalData 对象。<image> token 之间的占位符(例如行或列 token)不计入图像占位符。仅统计在建模代码中稍后会被图像特征替换的 token。

  3. ProcessorMixin 类必须检查 return_mm_token_type_ids 的值并返回 mm_token_type_ids。这用于指示每个位置是文本 token(0)、图像占位符 token(1)还是视频占位符 token(2)。多模态 token 类型 id 序列必须是连续的,相邻 token 之间不能有空隙。请将起始、结束、行和列 token 等特殊 token 视为占位符。

展开以下代码以查看示例。

modeling_my_multimodal_model.py
class MyMultimodalProcessor(ProcessorMixin):

    def __call__(self, images=None, text=None, **kwargs):
        if return_mm_token_type_ids:
            mm_token_type_ids = np.zeros_like(input_ids)
            mm_token_type_ids[input_ids == self.image_token_id] = 1
            text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist()
        return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)

    def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
        """
        Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
        Args:
            image_sizes (`list[list[int]]`, *optional*):
                The input sizes formatted as (height, width) per each image.
        Returns:
            `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
            input modalities, along with other useful data.
        """
        vision_data = {}
        if image_sizes is not None:
            num_image_tokens = [256] * len(image_sizes) # 256 placeholder tokens for each image always
            num_image_patches = [1] * len(image_sizes) # no patching, thus each image is processed as a single base image
            vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
        return MultiModalData(**vision_data)

资源

Update on GitHub