[BUG] MTP drops gradients to precomputed embeddings with sequence parallelism
Describe the bug
With TP=2 and sequence parallelism enabled, roll_tensor_precomputed_embeddings drops the gradient to a trainable embedding input. On two A100 GPUs with NCCL, the forward values match a dense shift and backward finishes. Both embedding .grad values are None, and both ranks warn that c10d::_allgather_base_ has no registered autograd kernel. The independent trainable branch of the test receives its exact gradient.
The precomputed roll gathers the shards into an output buffer with the native out-parameter collective. @NVIDIA/mcore-oncall, could you confirm whether the supplied decoder_input is expected to retain its MTP gradient when mtp_detach_heads=False?
Steps/Code to reproduce bug
Use two visible NVIDIA GPUs, CUDA PyTorch, and packaging. Save this as /tmp/mtp_grad.py. It loads the upstream helper and its process-group functions directly from the checkout.
import ast
import os
from pathlib import Path
from packaging.version import Version
import torch
import torch.distributed as dist
from torch.distributed.nn.functional import all_gather
# Read the original definitions from the current Megatron checkout without
# importing the rest of Megatron.
def load_roll():
ns = dict(torch=torch, PkgVersion=Version, HAVE_PACKAGING=True,
_torch_version=Version(torch.__version__))
for path, names in (
("megatron/core/utils.py",
("get_pg_size", "get_pg_rank", "get_torch_version", "is_torch_min_version")),
("megatron/core/transformer/multi_token_prediction.py",
("roll_tensor", "roll_tensor_precomputed_embeddings")),
):
tree = ast.parse(Path(path).read_text())
nodes = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in names]
if "roll_tensor" in names:
binding, = [n for n in tree.body if isinstance(n, (ast.If, ast.Try))
and any(isinstance(a, ast.Name) and a.id == "dist_all_gather_func"
for a in ast.walk(n))]
nodes.insert(0, binding)
future = ast.parse("from __future__ import annotations").body[0]
module = ast.fix_missing_locations(ast.Module(body=[future, *nodes], type_ignores=[]))
exec(compile(module, path, "exec"), ns)
if os.getenv("DIFF_GATHER") == "1":
def gather(out, value, group):
out.copy_(torch.cat(all_gather(value, group=group), dim=0))
ns["dist_all_gather_func"] = gather
return ns["roll_tensor_precomputed_embeddings"]
backend = os.getenv("BACKEND", "nccl")
device = torch.device("cpu")
if backend == "nccl":
device = torch.device("cuda", int(os.environ["LOCAL_RANK"]))
torch.cuda.set_device(device)
dist.init_process_group(backend)
try:
rank = dist.get_rank()
assert dist.get_world_size() == 2
full = torch.arange(1, 17, device=device, dtype=torch.float32).reshape(8, 1, 2)
weights = full.flip(0)
x = full.chunk(2)[rank].clone().requires_grad_()
y, _ = load_roll()(x, sp_group=dist.group.WORLD, return_sum=False)
expected_y = torch.cat((full[1:], torch.zeros_like(full[:1]))).chunk(2)[rank]
expected_grad = torch.cat((torch.zeros_like(weights[:1]), weights[:-1])).chunk(2)[rank]
torch.testing.assert_close(y, expected_y, rtol=0, atol=0)
# Keep backward valid even if the embedding path is disconnected.
side = torch.zeros_like(y, requires_grad=True)
((y + side) * weights.chunk(2)[rank]).sum().backward()
torch.testing.assert_close(side.grad, weights.chunk(2)[rank], rtol=0, atol=0)
print(f"rank {rank}: embedding grad={x.grad}, expected={expected_grad.flatten().tolist()}",
flush=True)
if os.getenv("DIFF_GATHER") == "1":
torch.testing.assert_close(x.grad, expected_grad, rtol=0, atol=0)
finally:
dist.destroy_process_group()
# Run from the root of a Megatron-LM checkout.
git switch --detach de5601f5f0dafcd34ee96972daa935200694a9ed
torchrun --nnodes=1 --master-addr=127.0.0.1 --master-port=29570 \
--nproc-per-node=2 /tmp/mtp_grad.py
DIFF_GATHER=1 torchrun --nnodes=1 --master-addr=127.0.0.1 --master-port=29571 \
--nproc-per-node=2 /tmp/mtp_grad.py
The first run leaves both input gradients None. The second changes only the gather binding and restores both gradients exactly.
Expected behavior
The original sequence-parallel path should preserve the same embedding gradient as a dense shift of the same sequence, including contributions that cross sequence-shard boundaries. For this fixture the flattened gradients are [0, 0, 15, 16, 13, 14, 11, 12] on rank 0 and [9, 10, 7, 8, 5, 6, 3, 4] on rank 1.
Additional context
- Reproduced with two A100-SXM4 GPUs, PyTorch 2.12.1+cu130, CUDA 13.0 and NCCL 2.29.7. FP32 reproduces at
91260b59andde5601f5, and BF16 reproduces atde5601f5. The TP=1 and TP=2 SP-off controls match the reference. - A two-layer HybridModel with native MTP loss also reproduced on A100/NCCL (PyTorch 2.8.0+cu128). The backbone was frozen to isolate MTP. With the original gather, the MTP projection still had a nonzero weight gradient, but the trainable projection that supplied
decoder_inputhad a zero weight gradient. Replacing only the gather restored that gradient exactly to its SP-off value (L2 norm 0.0498171). The main loss was unchanged across the controls. - The published Super VL fine-tuning recipe enables TP2 and SP. Its Omni wrapper supplies sequence-sharded embeddings, and its Megatron Core pin reproduces in the BF16 helper test.
I can reproduce the missing gradient without GPUs. On main 43a2ef6d3 with your script, BACKEND=gloo and two CPU processes (PyTorch 2.14.1):
- original gather: backward fails on both ranks with
RuntimeError: A view was created in no_grad mode and is being modified inplace with grad mode enabled.... On gloo the non-differentiableall_gather_into_tensorshows up as an error instead of a silentNone. DIFF_GATHER=1: both ranks get exactly[0, 0, 15, 16, 13, 14, 11, 12]and[9, 10, 7, 8, 5, 6, 3, 4].
The file already imports gather_from_sequence_parallel_region, whose backward is a reduce-scatter. That's the gradient this roll needs: each rank keeps only its own chunk of the rolled tensor, so a shard's gradient is the sum of the contributions from every rank, including the one across the shard boundary.
@Hiro208 are you planning to send a fix? If not, and the maintainers confirm the gradient should flow with mtp_detach_heads=False, I'd like to open a PR that switches to that helper and adds a two-rank unit test checking forward and gradient parity against a dense shift.
One more finding from checking the backward path: the zigzag context-parallel branch of roll_tensor also loses gradients at rank boundaries.
_exchange_cp_roll_boundaries uses batch_isend_irecv with newly allocated receive buffers. The forward values are correct, but gradients do not propagate back to the rank that sent each boundary token.
I reproduced this with 2 CPU/Gloo ranks, cp_group=WORLD, no SP or packing, using a weighted loss on the rolled tensor:
| Rank | Actual gradient | Expected gradient |
|---|---|---|
| 0 | [0, 101, 0, 107] |
[0, 101, 106, 107] |
| 1 | [0, 103, 104, 105] |
[102, 103, 104, 105] |
This affects differentiable inputs such as precomputed embeddings with CP > 1; token IDs and labels don't require gradients.
I haven't yet tested packed-sequence or contiguous CP paths.
Would you prefer the CP backward fix to be included in #9561, or tracked separately? The SP fix can remain independent if that makes review easier.
/claude assign
Thanks for reporting, this seems to be a bug, would you like to submit a PR to fix?
Thanks for confirming. Yes, I'll fix it. I asked @Hiro208 earlier whether they planned to send a fix and haven't heard back, so I'll go ahead.
I'll start with a draft PR for the sequence-parallel case: use gather_from_sequence_parallel_region(..., group=sp_group) in roll_tensor_precomputed_embeddings instead of the raw all-gather, so the backward reduce-scatters the gradient back to each rank, with a TP=2 sequence-parallel gradient test in test_multi_token_prediction.py.
The context-parallel boundary issue I mentioned above is a separate code path, so I'll send that as a second PR once I've also checked the packed-sequence and contiguous CP paths.
Quick update: #7834 reworked this path, and on current main the SP-only case from this issue now gets the right gradient, so I'm dropping the SP-only fix.
The zigzag CP path still loses gradients. Checked against a dense roll on 2-4 ranks:
| config | input gradient |
|---|---|
| SP=2, CP=1 | ok |
| CP=2 contiguous, with or without SP=2 | ok |
| CP=2 zigzag | one boundary row per rank gets no gradient |
| SP=2 + CP=2 zigzag | RuntimeError: A view was created in no_grad mode... |
roll_tensor gets the neighbor's boundary token through _exchange_cp_roll_boundaries and copies it in, so its gradient never returns to the owning rank, and the zigzag branch of roll_tensor_precomputed_embeddings still uses the raw all-gather for SP. I'm fixing both the way _RollLeft handles the contiguous layout and will open a draft PR shortly.
Thanks @Srivatsan6923 for reproducing this and following up on the zigzag CP case. I opened #9723 to cover the original SP case with a regression test that checks the gradient all the way back to the projection supplying decoder_input.