Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/transformers/distributed/mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
8 changes: 8 additions & 0 deletions src/transformers/modeling_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
92 changes: 65 additions & 27 deletions src/transformers/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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.")
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"""
Expand All @@ -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."""

Expand Down Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
153 changes: 153 additions & 0 deletions tests/trainer/distributed/scripts/sp_distributed_config.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading