用于推理的张量并行
张量并行将模型层切分为多个片段,使多个硬件加速器能够同时处理该层。这使得你可以运行超出单块 GPU 显存容量的模型,并获得更高的吞吐量。由于 GPU 在每一层都需要交换部分计算结果,因此你需要快速的节点内通信。
如果模型的 config 中定义了 base_model_tp_plan,则该模型支持张量并行。可以通过 supports_tp_plan 属性检查已加载的模型。
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
print(model.supports_tp_plan)本指南介绍了如何在 Transformers 中启用张量并行,以及可用的分区策略。
模型分区
在 DistributedConfig 中,使用 tp_size 配置张量并行设备的数量。
- 设置
DistributedConfig(tp_size=N)以使用模型预定义的计划。 - 手动定义
tp_plan,并将其与tp_size一起传递给 DistributedConfig。
您也可以设置 tp_plan="auto" 以显式请求预定义的计划。当省略 tp_size 且设置了 tp_plan 时,tp_size 将由 WORLD_SIZE 除以其他并行度得出。直接将 tp_plan 传递给 from_pretrained() 已被弃用,并将在 v5.18 中移除。
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, DistributedConfig
# model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct" # better to visualize all the possible strategies
distributed_config = DistributedConfig(tp_size=4)
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Meta-Llama-3-8B-Instruct",
dtype=torch.bfloat16,
distributed_config=distributed_config,
)
print(model.tp_plan)
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
prompt = "Can I help"
inputs = tokenizer(prompt, return_tensors="pt").input_ids.to(model.device)
# distributed run
outputs = model(inputs)使用 torchrun 启动推理脚本。每个 GPU 使用一个进程。
torchrun --nproc-per-node 4 demo.py
在 tp_plan 中为每一层定义张量并行计划,并通过 DistributedConfig 传入。下面的示例使用了列划分和行划分。有关其他支持的策略,请参阅 Partitioning strategies 部分。
手动分区需要对模型架构和策略交互有深入的理解。不恰当的分区选择会导致模型运行缓慢,甚至失败或产生错误结果。Ultra-Scale Playbook 详细解释了各种分区策略。
键是模块或参数名称,其中 * 代表层索引。无法识别的策略名称会引发 ValueError,其中列出了受支持的名称;此外,Transformers 会为未匹配到任何内容的计划规则以及未被任何规则覆盖的参数记录警告。
from transformers import AutoModelForCausalLM, DistributedConfig
tp_plan = {
"model.layers.*.self_attn.q_proj": "colwise",
"model.layers.*.self_attn.k_proj": "colwise",
"model.layers.*.self_attn.v_proj": "colwise",
"model.layers.*.self_attn.o_proj": "rowwise",
...
}
distributed_config = DistributedConfig(tp_size=4, tp_plan=tp_plan)
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Meta-Llama-3-8B-Instruct",
dtype="auto",
distributed_config=distributed_config,
)
print(model.tp_plan)分区策略
ALL_PARALLEL_STYLES 是在 distributed/parallel_utils.py 中定义的 ParallelInterface,它将计划中可用的每个策略名称映射到对应的已配置策略实例。你无需直接通过它来分片模型,但它提供了可用名称的权威列表。distributed/tensor_parallel.py 会将张量并行策略注册到其中:
ALL_PARALLEL_STYLES.register("embedding_rowwise", EmbeddingParallel(shard_dim=0))
ALL_PARALLEL_STYLES.register("embedding_colwise", EmbeddingParallel(shard_dim=1))
ALL_PARALLEL_STYLES.register("colwise_gather_output", ColwiseParallel(input_layouts=Replicate(), output_layouts=Replicate()))
ALL_PARALLEL_STYLES.register("colwise_rep", ColwiseParallel(input_layouts=Replicate(), output_layouts=Replicate()))
ALL_PARALLEL_STYLES.register("colwise", ColwiseParallel(input_layouts=Replicate(), output_layouts=Shard(-1)))
ALL_PARALLEL_STYLES.register("rowwise", RowwiseParallel(input_layouts=Shard(-1), output_layouts=Replicate()))
ALL_PARALLEL_STYLES.register("rowwise_split_input", RowwiseParallel(input_layouts=Replicate(), output_layouts=Replicate()))
ALL_PARALLEL_STYLES.register("rowwise_rep", RowwiseParallel(input_layouts=Replicate(), output_layouts=Replicate()))
ALL_PARALLEL_STYLES.register("packed_colwise", PackedColwiseParallel())
ALL_PARALLEL_STYLES.register("packed_rowwise", PackedRowwiseParallel())
ALL_PARALLEL_STYLES.register("sequence_parallel", SequenceParallel(use_local_output=True))
ALL_PARALLEL_STYLES.register("replicated_with_grad_allreduce", ReplicatedWithGradAllReduce())
ALL_PARALLEL_STYLES.register("mla_kv_a_proj", MlaKvAProjParallel())
ALL_PARALLEL_STYLES.register("all_reduce", AllReduceParallel())
ALL_PARALLEL_STYLES.register("moe_tp_experts", MoeExpertsParallel())
ALL_PARALLEL_STYLES.register("moe_identity_expert", MoeIdentityParallel())
ALL_PARALLEL_STYLES.register("local_params", LocalParamsParallel())该文件中的每个张量并行策略都是 TensorParallelLayer 的子类。专家并行策略(例如 ep_dispatch_experts)位于 distributed/expert_parallel.py 中,它们继承自 ExpertParallelLayer,拥有相同的钩子,并注册到同一个 ALL_PARALLEL_STYLES 中。最常用的两个策略是 ColwiseParallel 和 RowwiseParallel,它们接受 input_layouts 和 output_layouts 布局参数,这使得一个类能够覆盖多种计划名称。colwise 将其输出沿最后一个维度分片,以便后续的 rowwise 层使用;而 colwise_gather_output 则通过 all-gather 将其还原为完整的张量。
下表描述了每种策略。
| 策略 | 描述 |
|---|---|
ColwiseParallel | 在输出特征维度上对线性权重进行分片(对于 2D 的 nn.Linear 权重,即 Shard(0)),并对 1D 偏置进行分片。将输入重新分发到 Replicate(),然后将输出放置在 output_layouts。 |
RowwiseParallel | 在输入特征维度(Shard(-1))上对线性权重进行分片,并复制偏置,该偏置在归约之后相加。每个 rank 的前向传播产生一个 Partial() 输出,其中保存了求和结果中属于该 rank 的部分,随后 transform_output_post_forward 将其重新分配到 output_layouts。归约到 Replicate() 会触发 all-reduce,而归约到 Shard(1) 会触发 reduce-scatter。 |
EmbeddingParallel | 将 nn.Embedding 进行分片,其中 token id 是复制的。shard_dim=0(embedding_rowwise,通常的选择)对词表进行分片,并将每个 rank 的部分查找结果通过 all-reduce 合并为完整输出。shard_dim=1(embedding_colwise)对隐藏维度进行分片,并通过 all-gather 收集每个 rank 的输出切片。 |
PackedColwiseParallel | ColwiseParallel 的变体,用于融合权重,例如将 up_proj 和 gate_proj 打包到 gate_up_proj 中。当权重打包的层数不是两层时,请使用 split_factor。 |
PackedRowwiseParallel | 行级对应项,用于沿最后一个维度打包的权重。复制一维参数。 |
SequenceParallel | 复制模块的参数,并在 sequence_dim(默认为 1)上分片其输入。用于按 token 执行的归一化操作,例如 LayerNorm 和 RMSNorm。 |
ReplicatedWithGradAllReduce | 复制一个参数,但对其梯度执行 all-reduce 操作。这对于位于按列切分层和按行切分层之间、并沿分片轴进行归一化的归一化层是必需的,因为在这种情况下,每个 rank 只能看到自己的注意力头。 |
AllReduceParallel | 将模块的 Partial() 前向输出进行 all-reduce 操作,使其变为 Replicate()。请将其用作同步点,适用于计算以部分求和结束的模块。 |
MlaKvAProjParallel | 将 DeepSeek-V2 风格 MLA 注意力的 kv_a_proj_with_mqa 输出进行拆分,并对 RoPE 一半的梯度执行 all-reduce,从而绕过 kv_b_proj,避免保留部分梯度。需要在模型配置中提供 qk_rope_head_dim。 |
MoeExpertsParallel | Tensor 并行 MoE 专家。对专家输出执行前向 all-reduce,并为隐藏状态和路由权重添加反向 all-reduce。 |
MoeIdentityParallel | 将零专家或恒等专家的输入预先除以网格大小,以抵消 moe_tp_experts 在下游应用的全归约操作。 |
LocalParamsParallel | 使用其自身分片参数作为本地张量来运行模块的前向传播。请将其应用于拥有裸 nn.Parameter(例如 attention sinks)的模块,且该模块自身的计划条目会对其进行分片。 |
MoEParamShard | 在指定的放置策略上对 MoE 专家权重进行分片。支持 grouped_gemm 命名,其中 shards_expert_dim=True 还会将 module.num_experts 重写为每个 rank 的专家数量。 |
打包策略
权重打包将多个线性层合并为一个更大的层。PackedColwiseParallel 和 PackedRowwiseParallel 策略能够正确地对打包后的权重进行分片。而基础的 ColwiseParallel 或 RowwiseParallel 策略对打包权重的分片方式是不正确的。
以下示例将 up_proj 和 gate_proj 打包到单个 gate_up_proj 模块中,并要求使用 packed_rowwise 策略来分片 gate_up_proj。
class Llama4TextExperts(nn.Module):
...
self.gate_up_proj = nn.Parameter(torch.zeros(self.num_experts, self.hidden_size, 2 * self.expert_dim))在 forward 前向传播中使用批量矩阵乘法来计算 gate_up_proj 模块的输出。
def forward(self, hidden_states):
...
gate_up = torch.bmm(hidden_states, self.gate_up_proj) # Compute the output of the gate_up_proj module
gate, up = gate_up.chunk(2, dim=-1) # Split the output into gate and up普通的 Shard 会将该维度拆分为连续的块,因此某个 rank 会收到 gate 的尾部以及 up 的头部,而不是各自的一个切片。打包策略使用 _StridedShard 配合 split_factor(默认为 2)来交错执行拆分,使每个 rank 都能获得两半中对应的切片,从而确保分片后 chunk 仍然对齐。
自定义分区策略
在 distributed/tensor_parallel.py 中继承 TensorParallelLayer 以创建自定义的分区策略。只需重写你的策略所需的钩子,因为每个钩子都有一个空操作的默认实现。
| Hook | 目的 |
|---|---|
validate_param | 在加载任何权重之前,拒绝该策略无法分片的参数。 |
shard_param | 将一个参数替换为 DTensor 占位符,以便加载器知道哪个分片属于当前 rank。 |
transform_inputs_pre_forward | 将模块的输入重新分配到其 forward 所期望的布局。 |
context_around_forward | 将 forward 包裹在上下文管理器中,例如,以便向内核暴露本地张量。 |
transform_output_post_forward | 重新分配或缩减模块的输出。 |
should_use_local_tensors | 报告此模块的 forward 需要普通张量,而不是 DTensor。 |
install_forward | 直接替换 module.forward。仅当上述钩子不足以满足需求时才重写此方法,例如 ReplicatedWithGradAllReduce 重写它来注册反向传播钩子。 |
下面的示例逐步讲解了一个精简版的 ColwiseParallel。
继承
TensorParallelLayer并存储该策略所处理的 placements。基类未定义__init__,因此无需调用super()。class ColwiseParallel(TensorParallelLayer): def __init__(self, *, input_layouts=None, output_layouts=None, use_local_output: bool = True): self.input_layouts = input_layouts or Replicate() self.output_layouts = output_layouts if output_layouts is not None else Shard(-1) self.use_local_output = use_local_output实现
shard_param,将一个参数包装为DTensor占位符。它在 meta tensor 上运行,因此distribute_tensor仅构建元数据,不移动任何数据。由于目前尚不存在可从中分散的完整张量,请传入src_data_rank=None。def shard_param(self, module, param, mesh): meta = module._parameters.get(param) if meta is None: return # Output features live on dim 0 for a 2D weight and dim -1 for a 1D bias placement = Shard(1) if isinstance(module, torch.nn.Embedding) else Shard(meta.ndim - 2) module._parameters[param] = torch.nn.Parameter( distribute_tensor(meta, mesh, [placement], src_data_rank=None), requires_grad=meta.requires_grad, )实现输入和输出变换。
install_forward会在模块的原始 forward 前后调用它们,因此它们只需在布局之间移动张量。按列分区期望输入是复制的,并生成在最后一个维度上分片的输出。def transform_inputs_pre_forward(self, module, args, kwargs, mesh): x = args[0] if not isinstance(x, DTensor): x = DTensor.from_local(x, mesh, [self.input_layouts], run_check=False) if x.placements != (Replicate(),): x = x.redistribute(placements=[Replicate()]) return (x,) + args[1:], kwargs def transform_output_post_forward(self, module, output, mesh): if not isinstance(output, DTensor): output = DTensor.from_local(output, mesh, [Shard(-1)], run_check=False) if output.placements != (self.output_layouts,): output = output.redistribute(placements=[self.output_layouts]) return output.to_local() if self.use_local_output else output随附的
ColwiseParallel在此基础上增加了快速路径,可跳过针对普通nn.Linear推理以及需要本地张量的量化模块的DTensor往返操作。如果您的策略也需要类似的处理,请在复制前先阅读其源代码。注册该策略,以便
tp_plan可以引用其名称。注册过程接收一个策略实例,因此传递给__init__的 placements 会与该名称一起存储。请注意下方的()。import torch from transformers import AutoModelForCausalLM, DistributedConfig from transformers.distributed.parallel_utils import ALL_PARALLEL_STYLES ALL_PARALLEL_STYLES.register("colwise_custom", ColwiseParallel()) tp_plan = { "model.layers.*.self_attn.q_proj": "colwise_custom", ... } distributed_config = DistributedConfig(tp_size=4, tp_plan=tp_plan) model = AutoModelForCausalLM.from_pretrained( "meta-llama/Meta-Llama-3-8B-Instruct", dtype=torch.bfloat16, distributed_config=distributed_config, )
基准测试
张量并行可以显著加速推理,尤其是在大批量或长序列的情况下。
该图表展示了在 Llama 上,序列长度为 512 时单次前向传播的预期加速效果。

