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/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 03e0d7aca88a..00e88fc1171c 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,9 +774,11 @@ 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: + 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. 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,25 @@ def create_accelerator_and_postprocess(self) -> None: # create accelerator object self.accelerator = Accelerator(**args) + + 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 + 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, model_sp_size, 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 @@ -1816,8 +1836,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 @@ -2193,9 +2212,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") @@ -2247,8 +2267,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.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 @@ -2396,10 +2417,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 - num_items_in_batch = num_items_in_batch / ( - self.get_tp_size() * self.get_cp_size() * self.get_sp_size() - ) + 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 @@ -2549,10 +2571,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: @@ -2618,12 +2639,12 @@ def get_total_train_batch_size(self, args: TrainingArguments) -> int: 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""" @@ -2633,6 +2654,16 @@ def get_cp_size(self) -> int: pc = self.accelerator.parallelism_config return pc.cp_size + @property + 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 _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.""" @@ -2789,7 +2820,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() + total_tokens = self.accelerator.gather(input_tokens).sum().item() + self.state.num_input_tokens_seen += total_tokens // self._batch_replicas def _mixed_mesh_grad_norm(self, model, max_norm): """ @@ -2962,6 +2994,13 @@ def evaluation_loop( prediction_loss_only = prediction_loss_only if prediction_loss_only is not None else args.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 " + "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 +4296,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._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 new file mode 100644 index 000000000000..a0b59e290262 --- /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 = 6 +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 * 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 + + # 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..30822063994a 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,65 @@ 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: + + 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", + ) + 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()]