From f2ed560db98a0b7dff33c49b51de486dd53ef7c5 Mon Sep 17 00:00:00 2001 From: Ferdinand Mom Date: Tue, 10 Nov 2026 11:28:31 +0900 Subject: [PATCH 1/5] [distributed] Train a model with sequence parallelism in Trainer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Trainer` trains a model loaded with `DistributedConfig(sp_size=N)` like a model on a single device. Its dataloader mesh is `(dp_shard, cp, tp)` — the `cp` dim holds the `sp` size, the name Accelerate's dataloader shards over — so the ranks of an sp group (and of a tp group) get the same batch and only the data parallel ranks split them. The token count that normalizes the loss counts each sequence once, the logged loss is the loss of the full sequences, and the per-rank token and FLOP counts gathered over every rank are divided by the batch replicas. Evaluation supports the loss only: each rank holds the logits of its own slice of the sequences, so `predict` refuses to gather them. The refusal added with `DistributedConfig(sp_size=N)` goes away. The script trains a tiny model through `Trainer` with sp / tp / fsdp sizes and writes the loss, the gradient norm, the evaluation loss and the token count, so the test compares five configurations against a single-device run of the same samples. --- src/transformers/distributed/mixin.py | 2 + src/transformers/trainer.py | 64 ++++++++++++++++++++++----- 2 files changed, 55 insertions(+), 11 deletions(-) diff --git a/src/transformers/distributed/mixin.py b/src/transformers/distributed/mixin.py index eeed16bf3180..7d831bb9f0ee 100644 --- a/src/transformers/distributed/mixin.py +++ b/src/transformers/distributed/mixin.py @@ -66,6 +66,7 @@ class DistributedMixin: _ep_plan: dict[str, str] | None = None _tp_size = None _fsdp_size = None + _sp_size = None _pp_plan: dict[str, tuple[str, str]] | None = None _fsdp_plan: dict[str, str] | None = None _sp_plan: dict[str, str] | None = None @@ -347,6 +348,7 @@ def maybe_distribute_model( model._is_distributed_loading_by_transformers = True model._tp_size = distributed_config.tp_size model._fsdp_size = distributed_config.fsdp_size + model._sp_size = distributed_config.sp_size tp_plan, ep_plan, fsdp_plan, sp_plan = model._resolve_parallel_plans(distributed_config) diff --git a/src/transformers/trainer.py b/src/transformers/trainer.py index 03e0d7aca88a..e9a00a28024d 100755 --- a/src/transformers/trainer.py +++ b/src/transformers/trainer.py @@ -775,9 +775,10 @@ def _build_accelerator_args(self, **kwargs) -> dict[str, Any]: args["parallelism_config"] = self.args.parallelism_config model_tp_size = getattr(self.model, "tp_size", None) or 1 - if model_tp_size > 1: + if model_tp_size > 1 and self._model_sp_size == 1: # Sharded at load time (tensor/expert parallelism, optionally with FSDP2 or HSDP on more mesh # dimensions): accelerate has to know the TP size and the data parallel size, HSDP replicas included. + # With sequence parallelism, the device mesh is set after the accelerator is created instead. model_dp_size = self.model.config.distributed_config.dp_size if not is_accelerate_available("1.12.0"): raise ValueError("Requires accelerate>1.12.0 to use Tensor Parallelism.") @@ -862,6 +863,18 @@ def create_accelerator_and_postprocess(self) -> None: # create accelerator object self.accelerator = Accelerator(**args) + + # The ranks of an sp group and of a tp group share a batch: the dataloader shards over the other ranks only. + # Accelerate's dataloader knows that dimension as `cp`, so the mesh keeps that name for the sp size. + if self._model_sp_size > 1: + model_tp_size = getattr(self.model, "tp_size", None) or 1 + data_parallel_size = self.accelerator.num_processes // (self._model_sp_size * model_tp_size) + self.accelerator.state.device_mesh = dist.init_device_mesh( + self.accelerator.device.type, + (data_parallel_size, self._model_sp_size, model_tp_size), + mesh_dim_names=("dp_shard", "cp", "tp"), + ) + # some Trainer classes need to use `gather` instead of `gather_for_metrics`, thus we store a flag self.gather_function = self.accelerator.gather_for_metrics @@ -2247,8 +2260,9 @@ def compute_loss( and num_items_in_batch is not None ): # TP ranks (and the expert-parallel ranks sharing their batch) see replicated batches; `num_processes` - # over-counts them by `tp_size`. Mirror the divisor used in `_get_num_items_in_batch`. - loss_scale = self.accelerator.num_processes // self.get_tp_size() + # over-counts them by `tp_size`, and the ranks of an sp group by `sp_size` (the model already scales its + # gradient by `sp_size`). Mirror the divisor used in `_get_num_items_in_batch`. + loss_scale = self.accelerator.num_processes // (self.get_tp_size() * self._model_sp_size) loss *= loss_scale if self.args.n_gpu <= 1 else self.args.n_gpu return (loss, outputs) if return_outputs else loss @@ -2397,9 +2411,11 @@ def _get_num_items_in_batch(self, batch_samples: list, device: torch.device) -> # In the DataParallel case, convert the scalar tensor into a 2-dim tensor with the same value repeated num_items_in_batch = num_items_in_batch.unsqueeze(0).expand(self.args.n_gpu, -1) # Divide by number of devices with the same batch - num_items_in_batch = num_items_in_batch / ( - self.get_tp_size() * self.get_cp_size() * self.get_sp_size() - ) + replicas = self.get_tp_size() * self.get_cp_size() * self.get_sp_size() * self._model_sp_size + if self._model_sp_size > 1 and not self.args.average_tokens_across_devices: + # not gathered: this is already the count of the batch the sp group shares + replicas //= self._model_sp_size + num_items_in_batch = num_items_in_batch / replicas return num_items_in_batch @@ -2449,6 +2465,10 @@ def _prepare_context_parallel_inputs( tuple: (context_manager, prepared_inputs) where context_manager is either the context parallelism wrapper or a no-op context """ + if self._model_sp_size > 1: + # a model loaded with `DistributedConfig(sp_size=N)` splits its own inputs + return contextlib.nullcontext, inputs + if ( getattr(self.accelerator, "parallelism_config", None) is not None and self.accelerator.parallelism_config.cp_enabled @@ -2612,9 +2632,12 @@ def get_total_train_batch_size(self, args: TrainingArguments) -> int: - SP (Sequence Parallelism): Sequences split using ALST/Ulysses (DeepSpeed) All dimensions are separate and multiplicative: world_size = dp_size * tp_size * cp_size * sp_size + A model sharded at load time with `DistributedConfig(sp_size=N)` replicates each batch over its `sp` ranks too. """ - dp_world_size = args.world_size // self.get_tp_size() // self.get_cp_size() // self.get_sp_size() + dp_world_size = ( + args.world_size // self.get_tp_size() // self.get_cp_size() // self.get_sp_size() // self._model_sp_size + ) return self._train_batch_size * args.gradient_accumulation_steps * dp_world_size def get_sp_size(self) -> int: @@ -2633,6 +2656,18 @@ def get_cp_size(self) -> int: pc = self.accelerator.parallelism_config return pc.cp_size + @property + def _model_sp_size(self) -> int: + """The `sp_size` of a model sharded at load time by `DistributedConfig(sp_size=N)`, 1 otherwise.""" + return getattr(self.model, "_sp_size", None) or 1 + + @property + def _model_batch_replicas(self) -> int: + """How many ranks share each batch of a model loaded with `DistributedConfig(sp_size=N)`: `sp_size * tp_size`.""" + if self._model_sp_size == 1: + return 1 + return self._model_sp_size * self.get_tp_size() + def get_tp_size(self) -> int: """Get the tensor parallel size from either the model or DeepSpeed config.""" @@ -2789,7 +2824,8 @@ def _track_num_input_tokens(self, inputs): input_tokens = inputs[main_input_name].numel() input_tokens = torch.as_tensor(input_tokens, device=self.args.device, dtype=torch.int64) - self.state.num_input_tokens_seen += self.accelerator.gather(input_tokens).sum().item() + input_tokens = self.accelerator.gather(input_tokens) // self._model_batch_replicas + self.state.num_input_tokens_seen += input_tokens.sum().item() def _mixed_mesh_grad_norm(self, model, max_norm): """ @@ -2962,6 +2998,13 @@ def evaluation_loop( prediction_loss_only = prediction_loss_only if prediction_loss_only is not None else args.prediction_loss_only + if self._model_sp_size > 1 and not prediction_loss_only: + raise ValueError( + "Sequence parallelism (`sp_size > 1`) only supports evaluating the loss: each rank only holds the " + "logits of its own slice of the sequences, and gathering them would repeat the batch of every sp " + "group. Pass `prediction_loss_only=True`, or disable sequence parallelism." + ) + # if eval is called w/o train, handle model prep here if self.is_deepspeed_enabled and self.deepspeed is None: _, _ = deepspeed_init(self, num_training_steps=0, inference=True) @@ -4257,9 +4300,8 @@ def log(self, logs: dict[str, float], start_time: float | None = None) -> None: def store_flos(self) -> None: """Store the number of floating-point operations that went into the model.""" if self.args.parallel_mode == ParallelMode.DISTRIBUTED: - self.state.total_flos += ( - distributed_broadcast_scalars([self.current_flos], device=self.args.device).sum().item() - ) + total_flos = distributed_broadcast_scalars([self.current_flos], device=self.args.device).sum().item() + self.state.total_flos += total_flos / self._model_batch_replicas self.current_flos = 0 else: self.state.total_flos += self.current_flos From eaf26aa6d4a8512b61b023716a1656a289a035d3 Mon Sep 17 00:00:00 2001 From: Ferdinand Mom Date: Tue, 10 Nov 2026 11:28:32 +0900 Subject: [PATCH 2/5] [distributed] Test the Trainer with sequence parallelism against a single device `sp_distributed_config.py` trains a tiny model through `Trainer` with sp / fsdp / tp sizes and writes the loss, the gradient norm, the evaluation loss and the token count of two steps. Five configurations (sp, sp with gradient accumulation, fsdp x sp, tp x sp, and sp with tokens not averaged across devices) are compared with a single-device run of the same samples, launched with one process so that the reference does not use `DataParallel`. --- .../scripts/sp_distributed_config.py | 153 ++++++++++++++++++ .../test_trainer_distributed_transformers.py | 90 ++++++++++- 2 files changed, 241 insertions(+), 2 deletions(-) create mode 100644 tests/trainer/distributed/scripts/sp_distributed_config.py diff --git a/tests/trainer/distributed/scripts/sp_distributed_config.py b/tests/trainer/distributed/scripts/sp_distributed_config.py new file mode 100644 index 000000000000..d4413c0ccc85 --- /dev/null +++ b/tests/trainer/distributed/scripts/sp_distributed_config.py @@ -0,0 +1,153 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# 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. + +""" +Worker script: `Trainer` trains a model sharded at load time with `DistributedConfig(sp_size=N)` like a single device +trains the same weights on the same data. + +The loss and the gradient norm of every step, and the number of input tokens seen, are written to +``--metrics_file`` so that a run with sequence parallelism can be compared with a single-device run of the same samples. +Launched via ``torchrun`` from ``test_trainer_distributed_transformers.py``. +""" + +import argparse +import json +import os +from datetime import timedelta + +import torch +import torch.distributed as dist +from datasets import Dataset + +from transformers import AutoModelForCausalLM, LlamaConfig, Trainer, TrainerCallback, TrainingArguments, set_seed +from transformers.distributed import DistributedConfig +from transformers.distributed.utils import get_distributed_backend +from transformers.testing_utils import torch_device + + +NUM_STEPS = 2 +SEQ_LEN = 8 +NUM_SAMPLES = 32 + + +class StepMetricsCallback(TrainerCallback): + """The loss and the gradient norm logged at the end of every optimizer step.""" + + def __init__(self): + self.losses = [] + self.grad_norms = [] + + def on_log(self, args, state, control, logs=None, **kwargs): + if logs is not None and "loss" in logs: + self.losses.append(logs["loss"]) + self.grad_norms.append(logs["grad_norm"]) + + +def _tiny_config(): + """A `LlamaConfig` small enough for CPU tests, with enough key/value heads for four `sp` x `tp` ranks.""" + return LlamaConfig( + hidden_size=32, + intermediate_size=64, + num_hidden_layers=2, + num_attention_heads=4, + num_key_value_heads=4, + vocab_size=99, + attn_implementation="sdpa", + ) + + +def _dataset(config): + """`NUM_SAMPLES` deterministic sequences, the same for every run of this script.""" + generator = torch.Generator().manual_seed(0) + input_ids = torch.randint(0, config.vocab_size, (NUM_SAMPLES, SEQ_LEN), generator=generator).tolist() + return Dataset.from_dict({"input_ids": input_ids, "labels": input_ids}) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output_dir", required=True) + parser.add_argument("--metrics_file", required=True) + parser.add_argument("--sp_size", type=int, default=1) + parser.add_argument("--fsdp_size", type=int, default=1) + parser.add_argument("--tp_size", type=int, default=1) + parser.add_argument("--gradient_accumulation_steps", type=int, default=1) + parser.add_argument("--no_average_tokens_across_devices", action="store_true") + script_args = parser.parse_args() + + if script_args.sp_size > 1 or script_args.fsdp_size > 1 or script_args.tp_size > 1: + dist.init_process_group(backend=get_distributed_backend(torch_device), timeout=timedelta(seconds=120)) + rank = dist.get_rank() if dist.is_initialized() else 0 + + # every run starts from the same weights, whichever parallelism it then shards them with + config = _tiny_config() + model_dir = os.path.join(script_args.output_dir, "model") + set_seed(0) + if rank == 0: + AutoModelForCausalLM.from_config(config).save_pretrained(model_dir) + if dist.is_initialized(): + dist.barrier() + + model = AutoModelForCausalLM.from_pretrained( + model_dir, + distributed_config=DistributedConfig( + sp_size=script_args.sp_size, fsdp_size=script_args.fsdp_size, tp_size=script_args.tp_size + ), + ) + args = TrainingArguments( + output_dir=script_args.output_dir, + max_steps=NUM_STEPS, + per_device_train_batch_size=1, + gradient_accumulation_steps=script_args.gradient_accumulation_steps, + learning_rate=1e-3, + logging_steps=1, + save_strategy="no", + train_sampling_strategy="sequential", + dataloader_drop_last=True, + include_num_input_tokens_seen="all", + average_tokens_across_devices=not script_args.no_average_tokens_across_devices, + use_cpu=torch_device == "cpu", + report_to="none", + disable_tqdm=True, + ) + dataset = _dataset(config) + callback = StepMetricsCallback() + trainer = Trainer(model=model, args=args, train_dataset=dataset, callbacks=[callback]) + trainer.train() + + assert len(callback.losses) == NUM_STEPS, f"rank {rank}: {callback.losses}" + + # the logits of a sequence are split over the sp ranks, so only the loss can be predicted + if script_args.sp_size > 1: + try: + trainer.predict(dataset) + except ValueError as error: + assert "only supports evaluating the loss" in str(error), error + else: + raise AssertionError(f"rank {rank}: predicting logits with sequence parallelism did not raise") + + trainer.args.prediction_loss_only = True + metrics = { + "losses": callback.losses, + "grad_norms": callback.grad_norms, + "eval_loss": trainer.evaluate(dataset)["eval_loss"], + "num_input_tokens_seen": trainer.state.num_input_tokens_seen, + } + if rank == 0: + with open(script_args.metrics_file, "w", encoding="utf-8") as f: + json.dump(metrics, f) + trainer.end() + + +if __name__ == "__main__": + main() diff --git a/tests/trainer/distributed/test_trainer_distributed_transformers.py b/tests/trainer/distributed/test_trainer_distributed_transformers.py index 5caad5f44a08..d42f6e9f6d04 100644 --- a/tests/trainer/distributed/test_trainer_distributed_transformers.py +++ b/tests/trainer/distributed/test_trainer_distributed_transformers.py @@ -16,8 +16,11 @@ Trainer tests for models sharded at load time by transformers' `DistributedConfig`. """ +import json import os +import tempfile +import torch from parameterized import parameterized from transformers.testing_utils import ( @@ -28,6 +31,7 @@ require_torch_greater_or_equal, require_torch_multi_accelerator, ) +from transformers.utils import is_torch_greater_or_equal from .test_trainer_distributed import SCRIPTS_DIR @@ -35,8 +39,13 @@ @require_torch_greater_or_equal("2.7") @require_torch_multi_accelerator class TestTrainerDistributedConfig(TestCasePlus): - def get_torchrun_cmd(self, script, script_args=None): - cmd = ["torchrun", "--nproc_per_node=2", "--nnodes=1", f"--master_port={get_torch_dist_unique_port()}"] + def get_torchrun_cmd(self, script, script_args=None, nproc_per_node=2): + cmd = [ + "torchrun", + f"--nproc_per_node={nproc_per_node}", + "--nnodes=1", + f"--master_port={get_torch_dist_unique_port()}", + ] cmd.append(os.path.join(SCRIPTS_DIR, script)) return cmd + (script_args or []) @@ -83,6 +92,83 @@ def test_grad_accumulation_reduces_on_last_micro_batch(self, _, dp_replicate_siz self.get_torchrun_cmd("grad_accum_distributed_config.py", script_args), env=self.get_env() ) + @parameterized.expand( + [ + ("sp", 2, 1, 1, 1, True), + ("sp_grad_accumulation", 2, 1, 1, 2, True), + ("fsdp_sp", 2, 2, 1, 2, True), + ("tp_sp", 2, 1, 2, 1, True), + ("sp_tokens_not_averaged_across_devices", 2, 1, 1, 1, False), + ] + ) + def test_sequence_parallel(self, _, sp_size, fsdp_size, tp_size, gradient_accumulation_steps, average_tokens): + """A model split over sp and tp groups takes the same steps as a single device on the same samples.""" + if not is_torch_greater_or_equal("2.10" if fsdp_size > 1 else "2.9"): + self.skipTest("Sequence parallelism requires torch>=2.9, and torch>=2.10 with FSDP2") + with tempfile.TemporaryDirectory() as tmp_dir: + single_device_file = os.path.join(tmp_dir, "single_device.json") + # the data parallel groups hold a distinct batch each, so a single device accumulates one micro-batch per + # group to cover the same samples in a step + reference_args = [ + "--output_dir", + os.path.join(tmp_dir, "single_device"), + "--metrics_file", + single_device_file, + "--gradient_accumulation_steps", + str(gradient_accumulation_steps * fsdp_size), + ] + ([] if average_tokens else ["--no_average_tokens_across_devices"]) + # one process: a plain run would use `DataParallel` over every visible GPU + reference_cmd = self.get_torchrun_cmd("sp_distributed_config.py", reference_args, nproc_per_node=1) + execute_subprocess_async(reference_cmd, env=self.get_env()) + + sp_file = os.path.join(tmp_dir, "sequence_parallel.json") + script_args = [ + "--output_dir", + os.path.join(tmp_dir, "sequence_parallel"), + "--metrics_file", + sp_file, + "--sp_size", + str(sp_size), + "--fsdp_size", + str(fsdp_size), + "--tp_size", + str(tp_size), + "--gradient_accumulation_steps", + str(gradient_accumulation_steps), + ] + ([] if average_tokens else ["--no_average_tokens_across_devices"]) + cmd = self.get_torchrun_cmd( + "sp_distributed_config.py", script_args, nproc_per_node=sp_size * fsdp_size * tp_size + ) + execute_subprocess_async(cmd, env=self.get_env()) + + with open(single_device_file, encoding="utf-8") as f: + single_device = json.load(f) + with open(sp_file, encoding="utf-8") as f: + sequence_parallel = json.load(f) + + torch.testing.assert_close( + torch.tensor(sequence_parallel["losses"]), + torch.tensor(single_device["losses"]), + rtol=1e-5, + atol=1e-6, + msg="Loss mismatch", + ) + torch.testing.assert_close( + torch.tensor(sequence_parallel["grad_norms"]), + torch.tensor(single_device["grad_norms"]), + rtol=1e-5, + atol=1e-6, + msg="Gradient norm mismatch", + ) + torch.testing.assert_close( + torch.tensor(sequence_parallel["eval_loss"]), + torch.tensor(single_device["eval_loss"]), + rtol=1e-5, + atol=1e-6, + msg="Evaluation loss mismatch", + ) + assert sequence_parallel["num_input_tokens_seen"] == single_device["num_input_tokens_seen"] + def test_train_after_evaluate(self): """Training after an evaluation updates every parameter of a model sharded at load time.""" script_args = ["--output_dir", self.get_auto_remove_tmp_dir()] From fbb10c84e5601201f90c9e1f2279ed3b5d80937e Mon Sep 17 00:00:00 2001 From: Ferdinand Mom Date: Wed, 2 Dec 2026 00:17:47 -0800 Subject: [PATCH 3/5] [distributed] Simplify Trainer sequence parallelism and tests --- src/transformers/trainer.py | 39 ++++--- .../scripts/sp_distributed_config.py | 4 +- .../test_trainer_distributed_transformers.py | 102 ++++++++---------- 3 files changed, 62 insertions(+), 83 deletions(-) diff --git a/src/transformers/trainer.py b/src/transformers/trainer.py index e9a00a28024d..4b35fd816b51 100755 --- a/src/transformers/trainer.py +++ b/src/transformers/trainer.py @@ -778,7 +778,7 @@ def _build_accelerator_args(self, **kwargs) -> dict[str, Any]: if model_tp_size > 1 and self._model_sp_size == 1: # Sharded at load time (tensor/expert parallelism, optionally with FSDP2 or HSDP on more mesh # dimensions): accelerate has to know the TP size and the data parallel size, HSDP replicas included. - # With sequence parallelism, the device mesh is set after the accelerator is created instead. + # With SP, `dp_size` includes `sp_size`, so we set the dataloader mesh on `accelerator.state` after creation instead. model_dp_size = self.model.config.distributed_config.dp_size if not is_accelerate_available("1.12.0"): raise ValueError("Requires accelerate>1.12.0 to use Tensor Parallelism.") @@ -864,14 +864,14 @@ def create_accelerator_and_postprocess(self) -> None: # create accelerator object self.accelerator = Accelerator(**args) - # The ranks of an sp group and of a tp group share a batch: the dataloader shards over the other ranks only. - # Accelerate's dataloader knows that dimension as `cp`, so the mesh keeps that name for the sp size. if self._model_sp_size > 1: - model_tp_size = getattr(self.model, "tp_size", None) or 1 - data_parallel_size = self.accelerator.num_processes // (self._model_sp_size * model_tp_size) + # Ranks in the same (sp, tp) group share a batch, so the dataloader shards only over `dp_shard`. + # The SP axis is named "cp" because Accelerate's dataloader reads that dimension for shared batches. + tp_size = getattr(self.model, "tp_size", None) or 1 + dp_size = self.accelerator.num_processes // (self._model_sp_size * tp_size) self.accelerator.state.device_mesh = dist.init_device_mesh( self.accelerator.device.type, - (data_parallel_size, self._model_sp_size, model_tp_size), + (dp_size, self._model_sp_size, tp_size), mesh_dim_names=("dp_shard", "cp", "tp"), ) @@ -2410,12 +2410,11 @@ def _get_num_items_in_batch(self, batch_samples: list, device: torch.device) -> if self.args.n_gpu > 1 and num_items_in_batch.dim() == 0: # In the DataParallel case, convert the scalar tensor into a 2-dim tensor with the same value repeated num_items_in_batch = num_items_in_batch.unsqueeze(0).expand(self.args.n_gpu, -1) - # Divide by number of devices with the same batch - replicas = self.get_tp_size() * self.get_cp_size() * self.get_sp_size() * self._model_sp_size - if self._model_sp_size > 1 and not self.args.average_tokens_across_devices: - # not gathered: this is already the count of the batch the sp group shares - replicas //= self._model_sp_size - num_items_in_batch = num_items_in_batch / replicas + # Divide by number of devices with the same batch; without gathering, local labels are not duplicated across SP ranks + model_sp_replicas = self._model_sp_size if self.args.average_tokens_across_devices else 1 + num_items_in_batch = num_items_in_batch / ( + self.get_tp_size() * self.get_cp_size() * self.get_sp_size() * model_sp_replicas + ) return num_items_in_batch @@ -2658,15 +2657,13 @@ def get_cp_size(self) -> int: @property def _model_sp_size(self) -> int: - """The `sp_size` of a model sharded at load time by `DistributedConfig(sp_size=N)`, 1 otherwise.""" + """Sequence parallel size from `DistributedConfig(sp_size=N)` (distinct from Accelerate/DeepSpeed `get_sp_size`), or 1.""" return getattr(self.model, "_sp_size", None) or 1 @property - def _model_batch_replicas(self) -> int: - """How many ranks share each batch of a model loaded with `DistributedConfig(sp_size=N)`: `sp_size * tp_size`.""" - if self._model_sp_size == 1: - return 1 - return self._model_sp_size * self.get_tp_size() + def _sp_batch_replicas(self) -> int: + """Number of ranks sharing a batch when SP is enabled (`sp_size * tp_size`), or 1 otherwise.""" + return self._model_sp_size * self.get_tp_size() if self._model_sp_size > 1 else 1 def get_tp_size(self) -> int: """Get the tensor parallel size from either the model or DeepSpeed config.""" @@ -2824,8 +2821,8 @@ def _track_num_input_tokens(self, inputs): input_tokens = inputs[main_input_name].numel() input_tokens = torch.as_tensor(input_tokens, device=self.args.device, dtype=torch.int64) - input_tokens = self.accelerator.gather(input_tokens) // self._model_batch_replicas - self.state.num_input_tokens_seen += input_tokens.sum().item() + total_tokens = self.accelerator.gather(input_tokens).sum().item() + self.state.num_input_tokens_seen += total_tokens // self._sp_batch_replicas def _mixed_mesh_grad_norm(self, model, max_norm): """ @@ -4301,7 +4298,7 @@ def store_flos(self) -> None: """Store the number of floating-point operations that went into the model.""" if self.args.parallel_mode == ParallelMode.DISTRIBUTED: total_flos = distributed_broadcast_scalars([self.current_flos], device=self.args.device).sum().item() - self.state.total_flos += total_flos / self._model_batch_replicas + self.state.total_flos += total_flos / self._sp_batch_replicas self.current_flos = 0 else: self.state.total_flos += self.current_flos diff --git a/tests/trainer/distributed/scripts/sp_distributed_config.py b/tests/trainer/distributed/scripts/sp_distributed_config.py index d4413c0ccc85..a0b59e290262 100644 --- a/tests/trainer/distributed/scripts/sp_distributed_config.py +++ b/tests/trainer/distributed/scripts/sp_distributed_config.py @@ -37,7 +37,7 @@ NUM_STEPS = 2 -SEQ_LEN = 8 +SEQ_LEN = 6 NUM_SAMPLES = 32 @@ -85,7 +85,7 @@ def main(): parser.add_argument("--no_average_tokens_across_devices", action="store_true") script_args = parser.parse_args() - if script_args.sp_size > 1 or script_args.fsdp_size > 1 or script_args.tp_size > 1: + if script_args.sp_size * script_args.fsdp_size * script_args.tp_size > 1: dist.init_process_group(backend=get_distributed_backend(torch_device), timeout=timedelta(seconds=120)) rank = dist.get_rank() if dist.is_initialized() else 0 diff --git a/tests/trainer/distributed/test_trainer_distributed_transformers.py b/tests/trainer/distributed/test_trainer_distributed_transformers.py index d42f6e9f6d04..30822063994a 100644 --- a/tests/trainer/distributed/test_trainer_distributed_transformers.py +++ b/tests/trainer/distributed/test_trainer_distributed_transformers.py @@ -106,67 +106,49 @@ def test_sequence_parallel(self, _, sp_size, fsdp_size, tp_size, gradient_accumu if not is_torch_greater_or_equal("2.10" if fsdp_size > 1 else "2.9"): self.skipTest("Sequence parallelism requires torch>=2.9, and torch>=2.10 with FSDP2") with tempfile.TemporaryDirectory() as tmp_dir: - single_device_file = os.path.join(tmp_dir, "single_device.json") - # the data parallel groups hold a distinct batch each, so a single device accumulates one micro-batch per - # group to cover the same samples in a step - reference_args = [ - "--output_dir", - os.path.join(tmp_dir, "single_device"), - "--metrics_file", - single_device_file, - "--gradient_accumulation_steps", - str(gradient_accumulation_steps * fsdp_size), - ] + ([] if average_tokens else ["--no_average_tokens_across_devices"]) - # one process: a plain run would use `DataParallel` over every visible GPU - reference_cmd = self.get_torchrun_cmd("sp_distributed_config.py", reference_args, nproc_per_node=1) - execute_subprocess_async(reference_cmd, env=self.get_env()) - - sp_file = os.path.join(tmp_dir, "sequence_parallel.json") - script_args = [ - "--output_dir", - os.path.join(tmp_dir, "sequence_parallel"), - "--metrics_file", - sp_file, - "--sp_size", - str(sp_size), - "--fsdp_size", - str(fsdp_size), - "--tp_size", - str(tp_size), - "--gradient_accumulation_steps", - str(gradient_accumulation_steps), - ] + ([] if average_tokens else ["--no_average_tokens_across_devices"]) - cmd = self.get_torchrun_cmd( - "sp_distributed_config.py", script_args, nproc_per_node=sp_size * fsdp_size * tp_size + + def run(name, *, sp_size=1, fsdp_size=1, tp_size=1, grad_accum=1): + metrics_file = os.path.join(tmp_dir, f"{name}.json") + script_args = [ + "--output_dir", + os.path.join(tmp_dir, name), + "--metrics_file", + metrics_file, + "--sp_size", + str(sp_size), + "--fsdp_size", + str(fsdp_size), + "--tp_size", + str(tp_size), + "--gradient_accumulation_steps", + str(grad_accum), + ] + ([] if average_tokens else ["--no_average_tokens_across_devices"]) + cmd = self.get_torchrun_cmd( + "sp_distributed_config.py", script_args, nproc_per_node=sp_size * fsdp_size * tp_size + ) + execute_subprocess_async(cmd, env=self.get_env()) + with open(metrics_file, encoding="utf-8") as f: + return json.load(f) + + # Each DP group processes a distinct batch, so a single device accumulates `fsdp_size`x more micro-batches + # to cover the same samples per step. Run via torchrun (1 proc) to avoid DataParallel across GPUs. + single_device = run("single_device", grad_accum=gradient_accumulation_steps * fsdp_size) + sequence_parallel = run( + "sequence_parallel", + sp_size=sp_size, + fsdp_size=fsdp_size, + tp_size=tp_size, + grad_accum=gradient_accumulation_steps, + ) + + for key in ("losses", "grad_norms", "eval_loss"): + torch.testing.assert_close( + torch.tensor(sequence_parallel[key]), + torch.tensor(single_device[key]), + rtol=1e-5, + atol=1e-6, + msg=f"{key} mismatch", ) - execute_subprocess_async(cmd, env=self.get_env()) - - with open(single_device_file, encoding="utf-8") as f: - single_device = json.load(f) - with open(sp_file, encoding="utf-8") as f: - sequence_parallel = json.load(f) - - torch.testing.assert_close( - torch.tensor(sequence_parallel["losses"]), - torch.tensor(single_device["losses"]), - rtol=1e-5, - atol=1e-6, - msg="Loss mismatch", - ) - torch.testing.assert_close( - torch.tensor(sequence_parallel["grad_norms"]), - torch.tensor(single_device["grad_norms"]), - rtol=1e-5, - atol=1e-6, - msg="Gradient norm mismatch", - ) - torch.testing.assert_close( - torch.tensor(sequence_parallel["eval_loss"]), - torch.tensor(single_device["eval_loss"]), - rtol=1e-5, - atol=1e-6, - msg="Evaluation loss mismatch", - ) assert sequence_parallel["num_input_tokens_seen"] == single_device["num_input_tokens_seen"] def test_train_after_evaluate(self): From d8c939f893daf56787d7c765d373e7242abf00b3 Mon Sep 17 00:00:00 2001 From: Ferdinand Mom Date: Wed, 2 Dec 2026 23:15:31 -0800 Subject: [PATCH 4/5] [distributed] Unify Trainer get_sp_size and expose model.sp_size --- src/transformers/modeling_utils.py | 8 +++ src/transformers/trainer.py | 84 ++++++++++++++---------------- 2 files changed, 46 insertions(+), 46 deletions(-) diff --git a/src/transformers/modeling_utils.py b/src/transformers/modeling_utils.py index 78197b3b6ca7..212c65839ac5 100644 --- a/src/transformers/modeling_utils.py +++ b/src/transformers/modeling_utils.py @@ -4801,6 +4801,14 @@ def fsdp_size(self): # if None, the model didn't undergo FSDP sharding return self._fsdp_size + @property + def sp_size(self): + """ + Returns the model's sequence parallelism degree. + """ + # if None, the model didn't undergo sequence parallel sharding + return self._sp_size + @property def supports_pp_plan(self): # Check if model has a PP plan diff --git a/src/transformers/trainer.py b/src/transformers/trainer.py index 4b35fd816b51..3706c1e4847e 100755 --- a/src/transformers/trainer.py +++ b/src/transformers/trainer.py @@ -523,8 +523,7 @@ def __init__( ) # Sequence Parallelism computes its own good_tokens count - pc = getattr(self.accelerator, "parallelism_config", None) - if pc is not None and pc.sp_backend == "deepspeed" and pc.sp_enabled: + if self._is_deepspeed_sp_enabled: self.model_accepts_loss_kwargs = False model_to_inspect = unwrap_peft_model(self.model) @@ -775,7 +774,8 @@ def _build_accelerator_args(self, **kwargs) -> dict[str, Any]: args["parallelism_config"] = self.args.parallelism_config model_tp_size = getattr(self.model, "tp_size", None) or 1 - if model_tp_size > 1 and self._model_sp_size == 1: + model_sp_size = getattr(self.model, "sp_size", None) or 1 + if model_tp_size > 1 and model_sp_size == 1: # Sharded at load time (tensor/expert parallelism, optionally with FSDP2 or HSDP on more mesh # dimensions): accelerate has to know the TP size and the data parallel size, HSDP replicas included. # With SP, `dp_size` includes `sp_size`, so we set the dataloader mesh on `accelerator.state` after creation instead. @@ -864,14 +864,15 @@ def create_accelerator_and_postprocess(self) -> None: # create accelerator object self.accelerator = Accelerator(**args) - if self._model_sp_size > 1: + model_sp_size = getattr(self.model, "sp_size", None) or 1 + if model_sp_size > 1: # Ranks in the same (sp, tp) group share a batch, so the dataloader shards only over `dp_shard`. # The SP axis is named "cp" because Accelerate's dataloader reads that dimension for shared batches. tp_size = getattr(self.model, "tp_size", None) or 1 - dp_size = self.accelerator.num_processes // (self._model_sp_size * tp_size) + dp_size = self.accelerator.num_processes // (model_sp_size * tp_size) self.accelerator.state.device_mesh = dist.init_device_mesh( self.accelerator.device.type, - (dp_size, self._model_sp_size, tp_size), + (dp_size, model_sp_size, tp_size), mesh_dim_names=("dp_shard", "cp", "tp"), ) @@ -1829,8 +1830,7 @@ def _prepare_for_training(self, max_steps, train_dataloader, resume_from_checkpo dist.fsdp.register_fsdp_forward_method(self.model, "generate") # since DataLoader was Accelerate prepared w/o a model arg in the same call, we now have to complete the DL wrapping for ALST/UlyssesSP, after model has been prepared - pc = getattr(self.accelerator, "parallelism_config", None) - if pc is not None and pc.sp_backend == "deepspeed" and pc.sp_enabled: + if self._is_deepspeed_sp_enabled: train_dataloader = self.accelerator.deepspeed_ulysses_dl_adapter(train_dataloader, model) # `deepspeed_sp_compute_loss` relies on DeepSpeed scaling gradients over the SP group, which ZeRO-3 does @@ -2206,9 +2206,10 @@ def compute_loss( divides it by the number of gradient accumulation steps), `True` if you already normalized it over the whole accumulated batch. """ - pc = getattr(self.accelerator, "parallelism_config", None) - if pc is not None and pc.sp_backend == "deepspeed" and pc.sp_enabled and self.model.training: - return deepspeed_sp_compute_loss(self.accelerator, model, inputs, return_outputs, pc) + if self._is_deepspeed_sp_enabled and self.model.training: + return deepspeed_sp_compute_loss( + self.accelerator, model, inputs, return_outputs, self.accelerator.parallelism_config + ) if (self.label_smoother is not None or self.compute_loss_func is not None) and "labels" in inputs: labels = inputs.pop("labels") @@ -2259,10 +2260,9 @@ def compute_loss( and (self.model_accepts_loss_kwargs or self.compute_loss_func) and num_items_in_batch is not None ): - # TP ranks (and the expert-parallel ranks sharing their batch) see replicated batches; `num_processes` - # over-counts them by `tp_size`, and the ranks of an sp group by `sp_size` (the model already scales its - # gradient by `sp_size`). Mirror the divisor used in `_get_num_items_in_batch`. - loss_scale = self.accelerator.num_processes // (self.get_tp_size() * self._model_sp_size) + # TP ranks see replicated batches; `num_processes` over-counts them by `tp_size`, and the ranks of an sp + # group by `sp_size`. Mirror the divisor used in `_get_num_items_in_batch`. + loss_scale = self.accelerator.num_processes // (self.get_tp_size() * self.get_sp_size()) loss *= loss_scale if self.args.n_gpu <= 1 else self.args.n_gpu return (loss, outputs) if return_outputs else loss @@ -2410,11 +2410,11 @@ def _get_num_items_in_batch(self, batch_samples: list, device: torch.device) -> if self.args.n_gpu > 1 and num_items_in_batch.dim() == 0: # In the DataParallel case, convert the scalar tensor into a 2-dim tensor with the same value repeated num_items_in_batch = num_items_in_batch.unsqueeze(0).expand(self.args.n_gpu, -1) - # Divide by number of devices with the same batch; without gathering, local labels are not duplicated across SP ranks - model_sp_replicas = self._model_sp_size if self.args.average_tokens_across_devices else 1 - num_items_in_batch = num_items_in_batch / ( - self.get_tp_size() * self.get_cp_size() * self.get_sp_size() * model_sp_replicas - ) + if self.args.average_tokens_across_devices: + # Divide by number of devices with the same batch + num_items_in_batch = num_items_in_batch / ( + self.get_tp_size() * self.get_cp_size() * self.get_sp_size() + ) return num_items_in_batch @@ -2464,10 +2464,6 @@ def _prepare_context_parallel_inputs( tuple: (context_manager, prepared_inputs) where context_manager is either the context parallelism wrapper or a no-op context """ - if self._model_sp_size > 1: - # a model loaded with `DistributedConfig(sp_size=N)` splits its own inputs - return contextlib.nullcontext, inputs - if ( getattr(self.accelerator, "parallelism_config", None) is not None and self.accelerator.parallelism_config.cp_enabled @@ -2568,10 +2564,9 @@ def set_initial_training_values( len_dataloader = len(dataloader) if has_length(dataloader) else None total_train_batch_size = self.get_total_train_batch_size(args) - # Account for Sequence Parallelism (SP) dataloader adapter's effect - sp_size = self.get_sp_size() - if sp_size > 1 and len_dataloader is not None: - len_dataloader = len_dataloader * sp_size + # Account for DeepSpeed Sequence Parallelism (SP) dataloader adapter's effect + if self._is_deepspeed_sp_enabled and len_dataloader is not None: + len_dataloader = len_dataloader * self.get_sp_size() # Case 2: We have a dataloader length and can extrapolate if len_dataloader is not None: @@ -2631,21 +2626,18 @@ def get_total_train_batch_size(self, args: TrainingArguments) -> int: - SP (Sequence Parallelism): Sequences split using ALST/Ulysses (DeepSpeed) All dimensions are separate and multiplicative: world_size = dp_size * tp_size * cp_size * sp_size - A model sharded at load time with `DistributedConfig(sp_size=N)` replicates each batch over its `sp` ranks too. """ - dp_world_size = ( - args.world_size // self.get_tp_size() // self.get_cp_size() // self.get_sp_size() // self._model_sp_size - ) + dp_world_size = args.world_size // self.get_tp_size() // self.get_cp_size() // self.get_sp_size() return self._train_batch_size * args.gradient_accumulation_steps * dp_world_size def get_sp_size(self) -> int: - """Get the sequence parallel size""" - if getattr(self.accelerator, "parallelism_config", None) is None: - return 1 - else: - pc = self.accelerator.parallelism_config + """Get the sequence parallel size from either the model (`DistributedConfig`) or Accelerate.""" + if (model_sp := getattr(self.model, "sp_size", None) or 1) > 1: + return model_sp + if (pc := getattr(getattr(self, "accelerator", None), "parallelism_config", None)) is not None: return pc.sp_size + return 1 def get_cp_size(self) -> int: """Get the context parallel size""" @@ -2656,14 +2648,14 @@ def get_cp_size(self) -> int: return pc.cp_size @property - def _model_sp_size(self) -> int: - """Sequence parallel size from `DistributedConfig(sp_size=N)` (distinct from Accelerate/DeepSpeed `get_sp_size`), or 1.""" - return getattr(self.model, "_sp_size", None) or 1 + def _is_deepspeed_sp_enabled(self) -> bool: + pc = getattr(getattr(self, "accelerator", None), "parallelism_config", None) + return pc is not None and pc.sp_backend == "deepspeed" and pc.sp_enabled @property - def _sp_batch_replicas(self) -> int: - """Number of ranks sharing a batch when SP is enabled (`sp_size * tp_size`), or 1 otherwise.""" - return self._model_sp_size * self.get_tp_size() if self._model_sp_size > 1 else 1 + def _batch_replicas(self) -> int: + """Number of ranks sharing the same batch (`tp_size * sp_size`), used to avoid over-counting tokens/flops.""" + return self.get_tp_size() * (1 if self._is_deepspeed_sp_enabled else self.get_sp_size()) def get_tp_size(self) -> int: """Get the tensor parallel size from either the model or DeepSpeed config.""" @@ -2822,7 +2814,7 @@ def _track_num_input_tokens(self, inputs): input_tokens = torch.as_tensor(input_tokens, device=self.args.device, dtype=torch.int64) total_tokens = self.accelerator.gather(input_tokens).sum().item() - self.state.num_input_tokens_seen += total_tokens // self._sp_batch_replicas + self.state.num_input_tokens_seen += total_tokens // self._batch_replicas def _mixed_mesh_grad_norm(self, model, max_norm): """ @@ -2995,7 +2987,7 @@ def evaluation_loop( prediction_loss_only = prediction_loss_only if prediction_loss_only is not None else args.prediction_loss_only - if self._model_sp_size > 1 and not prediction_loss_only: + if self.get_sp_size() > 1 and not self._is_deepspeed_sp_enabled and not prediction_loss_only: raise ValueError( "Sequence parallelism (`sp_size > 1`) only supports evaluating the loss: each rank only holds the " "logits of its own slice of the sequences, and gathering them would repeat the batch of every sp " @@ -4298,7 +4290,7 @@ def store_flos(self) -> None: """Store the number of floating-point operations that went into the model.""" if self.args.parallel_mode == ParallelMode.DISTRIBUTED: total_flos = distributed_broadcast_scalars([self.current_flos], device=self.args.device).sum().item() - self.state.total_flos += total_flos / self._sp_batch_replicas + self.state.total_flos += total_flos / self._batch_replicas self.current_flos = 0 else: self.state.total_flos += self.current_flos From 648b98389b01ee4ccc7d08ae171fbf0c8e44b3c0 Mon Sep 17 00:00:00 2001 From: Ferdinand Mom Date: Wed, 2 Dec 2026 23:37:04 -0800 Subject: [PATCH 5/5] [distributed] Guard against combining model SP with Accelerate SP/CP --- src/transformers/trainer.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/transformers/trainer.py b/src/transformers/trainer.py index 3706c1e4847e..00e88fc1171c 100755 --- a/src/transformers/trainer.py +++ b/src/transformers/trainer.py @@ -866,6 +866,12 @@ def create_accelerator_and_postprocess(self) -> None: model_sp_size = getattr(self.model, "sp_size", None) or 1 if model_sp_size > 1: + pc = getattr(self.accelerator, "parallelism_config", None) + if pc is not None and (pc.sp_enabled or pc.cp_enabled): + raise ValueError( + "Cannot combine model-level sequence parallelism (`DistributedConfig(sp_size>1)`) with " + "Accelerate's `ParallelismConfig` sequence or context parallelism (`sp_size > 1` or `cp_size > 1`)." + ) # Ranks in the same (sp, tp) group share a batch, so the dataloader shards only over `dp_shard`. # The SP axis is named "cp" because Accelerate's dataloader reads that dimension for shared batches. tp_size = getattr(self.model, "tp_size", None) or 1 @@ -2260,8 +2266,9 @@ def compute_loss( and (self.model_accepts_loss_kwargs or self.compute_loss_func) and num_items_in_batch is not None ): - # TP ranks see replicated batches; `num_processes` over-counts them by `tp_size`, and the ranks of an sp - # group by `sp_size`. Mirror the divisor used in `_get_num_items_in_batch`. + # TP ranks (and the expert-parallel ranks sharing their batch) see replicated batches; `num_processes` + # over-counts them by `tp_size`, and the ranks of an sp group by `sp_size` (the model already scales its + # gradient by `sp_size`). Mirror the divisor used in `_get_num_items_in_batch`. loss_scale = self.accelerator.num_processes // (self.get_tp_size() * self.get_sp_size()) loss *= loss_scale if self.args.n_gpu <= 1 else self.args.n_gpu