设计实现
Transformers 以与框架无关的方式实现了张量并行。它依赖于 torch.distributed 中的 DeviceMesh 和 DTensor,以提供一个简单且可扩展的接口。
DeviceMesh
DeviceMesh 创建一个由相互通信的设备组成的多维网格。不同的并行化策略需要不同的通信模式。创建带有多个子网格的 DeviceMesh 以处理这些模式。
import torch
from torch.distributed.device_mesh import init_device_mesh
# Create a 1D mesh of 4 accelerators
device_type = torch.accelerator.current_accelerator().type
device_mesh = init_device_mesh(device_type, (4,), mesh_dim_names=["tp"])大多数 torch.distributed 并行化策略都作用于网格本身或其子网格。网格会自动处理通信模式。
DTensor
DTensor(分布式张量)在常规张量操作之上处理分布式逻辑。在张量并行下,模型权重以 DTensor 的形式存储,这使得策略可以将通信描述为布局的变更,而非显式的集合通信。
placements 属性用于告知 PyTorch 张量在 DeviceMesh 中的各个设备上的布局方式。它接受以下值:
Shard(dimension)会在其构建时所在的DeviceMesh上,沿指定维度对DTensor进行分片。按列分片会对权重的输出特征维度以及偏置的唯一维度进行分片。weight = DTensor.from_local(weight, device_mesh["tp"], placements=[Shard(0)]) # Shard the output features bias = DTensor.from_local(bias, device_mesh["tp"], placements=[Shard(-1)]) # Shard the ONLY dimension行式分区对输入特征维度进行分片,并复制偏置,因为偏置是在归约之后一次性添加的,而不是在每个 rank 上分别添加。
weight = DTensor.from_local(weight, device_mesh["tp"], placements=[Shard(-1)]) # Shard the input features bias = DTensor.from_local(bias, device_mesh["tp"], placements=[Replicate()]) # Replicate bias across all GPUsReplicate()会在DeviceMesh上复制DTensor,在每个设备上创建该张量的完整副本。Partial()将张量标记为待归约状态。行并行层的 forward 输出为Partial(),将其重新分布为Replicate()时会触发 all-reduce。
资源
有关张量并行的更多详细信息,请参阅Ultra-Scale Playbook部分。
如果您使用的是混合专家(MoE)模型,请查阅专家并行指南。这些模型支持张量并行和专家并行。
阅读Transformers 中的张量并行(TP):5 分钟入门博客文章,快速了解张量并行,并学习列并行和行并行配置之间的区别。
请参阅 Tensor parallelism 训练指南,了解如何在训练场景中使用它。