huggingface/transformers · #48848

[`distributed`] Add a new parallel plan for unit sharding

ArthurZucker · merged Nov 26, 20268 files · 414 + / 99 −
src/transformers/core_model_loading.py4 + / 5 −
@@ -1940,11 +1940,10 @@ def convert_and_load_state_dict_in_model(             if is_dtensor(empty_param):                 sharding_op = DtensorShardOperation(empty_param) -            # Some parameters are so large (qwen4_exp ple_embedding is about ~95 GiB) that we cannot afford to perform the Operations-            # directly on the device, as it will completely blow up the memory during the ops memory spike. So defer to "cpu", then-            # accelerate will take care of putting back on correct device after loading-            # Note that we only do it with `device_map` but not with `tp_plan`, as tp will perform local sharding before, so memory-            # spike during conversion ops should be fine+            # Very large params (e.g. qwen4_exp ple_embedding ~95 GiB) would blow up memory if sharded+            # on-device, so defer to "cpu"; accelerate moves them back afterwards. Only for `device_map`,+            # not `tp_plan`, since tp shards locally first and the conversion spike is small.+            # TODO: move comment to the force_cpu doc, the flow is broken.             if sharding_op is None and isinstance(mapping, WeightConverter) and mapping.force_cpu:                 param_device = "cpu" 
src/transformers/distributed/parallel_utils.py24 + / 12 −
@@ -101,10 +101,10 @@ class _AllReduceForward(torch.autograd.Function):         """Allreduce-sum forward, identity backward."""          @staticmethod-        def forward(ctx, x, process_group):+        def forward(ctx, tensor, process_group):             if dist.get_world_size(process_group) > 1:-                dist.all_reduce(x, group=process_group)-            return x+                dist.all_reduce(tensor, group=process_group)+            return tensor          @staticmethod         def backward(ctx, grad):@@ -118,34 +118,46 @@ class _AllReduceBackward(torch.autograd.Function):         its expert shard). We need to sum the partial gradients without dividing by         world_size, which is what DTensor's Replicate backward does incorrectly. -        `apply` returns `x` as is when no gradient can flow: at inference the per-call overhead of an+        `apply` returns `tensor` as is when no gradient can flow: at inference the per-call overhead of an         `autograd.Function` compounds across layers, e.g. in eager decode.         """          @classmethod-        def apply(cls, x, process_group):-            if torch.is_grad_enabled() and x.requires_grad:-                return super().apply(x, process_group)-            return x+        def apply(cls, tensor, process_group):+            if torch.is_grad_enabled() and tensor.requires_grad:+                return super().apply(tensor, process_group)+            return tensor          @staticmethod-        def forward(ctx, x, process_group):+        def forward(ctx, tensor, process_group):             ctx.process_group = process_group-            return x+            return tensor          @staticmethod         def backward(ctx, grad):             grad = grad.contiguous()             dist.all_reduce(grad, group=ctx.process_group)             return grad, None +    class _ScaleBackward(torch.autograd.Function):+        """Identity forward, gradient multiplied by `scale` in backward."""++        @staticmethod+        def forward(ctx, tensor, scale):+            ctx.scale = scale+            return tensor.view_as(tensor)++        @staticmethod+        def backward(ctx, grad):+            return grad * ctx.scale, None+     class _WaitTensor(torch.autograd.Function):         """Wait on a functional collective's result, identity backward (`wait_tensor` has no autograd kernel before         torch 2.11)."""          @staticmethod-        def forward(ctx, x):-            return wait_tensor(x)+        def forward(ctx, tensor):+            return wait_tensor(tensor)          @staticmethod         def backward(ctx, grad):
src/transformers/distributed/sharding_utils.py4 + / 1 −
@@ -73,6 +73,10 @@ class DtensorShardOperation:     | TP + FSDP, same tensor dim (fused/interleaved TP) | [_StridedShard(d, sf=tp_size), Shard(d)]     |     | TP + FSDP, different dims                         | [Shard(d1), Shard(d2)]                       | +    There is an additional case when we have to force non-empty chunks. This will transform any Shard(n) placements+    into a [Shard(n), Replicate()].+    This is intended to solved cases where you have 6 key value heads and 8 process -> 2 process shard(n) replicated 4 times.+     Loading (this class)     --------------------     During from_pretrained, each rank looks up every tensor key, but does not load the weight bytes yet (safetensors get_slice).@@ -148,7 +152,6 @@ def shard_tensor(                         intervals = self._compute_contiguous_slice(intervals, rank, world_size)                 intervals_by_dim[dim_idx] = intervals -            # finally fetch from the disk only the slices             # finally fetch from the disk only the slices             if has_strided_shard:                 # Multi-interval dim: read each piece separately, then concatenate.
src/transformers/distributed/tensor_parallel.py194 + / 72 −
@@ -47,7 +47,7 @@     from torch.distributed.tensor import DTensor, Partial, Replicate, Shard, distribute_tensor     from torch.distributed.tensor.placement_types import _StridedShard -    from .parallel_utils import _AllReduceBackward, _AllReduceForward+    from .parallel_utils import _AllReduceBackward, _AllReduceForward, _ScaleBackward   def verify_tp_plan(expected_keys: list[str], tp_plan: dict[str, str] | None):@@ -102,7 +102,7 @@ def validate_param(self, module, param, mesh, parameter_name=None):         """Validate a parameter before applying this TP style."""         pass -    def shard_param(self, module, param, mesh):+    def shard_param(self, module, param, mesh, *, config=None, mesh_manager=None):         """Wrap ONE parameter as a DTensor placeholder. Default: no-op."""         pass @@ -114,7 +114,7 @@ def context_around_forward(self, module, mesh):             return _use_local_dtensor_params(module)         return contextlib.nullcontext() -    def transform_output_post_forward(self, module, output, mesh):+    def transform_output_post_forward(self, module, output, mesh, config=None):         return output      @staticmethod@@ -126,15 +126,15 @@ def _from_local_last_dim_shard(local, mesh, size):             local, mesh, [Shard(-1)], run_check=False, shape=shape, stride=torch.empty(shape, device="meta").stride()         ) -    def install_forward(self, module, mesh):+    def install_forward(self, module, mesh, *, config=None, mesh_manager=None):         """Install pre / around / post transforms by replacing module.forward."""         original_forward = module.forward          def tp_forward(*args, **kwargs):             args, kwargs = self.transform_inputs_pre_forward(module, args, kwargs, mesh)             with self.context_around_forward(module, mesh):                 output = original_forward(*args, **kwargs)-            return self.transform_output_post_forward(module, output, mesh)+            return self.transform_output_post_forward(module, output, mesh, config=config)          module.forward = tp_forward         return module@@ -155,12 +155,12 @@ def should_use_local_tensors(self, module):         uses_local_inference_kernel = isinstance(module, torch.nn.Linear) and not torch.is_grad_enabled()         return use_local_quantized_path or uses_local_inference_kernel -    def install_forward(self, module, mesh):+    def install_forward(self, module, mesh, *, config=None, mesh_manager=None):         if not hasattr(module, "out_features"):             raise ValueError(f"{type(module).__name__} has no `out_features`: colwise shards linear layers.")-        return super().install_forward(module, mesh)+        return super().install_forward(module, mesh, config=config, mesh_manager=mesh_manager) -    def shard_param(self, module, param, mesh):+    def shard_param(self, module, param, mesh, *, config=None, mesh_manager=None):         meta = module._parameters.get(param)         if meta is None:             return@@ -171,8 +171,8 @@ def shard_param(self, module, param, mesh):         )      def transform_inputs_pre_forward(self, module, args, kwargs, mesh):-        x = args[0]-        is_local_input = not isinstance(x, DTensor)+        input_tensor = args[0]+        is_local_input = not isinstance(input_tensor, DTensor)          # regular Linear inference fast path: the input is already replicated, the         # local weight owns a shard of the output features, and no backward is needed.@@ -184,19 +184,19 @@ def transform_inputs_pre_forward(self, module, args, kwargs, mesh):         # input-gradient contributions explicitly.         if is_local_input and getattr(module, "_hf_quantized_needs_local_tp", False):             process_group = mesh.get_group() if mesh.ndim == 1 else mesh.get_group("tp")-            x = _AllReduceBackward.apply(x, process_group)-            return (x,) + args[1:], kwargs+            input_tensor = _AllReduceBackward.apply(input_tensor, process_group)+            return (input_tensor,) + args[1:], kwargs          # DTensor path: handle regular training and layout redistribution.         if is_local_input:-            x = DTensor.from_local(x, mesh, [self.input_layouts], run_check=False)-        if x.placements != (Replicate(),):-            x = x.redistribute(placements=[Replicate()])+            input_tensor = DTensor.from_local(input_tensor, mesh, [self.input_layouts], run_check=False)+        if input_tensor.placements != (Replicate(),):+            input_tensor = input_tensor.redistribute(placements=[Replicate()])         if self.should_use_local_tensors(module):-            x = x.to_local(grad_placements=[Partial()])-        return (x,) + args[1:], kwargs+            input_tensor = input_tensor.to_local(grad_placements=[Partial()])+        return (input_tensor,) + args[1:], kwargs -    def transform_output_post_forward(self, module, output, mesh):+    def transform_output_post_forward(self, module, output, mesh, config=None):         # The local forward produced this rank's shard of the output features (last dim).         output_is_local_shard = (             not isinstance(output, DTensor)@@ -213,6 +213,71 @@ def transform_output_post_forward(self, module, output, mesh):         return output.to_local() if self.use_local_output else output  +class UnitColwiseParallel(ColwiseParallel):+    """This forces all ranks to own at least 1 unit of the tensor.+    It is designed to be used on `query/key/value` layers when running TP.+    For `query = nn.Linear(hidden_dim, head_dim * num_heads)` you can't divide the second dimension blindly by the world size as the attention REQUIRES to split per-head. You cannot split 2 heads of dim 64 into 4 GPUs by just separating into 4 x 32. This would mix the heads.++    The unit colwise handles 2 cases:+    - Less heads than world size: 2 heads, 4 process -> we replicate the heads.+          Rank: | 0 |  1 |  2 | 3 |+    This gives: |h0 | h0 | h1 | h1|++    - More heads than world size: 6 heads, 4 process -> we also replicate the heads.+          Rank: |   0  |   1  |   2  |   3  |+    This gives: |h0h1h2|h0h1h2|h3h4h5|h3h4h5|++    We need to have [Shard(0), Replicate()] .++    TODO: this only handles head-aligned Linear weights. Extra per-head parameters attached directly to+    the attention module, such as Beam's `gate_bias` or GraniteSWA's `sinks`, are not supported yet.+    A clean fix needs a dedicated style instead of treating every sharded parameter as a Linear weight.+    """++    def shard_param(self, module, param, mesh, *, config=None, mesh_manager=None):+        meta = module._parameters.get(param)+        if meta is None:+            return+        weight = module._parameters["weight"]+        head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads+        module._unit_mesh = mesh_manager.get_unit_mesh(weight.shape[0] // head_dim)+        module._parameters[param] = torch.nn.Parameter(+            distribute_tensor(meta, module._unit_mesh, [Shard(meta.ndim - 2), Replicate()], src_data_rank=None),+            requires_grad=meta.requires_grad,+        )++    def transform_inputs_pre_forward(self, module, args, kwargs, mesh):+        # The inputs are on a different mesh. We HAVE to swap the meshes as cross mesh comms+        # do not work.+        # Swapping meshes is metadata only while the tensor is replicated, so gather first.+        input_tensor = args[0]+        if isinstance(input_tensor, DTensor):+            replicated = [Replicate()] * input_tensor.device_mesh.ndim+            if input_tensor.placements != tuple(replicated):+                input_tensor = input_tensor.redistribute(placements=replicated)+            input_tensor = input_tensor.to_local()+        if not self.should_use_local_tensors(module):+            # The input is replicated on every rank by construction, no need to check it.+            input_tensor = DTensor.from_local(+                input_tensor, module._unit_mesh, [Replicate(), Replicate()], run_check=False+            )+        return (input_tensor,) + args[1:], kwargs++    def transform_output_post_forward(self, module, output, mesh, config=None):+        # Training path: already on the unit mesh as [Shard(-1), Replicate()], don't move it to the TP mesh.+        if isinstance(output, DTensor):+            local = output.to_local()+            if module._unit_mesh.size(1) > 1:+                # A replicated head only gets the gradient of the query heads on its rank (GQA): sum the replicas'.+                # `UnitRowwiseParallel` scales them so query heads replicated on several ranks aren't counted twice.+                local = _AllReduceBackward.apply(local, module._unit_mesh.get_group(1))+            if self.use_local_output:+                return local+            return DTensor.from_local(local, module._unit_mesh, output.placements, run_check=False)+        # Inference path: the local kernel output is this rank's heads, the parent handles it.+        return super().transform_output_post_forward(module, output, mesh)++ class RowwiseParallel(TensorParallelLayer):     """Row-wise for linear layers: weight → Shard(1), bias → Replicate; input sharded on the last dim. @@ -231,7 +296,7 @@ def should_use_local_tensors(self, module):         uses_local_inference_kernel = isinstance(module, torch.nn.Linear) and not torch.is_grad_enabled()         return use_local_quantized_path or uses_local_inference_kernel -    def shard_param(self, module, param, mesh):+    def shard_param(self, module, param, mesh, *, config=None, mesh_manager=None):         meta = module._parameters.get(param)         if meta is None:             return@@ -242,30 +307,34 @@ def shard_param(self, module, param, mesh):             requires_grad=meta.requires_grad,         ) -    def install_forward(self, module, mesh):+    def install_forward(self, module, mesh, *, config=None, mesh_manager=None):         if not hasattr(module, "in_features"):             raise ValueError(f"{type(module).__name__} has no `in_features`: rowwise shards linear layers.")-        return super().install_forward(module, mesh)+        return super().install_forward(module, mesh, config=config, mesh_manager=mesh_manager)      def transform_inputs_pre_forward(self, module, args, kwargs, mesh):         desired = Shard(-1)-        x = args[0]+        input_tensor = args[0]         # A local kernel can use a plain input when the previous layer already split it.-        #  avoid a redundant Tensor -> DTensor -> Tensor round trip.+        # avoid a redundant Tensor -> DTensor -> Tensor round trip.         input_has_desired_layout = self.input_layouts == desired-        if self.should_use_local_tensors(module) and input_has_desired_layout and not isinstance(x, DTensor):+        if (+            self.should_use_local_tensors(module)+            and input_has_desired_layout+            and not isinstance(input_tensor, DTensor)+        ):             return args, kwargs-        if not isinstance(x, DTensor):+        if not isinstance(input_tensor, DTensor):             if isinstance(self.input_layouts, Shard):                 # the input is this rank's slice of the module's declared `in_features`-                x = self._from_local_last_dim_shard(x, mesh, module.in_features)+                input_tensor = self._from_local_last_dim_shard(input_tensor, mesh, module.in_features)             else:-                x = DTensor.from_local(x, mesh, [self.input_layouts], run_check=False)-        if x.placements != (desired,):-            x = x.redistribute(placements=[desired])+                input_tensor = DTensor.from_local(input_tensor, mesh, [self.input_layouts], run_check=False)+        if input_tensor.placements != (desired,):+            input_tensor = input_tensor.redistribute(placements=[desired])         if self.should_use_local_tensors(module):-            x = x.to_local()-        return (x,) + args[1:], kwargs+            input_tensor = input_tensor.to_local()+        return (input_tensor,) + args[1:], kwargs      @contextlib.contextmanager     def context_around_forward(self, module, mesh):@@ -285,7 +354,7 @@ def context_around_forward(self, module, mesh):                 if bias is not None:                     module._parameters["bias"] = bias -    def transform_output_post_forward(self, module, output, mesh):+    def transform_output_post_forward(self, module, output, mesh, config=None):         use_local_inference_path = (             isinstance(module, torch.nn.Linear)             and not isinstance(output, DTensor)@@ -311,6 +380,55 @@ def transform_output_post_forward(self, module, output, mesh):         return output  +class UnitRowwiseParallel(RowwiseParallel):+    """Row-wise for the attention output projection: the weight is split by head like `UnitColwiseParallel`, and each+    rank keeps whole heads. The replica axis recomputes the same heads, so their gradients are scaled by `1/replicas`+    here and summed back by `UnitColwiseParallel`'s `_AllReduceBackward`."""++    def shard_param(self, module, param, mesh, *, config=None, mesh_manager=None):+        meta = module._parameters.get(param)+        if meta is None:+            return+        weight = module._parameters["weight"]+        head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads+        module._unit_mesh = mesh_manager.get_unit_mesh(weight.shape[-1] // head_dim)+        # bias is added once after the reduce, so it stays replicated+        placements = [Replicate(), Replicate()] if param == "bias" else [Shard(meta.ndim - 1), Replicate()]+        module._parameters[param] = torch.nn.Parameter(+            distribute_tensor(meta, module._unit_mesh, placements, src_data_rank=None),+            requires_grad=meta.requires_grad,+        )++    def transform_inputs_pre_forward(self, module, args, kwargs, mesh):+        input_tensor = args[0]+        if isinstance(input_tensor, DTensor):+            input_tensor = input_tensor.to_local()+        if not self.should_use_local_tensors(module):+            if (replicas := module._unit_mesh.size(1)) > 1:+                # Scale gradients by 1/replicas; UnitColwiseParallel all-reduces them back.+                input_tensor = _ScaleBackward.apply(input_tensor, 1 / replicas)+            input_tensor = DTensor.from_local(+                input_tensor, module._unit_mesh, [Shard(-1), Replicate()], run_check=False+            )+        return (input_tensor,) + args[1:], kwargs++    def transform_output_post_forward(self, module, output, mesh, config=None):+        # Reduce over the unit axis only: reducing over the whole TP mesh, like the parent, would also sum the replicas.+        if not isinstance(output, DTensor):+            # Inference path: local all-reduce over this rank's unit group, then add the bias once.+            if module._unit_mesh.size(0) > 1:+                dist.all_reduce(output, group=module._unit_mesh.get_group(0))+            if (bias := module._parameters.get("bias")) is not None:+                output = output + (bias.to_local() if isinstance(bias, DTensor) else bias)+            if not self.use_local_output:+                output = DTensor.from_local(output, mesh, [Replicate()], run_check=False)+            return output+        # Training path: resolve the Partial (and its backward) while the unit axis still exists,+        # then move the replicated result back to the TP mesh (metadata only).+        local = output.redistribute(placements=[Replicate(), Replicate()]).to_local()+        return local if self.use_local_output else DTensor.from_local(local, mesh, [Replicate()], run_check=False)++ class EmbeddingParallel(TensorParallelLayer):     """Embedding with the token ids replicated on every rank. `shard_dim=0` is vocab-parallel: each rank holds a slice     of the vocabulary, and the ranks' partial lookups are summed. `shard_dim=1` shards the hidden dim: each rank looks@@ -323,7 +441,7 @@ def __init__(self, *, shard_dim: int = 0, use_local_output: bool = True):     def should_use_local_tensors(self, module):         return getattr(module, "_hf_quantized_needs_local_tp", False) -    def shard_param(self, module, param, mesh):+    def shard_param(self, module, param, mesh, *, config=None, mesh_manager=None):         meta = module._parameters.get(param)         if meta is None:             return@@ -333,18 +451,18 @@ def shard_param(self, module, param, mesh):         )      def transform_inputs_pre_forward(self, module, args, kwargs, mesh):-        x = args[0]-        if self.should_use_local_tensors(module) and not isinstance(x, DTensor):+        input_tensor = args[0]+        if self.should_use_local_tensors(module) and not isinstance(input_tensor, DTensor):             return args, kwargs-        if not isinstance(x, DTensor):-            x = DTensor.from_local(x, mesh, [Replicate()], run_check=False)-        elif x.placements != (Replicate(),):-            x = x.redistribute(placements=[Replicate()])+        if not isinstance(input_tensor, DTensor):+            input_tensor = DTensor.from_local(input_tensor, mesh, [Replicate()], run_check=False)+        elif input_tensor.placements != (Replicate(),):+            input_tensor = input_tensor.redistribute(placements=[Replicate()])         if self.should_use_local_tensors(module):-            x = x.to_local()-        return (x,) + args[1:], kwargs+            input_tensor = input_tensor.to_local()+        return (input_tensor,) + args[1:], kwargs -    def transform_output_post_forward(self, module, output, mesh):+    def transform_output_post_forward(self, module, output, mesh, config=None):         if not isinstance(output, DTensor):             if self.shard_dim == 0:                 output = DTensor.from_local(output, mesh, [Partial()], run_check=False)@@ -365,7 +483,7 @@ class ReplicatedWithGradAllReduce(TensorParallelLayer):     summed across the mesh.     """ -    def install_forward(self, module, mesh):+    def install_forward(self, module, mesh, *, config=None, mesh_manager=None):         original_forward = module.forward         # Module-level backward hooks create graph breaks when using torch.compile but not with parameter-level         # hooks. We can't add them during setup time as the parameters are empty placeholders that are going to be@@ -391,7 +509,7 @@ def tp_forward(*args, **kwargs): class AllReduceParallel(TensorParallelLayer):     """All-reduce a module's partial forward output across the TP mesh.""" -    def transform_output_post_forward(self, module, output, mesh):+    def transform_output_post_forward(self, module, output, mesh, config=None):         if output is None:             return None         if not isinstance(output, DTensor):@@ -429,14 +547,14 @@ class MlaKvAProjParallel(TensorParallelLayer):     However, k_rot goes straight to attention, never touches kv_b_proj. So we need to average gradient across all ranks otherwise we only get gradient for one rank (partial gradient).     """ -    def transform_output_post_forward(self, module, output, mesh):-        if not hasattr(module.config, "qk_rope_head_dim"):+    def transform_output_post_forward(self, module, output, mesh, config=None):+        if not hasattr(config, "qk_rope_head_dim"):             raise AttributeError(                 f"Config for {type(module).__name__} does not have `qk_rope_head_dim`. "                 "MlaKvAProjParallel requires `qk_rope_head_dim` to be defined in the model config. "                 "Please add it to the model's config or update the TP plan mapping."             )-        rope_dim = module.config.qk_rope_head_dim+        rope_dim = config.qk_rope_head_dim         pass_output, rope_output = output.split([output.shape[-1] - rope_dim, rope_dim], dim=-1)         rope_output = _AllReduceBackward.apply(rope_output, mesh.get_group())         return torch.cat([pass_output, rope_output], dim=-1)@@ -447,24 +565,24 @@ def __init__(self, *, sequence_dim: int = 1, use_local_output: bool = True):         self.sequence_dim = sequence_dim         self.use_local_output = use_local_output -    def install_forward(self, module, mesh):+    def install_forward(self, module, mesh, *, config=None, mesh_manager=None):         # Replicate the module's params (LayerNorm/RMSNorm ones-init → from_local is safe).         for p_name, p in list(module.named_parameters(recurse=False)):             module.register_parameter(                 p_name, torch.nn.Parameter(DTensor.from_local(p, mesh, [Replicate()], run_check=False))             )-        return super().install_forward(module, mesh)+        return super().install_forward(module, mesh, config=config, mesh_manager=mesh_manager)      def transform_inputs_pre_forward(self, module, args, kwargs, mesh):-        seq = Shard(self.sequence_dim)-        x = args[0]-        if not isinstance(x, DTensor):-            x = DTensor.from_local(x, mesh, [seq], run_check=False)-        elif x.placements != (seq,):-            x = x.redistribute(placements=[seq])-        return (x,) + args[1:], kwargs--    def transform_output_post_forward(self, module, output, mesh):+        sequence_layout = Shard(self.sequence_dim)+        input_tensor = args[0]+        if not isinstance(input_tensor, DTensor):+            input_tensor = DTensor.from_local(input_tensor, mesh, [sequence_layout], run_check=False)+        elif input_tensor.placements != (sequence_layout,):+            input_tensor = input_tensor.redistribute(placements=[sequence_layout])+        return (input_tensor,) + args[1:], kwargs++    def transform_output_post_forward(self, module, output, mesh, config=None):         if isinstance(output, DTensor):             return output.to_local() if self.use_local_output else output         return output@@ -495,7 +613,7 @@ def _packed_output_shard_dim(self, param_ndim: int) -> int:             return -1         return param_ndim - 2 -    def shard_param(self, module, param, mesh):+    def shard_param(self, module, param, mesh, *, config=None, mesh_manager=None):         meta = module._parameters.get(param)         if meta is None:             return@@ -524,7 +642,7 @@ def transform_inputs_pre_forward(self, module, args, kwargs, mesh):         input_tensor = input_tensor.to_local(grad_placements=[Partial()])         return (input_tensor,) + args[1:], kwargs -    def transform_output_post_forward(self, module, output, mesh):+    def transform_output_post_forward(self, module, output, mesh, config=None):         if output is None or self.use_local_output:             return output         return DTensor.from_local(@@ -538,7 +656,7 @@ class PackedRowwiseParallel(TensorParallelLayer):     def __init__(self, *, split_factor: int = 2):         self.split_factor = split_factor -    def shard_param(self, module, param, mesh):+    def shard_param(self, module, param, mesh, *, config=None, mesh_manager=None):         meta = module._parameters.get(param)         if meta is None:             return@@ -569,7 +687,7 @@ def transform_inputs_pre_forward(self, module, args, kwargs, mesh):          return (hidden_states, *routing_args), kwargs -    def transform_output_post_forward(self, module, output, mesh):+    def transform_output_post_forward(self, module, output, mesh, config=None):         if output is None:             return None         # each rank ran its shard of every expert: sum the partial outputs@@ -593,7 +711,13 @@ def should_use_local_tensors(self, module):     )     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(+        "unit_colwise", UnitColwiseParallel(input_layouts=Replicate(), output_layouts=Shard(-1))+    )     ALL_PARALLEL_STYLES.register("rowwise", RowwiseParallel(input_layouts=Shard(-1), output_layouts=Replicate()))+    ALL_PARALLEL_STYLES.register(+        "unit_rowwise", UnitRowwiseParallel(input_layouts=Shard(-1), output_layouts=Replicate())+    )     ALL_PARALLEL_STYLES.register(         "rowwise_split_input", RowwiseParallel(input_layouts=Replicate(), output_layouts=Replicate())     )@@ -640,20 +764,18 @@ def apply_tensor_parallelism(model: nn.Module, tp_mesh: DeviceMesh, tp_plan: dic             '`DistributedConfig(ep_implementation="all_reduce")`.'         ) +    config = model.config.get_text_config()+    mesh_manager = model._mesh_manager     for name, style_name in tp_plan.items():         style = ALL_PARALLEL_STYLES[style_name]-        if name in parameters:-            module_name, _, param_name = name.rpartition(".")-            module = modules[module_name]+        is_param = name in parameters+        module_name, _, param_name = name.rpartition(".") if is_param else (name, "", "")+        module = modules[module_name]+        if is_param:             style.validate_param(module, param_name, tp_mesh, parameter_name=name)-            style.shard_param(module, param_name, tp_mesh)+            style.shard_param(module, param_name, tp_mesh, config=config, mesh_manager=mesh_manager)         else:-            module = modules[name]-            if style_name == "mla_kv_a_proj":-                # MLA needs to know the qk_rope_head_dim to split the projection output into KV and RoPE parts.-                # TODO: Store qk_rope_head_dim on MLA projection modules when the models initialize them.-                module.config = model.config.get_text_config()-            style.install_forward(module, tp_mesh)+            style.install_forward(module, tp_mesh, config=config, mesh_manager=mesh_manager)         module._is_hooked = True      return model
src/transformers/distributed/utils.py19 + / 0 −
@@ -204,13 +204,32 @@ class TransformersDeviceMesh:     def __init__(self, dense_mesh: DeviceMesh, expert_mesh: DeviceMesh):         self._dense_mesh = dense_mesh         self._expert_mesh = expert_mesh+        self._unit_meshes: dict[int, DeviceMesh] = {}      def get_mesh(self, dims: str | tuple[str, ...]) -> DeviceMesh:         """Select expert axes for `ep`/`efsdp`, otherwise dense axes; DeviceMesh handles slicing."""         dims = (dims,) if isinstance(dims, str) else dims         mesh = self._expert_mesh if "ep" in dims or "efsdp" in dims else self._dense_mesh         return mesh[dims] +    def get_unit_mesh(self, unit_number: int) -> DeviceMesh:+        """+        A 2-D unit-view of the `tp` mesh. We reshape it as (units, replicas), so every rank owns whole units+        (e.g. attention heads). Built once per number of groups: projections that agree on it share the mesh+        and its process groups.+        """+        from torch.distributed.device_mesh import DeviceMesh++        tp_mesh = self.get_mesh("tp")+        groups = math.gcd(unit_number, tp_mesh.size())+        if groups not in self._unit_meshes:+            self._unit_meshes[groups] = DeviceMesh(+                device_type=tp_mesh.device_type,+                mesh=tp_mesh.mesh.reshape(groups, tp_mesh.size() // groups),+                mesh_dim_names=["tp", "unit_replicate"],+            )+        return self._unit_meshes[groups]+  # Retained for the legacy transformers.integrations.tensor_parallel API. def initialize_tensor_parallelism(
tests/distributed_testing_utils.py3 + / 0 −
@@ -102,6 +102,9 @@ def _worker_main(rank, world_size, master_port, backend, pipe):         for group in list(_world.pg_map):             if group is not GroupMember.WORLD:                 dist.destroy_process_group(group)+        # DTensor caches shardings with meshes compared by value: a new mesh would get the destroyed groups back+        if hasattr(torch._C, "_clear_DTensor_sharding_propagator_cache"):+            torch._C._clear_DTensor_sharding_propagator_cache()         set_seed(42)         try:             func(rank, *args, **kwargs)
tests/tensor_parallel/test_tensor_parallel.py113 + / 1 −
@@ -11,14 +11,15 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.+import math import tempfile from unittest.mock import patch  import torch import torch.distributed as dist from parameterized import parameterized -from transformers import AutoModelForCausalLM, LlamaConfig, LlamaForCausalLM+from transformers import AutoModelForCausalLM, LlamaConfig, LlamaForCausalLM, LlamaModel from transformers.distributed import DistributedConfig, tensor_parallel from transformers.distributed.sharding_utils import DtensorShardOperation from transformers.distributed.tensor_parallel import (@@ -29,6 +30,7 @@     RowwiseParallel,     get_kv_heads_per_rank, )+from transformers.distributed.utils import TransformersDeviceMesh from transformers.testing_utils import TestCasePlus, is_tensor_parallel_test  from ..distributed_testing_utils import run_distributed@@ -375,6 +377,116 @@ def test_sharding_does_not_create_unrelated_module_attributes(self):   @is_tensor_parallel_test+class TestUnitParallel(TestCasePlus):+    """`unit_colwise`/`unit_rowwise` must give every rank whole heads, and never split one."""++    HEAD_DIM = 8+    HIDDEN = 64++    class FakeMesh:+        """Enough of a DeviceMesh for `get_unit_mesh` to reshape, with no process groups."""++        def __init__(self, ranks, rank=0):+            self.mesh, self.rank = ranks, rank+            self.device_type, self.mesh_dim_names = "cpu", None+            self.ndim = ranks.ndim++        def size(self):+            return int(self.mesh.numel())++        def get_local_rank(self):+            return self.rank++        def __getitem__(self, dims):+            return self++    def _manager(self, world_size):+        """A `TransformersDeviceMesh` whose `tp` mesh is fake, and whose unit meshes are fake too."""+        return TransformersDeviceMesh(self.FakeMesh(torch.arange(world_size)), None)++    def _fake_device_mesh(self):+        return patch(+            "torch.distributed.device_mesh.DeviceMesh",+            lambda device_type, mesh, mesh_dim_names=None: self.FakeMesh(mesh),+        )++    def _attention(self, num_heads, num_key_value_heads):+        """A real attention layer from a one-layer Llama, plus the config the unit styles read."""+        config = LlamaConfig(+            hidden_size=num_heads * self.HEAD_DIM,+            intermediate_size=2 * num_heads * self.HEAD_DIM,+            num_hidden_layers=1,+            num_attention_heads=num_heads,+            num_key_value_heads=num_key_value_heads,+            head_dim=self.HEAD_DIM,+            vocab_size=32,+        )+        attention = LlamaModel(config).layers[0].self_attn+        return attention, config++    def _shard(self, module, name, style, manager, config):+        """Shard one projection, returning the placements it asked for."""+        with (+            self._fake_device_mesh(),+            patch.object(+                tensor_parallel, "distribute_tensor", side_effect=lambda tensor, *a, **kw: tensor+            ) as distribute,+        ):+            style.shard_param(module, name, manager.get_mesh("tp"), config=config, mesh_manager=manager)+            return distribute.call_args.args[2]++    @parameterized.expand(+        [+            (2, 2, 4),  # fewer heads than ranks -> replicated+            (6, 6, 4),  # heads do not divide the world+            (7, 7, 4),  # coprime -> fully replicated+            (8, 8, 4),  # exact fit, no replication+            (12, 12, 8),+            (2, 2, 8),+            (32, 8, 8),  # GQA+            (32, 8, 16),  # GQA, more ranks than kv heads+            (8, 1, 4),  # MQA+        ]+    )+    def test_every_rank_owns_whole_heads(self, num_heads, num_key_value_heads, world_size):+        manager = self._manager(world_size)+        with self._fake_device_mesh():+            for units in (num_heads, num_key_value_heads):+                groups, replicas = manager.get_unit_mesh(units).mesh.shape+                self.assertEqual(groups * replicas, world_size, "the mesh must cover every rank")+                self.assertEqual(groups, math.gcd(units, world_size), "replication must be the least possible")+                self.assertEqual(units % groups, 0, "a head may not be split across ranks")+                self.assertGreaterEqual(units // groups, 1, "no rank may be left without a head")++    @parameterized.expand([(2, 2, 4), (6, 6, 4), (8, 8, 4), (32, 8, 8), (32, 8, 16), (8, 1, 4)])+    def test_projections_are_sharded_on_the_head_axis(self, num_heads, num_key_value_heads, world_size):+        attention, config = self._attention(num_heads, num_key_value_heads)+        manager = self._manager(world_size)+        colwise, rowwise = ALL_PARALLEL_STYLES["unit_colwise"], ALL_PARALLEL_STYLES["unit_rowwise"]++        for name, units in (("q_proj", num_heads), ("k_proj", num_key_value_heads), ("v_proj", num_key_value_heads)):+            proj = getattr(attention, name)+            placements = self._shard(proj, "weight", colwise, manager, config)+            groups = math.gcd(units, world_size)+            self.assertEqual(placements[0].dim, 0, f"{name} shards its output features")+            self.assertTrue(placements[1].is_replicate(), f"{name} replicates along the second axis")+            self.assertEqual(proj.weight.shape[0] // groups % self.HEAD_DIM, 0, f"{name} split a head")++        placements = self._shard(attention.o_proj, "weight", rowwise, manager, config)+        self.assertEqual(placements[0].dim, 1, "o_proj shards its input features")+        self.assertTrue(placements[1].is_replicate())+        self.assertEqual(attention.o_proj.weight.shape[1] // math.gcd(num_heads, world_size) % self.HEAD_DIM, 0)++    @parameterized.expand([(2, 4), (6, 4), (8, 4), (12, 8), (32, 16)])+    def test_colwise_and_rowwise_agree_on_the_mesh(self, num_heads, world_size):+        """o_proj consumes q_proj's output, so the two must land on the same unit mesh."""+        attention, config = self._attention(num_heads, num_heads)+        manager = self._manager(world_size)+        self._shard(attention.q_proj, "weight", ALL_PARALLEL_STYLES["unit_colwise"], manager, config)+        self._shard(attention.o_proj, "weight", ALL_PARALLEL_STYLES["unit_rowwise"], manager, config)+        self.assertIs(attention.q_proj._unit_mesh, attention.o_proj._unit_mesh, "the unit mesh is built once")++ class TestTensorParallelTiedWeights(TestCasePlus):     @parameterized.expand([("equal", True), ("different", False)])     def test_checkpoint_with_both_tied_keys_matches_tp1(self, _, equal):
tests/test_tensor_parallel_mixin.py53 + / 8 −
@@ -117,15 +117,15 @@ def _get_expert_weight_names(model):     return names  -def _load_tp_and_reference_models(model_path, model_class):-    """Load TP model and non-TP reference model for comparison.+def _load_tp_and_reference_models(model_path, model_class, tp_plan=None):+    """Load TP model and non-TP reference model for comparison. `tp_plan` overrides rules of the model's plan.      Returns:         tuple: (model_tp, model_ref, device)     """     model_tp = model_class.from_pretrained(         model_path,-        distributed_config=DistributedConfig(tp_size=dist.get_world_size()),+        distributed_config=DistributedConfig(tp_size=dist.get_world_size(), tp_plan=tp_plan),     )     dist.barrier() @@ -184,11 +184,11 @@ def _reference_grad_shard(name, grad, local_grad, rank, world_size, tp_plan, exp     return grad  -def _test_tp_forward_impl(_rank, model_path, model_class, atol, rtol):+def _test_tp_forward_impl(_rank, model_path, model_class, atol, rtol, tp_plan=None):     """Implementation for comparing TP and non-TP model outputs."""     set_seed(0) -    model_tp, model, device = _load_tp_and_reference_models(model_path, model_class)+    model_tp, model, device = _load_tp_and_reference_models(model_path, model_class, tp_plan)      _verify_tp_sharding(_rank, model_tp, model) @@ -211,11 +211,11 @@ def _test_tp_forward_impl(_rank, model_path, model_class, atol, rtol):     dist.barrier()  -def _test_tp_backward_impl(rank, model_path, model_class, atol, rtol):+def _test_tp_backward_impl(rank, model_path, model_class, atol, rtol, tp_plan=None):     """Implementation for comparing TP and non-TP model backward passes."""     set_seed(0) -    model_tp, model, device = _load_tp_and_reference_models(model_path, model_class)+    model_tp, model, device = _load_tp_and_reference_models(model_path, model_class, tp_plan)     model_tp.train()     model.train() @@ -247,8 +247,9 @@ def _test_tp_backward_impl(rank, model_path, model_class, atol, rtol):              # A sharded param's grad is a DTensor: take this rank's local shard, since a DTensor             # reports the *global* shape and can't be compared against a plain tensor.+            # Unit styles shard on a 2-D (units, replicas) mesh, where the rank isn't the shard index: gather those.             if isinstance(grad_tp, DTensor):-                grad_tp = grad_tp.to_local()+                grad_tp = grad_tp.full_tensor() if grad_tp.device_mesh.ndim > 1 else grad_tp.to_local()              grad = _reference_grad_shard(name, grad, grad_tp, rank, world_size, model_tp._tp_plan) @@ -520,6 +521,50 @@ def test_tp_backward(self):                 tmp_dir, model_class, atol, rtol             ) +    @is_tensor_parallel_test+    def test_tp_unit_plan_forward_backward(self):+        """`unit_colwise`/`unit_rowwise` on the attention projections must match the unsharded model, outputs and+        gradients, including when ranks replicate heads (fewer KV heads than ranks)."""+        self._skip_if_not_supported()++        config = self._get_tp_config()+        text_config = config.get_text_config()+        head_dim = getattr(text_config, "head_dim", None) or text_config.hidden_size // text_config.num_attention_heads+        if hasattr(text_config, "num_key_value_heads"):+            text_config.num_key_value_heads = 1  # fewer KV heads than ranks: ranks replicate the head+        # Replicate Q heads too so the rowwise output projection hits the 1/replicas scaling path.+        if hasattr(text_config, "num_attention_heads"):+            text_config.num_attention_heads = 1+            # Keep the per-head width: models like Glm4v-MoE derive other config values (mrope) from it.+            text_config.head_dim = head_dim+        model_class = self._get_tp_model_class()+        expected = {"q_proj": "colwise", "k_proj": "colwise", "v_proj": "colwise", "o_proj": "rowwise"}+        model_plan = model_class(config).tp_plan+        attention_styles = {+            key.rsplit(".", 1)[-1]: style+            for key, style in model_plan.items()+            if "self_attn" in key and style in ("colwise", "rowwise")+        }+        # TODO: unit sharding only covers head-aligned Linear weights for now. It does not handle extra+        # per-head parameters such as Beam's `gate_bias` or GraniteSWA's `sinks`, so skip those models.+        if set(attention_styles) != set(expected):+            self.skipTest("Attention has additional head-aligned parameters that unit sharding does not support yet")+        tp_plan = {}+        for key, style in model_plan.items():+            name = key.rsplit(".", 1)[-1]+            if expected.get(name) == style:+                tp_plan[key] = f"unit_{style}"+        if {key.rsplit(".", 1)[-1] for key in tp_plan} != set(expected):+            self.skipTest("Attention is not a plain colwise q/k/v + rowwise o_proj")++        atol = self.tensor_parallel_atol+        rtol = self.tensor_parallel_rtol+        with tempfile.TemporaryDirectory() as tmp_dir:+            set_seed(42)+            model_class(config).save_pretrained(tmp_dir, save_original_format=True)+            for impl in (_test_tp_forward_impl, _test_tp_backward_impl):+                run_distributed(world_size=self.tensor_parallel_size)(impl)(tmp_dir, model_class, atol, rtol, tp_plan)+     @is_tensor_parallel_test     def test_tp_generation(self):         # Test TP generation: unfused checkpoint → conversion mapping (if needed) → TP sharding → model → generate