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
509 changes: 509 additions & 0 deletions deepspeed/module_inject/autotp_sequence_sharding.py

Large diffs are not rendered by default.

21 changes: 19 additions & 2 deletions deepspeed/module_inject/layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import re
from deepspeed import comm as dist
from deepspeed.comm import pg_utils
from deepspeed.module_inject.autotp_sequence_sharding import (reduce_scatter_from_tensor_parallel_block,
take_precomputed_column_output)
from torch import nn
from torch.nn import functional as F
from torch.nn.parameter import Parameter
Expand Down Expand Up @@ -394,6 +396,11 @@ class TensorParallel_Layer(nn.Module, ABC):
tp_overlap_comm: bool = False
""" Whether to overlap communication with computation. Currently, only allreduce supports overlap. """

# Set per layer by apply_autotp_sequence_sharding: the layer's input (column) or output (row) is split along
# sequence_sharding_dim over the tensor-parallel ranks outside its block.
sequence_sharding: bool = False
sequence_sharding_dim: int = 1

def __init__(self, mp_group: Optional[dist.ProcessGroup], **kwargs: Any):
"""
Initializes the TensorParallel_Layer with optional model parallelism group and layer name.
Expand Down Expand Up @@ -906,7 +913,9 @@ def __init__(self, module, mp_group, **kwargs):
def forward(self, input):
self._assert_compiled_if_deferred()
output = torch.matmul(input, self.weight.transpose(-1, -2))
if not self.defer_collectives_to_compiler:
if self.sequence_sharding:
output = reduce_scatter_from_tensor_parallel_block(output, self.mp_group, self.sequence_sharding_dim)
elif not self.defer_collectives_to_compiler:
output = RowParallel.apply(self.mp_group, output, not self.is_training_mode())
if self.bias is not None:
output = add_bias(output, self.bias, self.is_training_mode())
Expand Down Expand Up @@ -1000,7 +1009,15 @@ def __init__(self, module, mp_group=None, skip_partition=False, gather_output=Fa

def forward(self, input):
self._assert_compiled_if_deferred()
if not self.__class__.tp_overlap_comm:
if self.sequence_sharding:
# The block input was all-gathered along the sequence; the reduce-scatter in that gather's backward
# sums this layer's input gradient together with the other column-parallel layers of the block.
output = take_precomputed_column_output(self, input)
if output is None:
output = torch.matmul(input, self.weight.transpose(-1, -2))
if self.bias is not None:
output = add_bias(output, self.bias, self.is_training_mode())
elif not self.__class__.tp_overlap_comm:
if getattr(self, 'mp_group', None) is not None and not self.defer_collectives_to_compiler:
input = ColumnParallel.apply(self.mp_group, input)
output = torch.matmul(input, self.weight.transpose(-1, -2))
Expand Down
11 changes: 11 additions & 0 deletions deepspeed/runtime/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -1102,6 +1102,17 @@ def finalize_autotp(autotp=None, attach_uc_metadata=False, require_vocab_paralle

if attach_uc_metadata:
setattr(model, UNIVERSAL_CHECKPOINT_INFO, collect_autotp_universal_checkpoint_info(model))
if tp_config.sequence_sharding:
from deepspeed.module_inject.autotp_sequence_sharding import apply_autotp_sequence_sharding
frozen = apply_autotp_sequence_sharding(model,
tp_config.tensor_parallel.tp_group,
overlap=tp_config.sequence_sharding_overlap,
zero_stage=self.zero_optimization_stage())
# Like AutoTP's own frozen replicated parameters, these get no gradient sum: reject unfreezing them.
listed = getattr(self, "_autotp_frozen_replicated_params", [])
listed_ids = {id(param) for _, param in listed}
unlisted = [(name, param) for name, param in frozen if id(param) not in listed_ids]
self._autotp_frozen_replicated_params = listed + unlisted
setattr(model, "ds_autotp_parsed", True)

if partition_config is not None:
Expand Down
15 changes: 15 additions & 0 deletions deepspeed/runtime/tensor_parallel/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,21 @@ class TPTrainingConfig(DeepSpeedConfigModel):
tp_overlap_comm: bool = False
""" Whether to overlap communication with computation. Currently, only allreduce supports overlap. """

sequence_sharding: bool = False
"""
Split the hidden states between the tensor-parallel blocks (attention, MLP) along the sequence over the
tensor-parallel ranks, so norms and residual adds run on 1/tp of the tokens (what Megatron-LM calls sequence
parallelism; unrelated to Ulysses ``sequence_parallel_size``). The row-parallel all-reduce becomes a
reduce-scatter and each block input is all-gathered. Decoder models built from attention and MLP blocks only.
"""

sequence_sharding_overlap: bool = True
"""
With sequence_sharding: run the column-parallel linears that read a block input (q/k/v, gate/up) in one
autograd node and overlap the reduce-scatter of their input gradient with their weight-gradient GEMMs. Not used
for ZeRO-3 partitioned weights.
"""

vocab_parallel_lm_head: Optional[bool] = None
"""True requires vocabulary sharding, False disables it, and None follows a supported HF tied-embedding plan."""

Expand Down
13 changes: 13 additions & 0 deletions docs/_pages/config-json.md
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,7 @@ When a HuggingFace model provides a built-in `tp_plan` (via `model.config.base_m
"autotp_size": 4,
"preset_model": "llama",
"tp_overlap_comm": false,
"sequence_sharding": false,
"vocab_parallel_lm_head": false,
"partition_config": {
"use_default_specs": false,
Expand Down Expand Up @@ -804,6 +805,18 @@ When a HuggingFace model provides a built-in `tp_plan` (via `model.config.base_m
| -------------------------------------------------------------------------------------------------------- | ------- |
| Overlap tensor-parallel allreduce communication with computation (training only). | `false` |

***sequence_sharding***: [boolean]

| Description | Default |
| ----------- | ------- |
| Split the hidden states between the attention and MLP blocks along the sequence over the tensor-parallel ranks, so norms and residual adds run on 1/tp of the tokens: each block input is all-gathered and each row-parallel output reduce-scattered instead of all-reduced. This is what Megatron-LM calls sequence parallelism; it is unrelated to Ulysses `sequence_parallel_size`. See [Sequence Sharding](/tutorials/autotp-training/#sequence-sharding). | `false` |

***sequence_sharding_overlap***: [boolean]

| Description | Default |
| ----------- | ------- |
| With `sequence_sharding`: run the column-parallel linears that read a block input (q/k/v, gate/up) in one autograd node and overlap the reduce-scatter of their input gradient with their weight-gradient GEMMs. Not used for ZeRO-3 partitioned weights. | `true` |

***vocab_parallel_lm_head***: [boolean or null]

| Description | Default |
Expand Down
70 changes: 70 additions & 0 deletions docs/_tutorials/autotp-training.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ This tutorial covers **Automatic Tensor Parallelism** for combining tensor paral
- [Introduction](#introduction)
- [Quick Start](#quick-start)
- [HuggingFace tp_plan Support](#huggingface-tp_plan-support)
- [Sequence Sharding](#sequence-sharding)
- [Vocabulary-parallel LM Loss](#vocabulary-parallel-lm-loss)
- [Custom Layer Specifications](#custom-layer-specifications)
- [Limitations](#limitations)
Expand Down Expand Up @@ -162,6 +163,75 @@ If you need to override the model's built-in `tp_plan`, provide a
`partition_config` in the DeepSpeed config -- it takes precedence.


## Sequence Sharding

By default every TP rank runs the norms, residual adds and other token-wise ops of a
decoder layer on the whole sequence and keeps their activations at full size, and
each column-parallel linear all-reduces its own input gradient in backward. With
`sequence_sharding`, the hidden states between the attention and MLP blocks are
split along the sequence over the TP ranks, 1/tp of the tokens each:

```json
"tensor_parallel": {
"autotp_size": 4,
"sequence_sharding": true
}
```

Each block all-gathers its input before its column-parallel linears, and its
row-parallel linear reduce-scatters its output instead of all-reducing it. In
backward, one reduce-scatter per block sums the input gradients of all its
column-parallel linears. The gradients of replicated parameters inside the decoder
layers (norm weights, row-parallel biases) are summed over the TP group, since each
rank now sees part of the sequence. This is the scheme Megatron-LM calls sequence
parallelism; it is unrelated to DeepSpeed's Ulysses sequence parallelism
(`sequence_parallel_size`), and the two are not combined.

`sequence_sharding_overlap` (default `true`) runs the column-parallel linears that
read a block input in one autograd node, saves only this rank's part of the input
for backward, and overlaps the backward reduce-scatter with the weight-gradient
GEMMs. ZeRO-3 partitioned weights use the plain path, and so do weights with
tensor hooks (such as the sum of GPTBigCode's shared key/value rows), whose hooks
PyTorch would skip under non-reentrant activation checkpointing.

Requirements, checked at `deepspeed.initialize()`:

- Every tensor-parallel linear inside the decoder layers belongs to a block (the
parent module of a row-parallel linear), the blocks are inside one numbered layer
list (such as `model.layers`), and every decoder layer has at least one block.
- A block is neither a whole decoder layer nor inside another block: the
row-parallel linears sit inside the attention and MLP modules, not directly in the
decoder layer (as OPT's `fc2` does), because the decoder layer adds the residual to
the block output.
- The sequence length is divisible by `autotp_size` (checked in the forward pass).
- No column-parallel layer gathers its output, and the DeepCompile `autotp` pass is
not used.
- No AutoEP MoE layer is inside the decoder layers: AutoEP + AutoTP folding expects
every TP rank to hold the whole sequence.
- No other routed MoE layer (a module with `experts` and a `gate` or `router`) is
inside the decoder layers: the TP ranks hold different tokens, so they could call
different experts, and a gradient sum or block gather that runs on some ranks only
would hang.

The modules of a decoder layer outside its blocks (an MLP left unsharded, for
example) run on this rank's part of the sequence, so they must act on each token
alone, and they must use every one of their parameters on every rank whatever the
tokens are: a replicated parameter's gradient is summed over the TP group, and a
rank whose tokens skip the parameter would not join that sum. Shard every attention
module: an unsharded attention would attend over the wrong tokens. These two
conditions are not checked.

At ZeRO stages 0, 1 and 2 the gradient sum of a replicated parameter runs in a
tensor hook. PyTorch skips that hook when a custom autograd function, such as a
fused norm kernel, saves the parameter inside non-reentrant activation
checkpointing (the Hugging Face `gradient_checkpointing_enable()` default); the
backward pass then raises an error instead of training on a partial gradient.
ZeRO-3 sums these gradients after accumulation and is not affected.

The hidden states are gathered again after the last decoder layer, so the final
norm, output layer and loss see the whole sequence. Combine with
`vocab_parallel_lm_head` (below) to keep the output layer and loss sharded as well.

## Vocabulary-parallel LM Loss

Causal language models normally gather the complete `lm_head` output before
Expand Down
Loading
Loading