Skip to content

[DeepSeek] all-to-all-v kernel writes out output_splits - #941

Merged
kwen2501 merged 7 commits into
gh/kwen2501/5/basefrom
gh/kwen2501/5/head
Mar 20, 2025
Merged

kwen2501 merged 7 commits into
gh/kwen2501/5/basefrom
gh/kwen2501/5/head

Conversation

@kwen2501

@kwen2501 kwen2501 commented Mar 7, 2025 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

This PR contains three changes:

1. all-to-all-v kernel writes out `output_splits` instead of total received
(so that we can use the split info as `input_splits` in the second shuffle or backward)

2. Add backward for all_to_all_v (WIP)
  
3. Move parts of the model out of `no_grad()`

ghstack-source-id: 8e0dda40b4dc9206343a020c42e8cd8c5741f860
Pull Request resolved: #941

Test

$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done

cc @yifuwang @ngimel

kwen2501 added a commit that referenced this pull request Mar 7, 2025
@facebook-github-bot facebook-github-bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 7, 2025
# )
# torch.testing.assert_close(self.output_splits, expected_splits)
# Received tokens from all other ranks. TODO: use mask instead
received = self.output_splits.sum().item()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is an h2d sync?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is. I am looking for an mechanism that can consume the output_splits directly.
Would your PR be related? pytorch/pytorch#148531
Without that mechanism, I am putting a sync here for now.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yifuwang

yifuwang commented Mar 7, 2025

Copy link
Copy Markdown

Looks good. Though you probably want to return both received and output_split_sizes. This doesn't avoid the CPU sync if you need received on the host, but avoids a sum kernel launch.

…total received"


cc yifuwang ngimel

[ghstack-poisoned]
kwen2501 added a commit that referenced this pull request Mar 10, 2025
1. all-to-all-v kernel writes out `output_splits` instead of total received
(so that we can use the split info in backward)

ghstack-source-id: 8e0dda4
Pull Request resolved: #941

2. Add backward for all_to_all_v

ghstack-source-id: 8e0dda4
Pull Request resolved: #943

3. [DeepSeek] Enable backward
@kwen2501 kwen2501 changed the title all-to-all-v kernel writes out output_splits instead of total received [DeepSeek] Enable backward Mar 10, 2025
This PR contains three changes:
    
    1. all-to-all-v kernel writes out `output_splits` instead of total received
    (so that we can use the split info as `input_splits` in backward)
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #941
    
    2. Add backward for all_to_all_v
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #943
    
    3. [DeepSeek] Enable backward

Test
```
$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done
```

cc yifuwang ngimel

[ghstack-poisoned]
kwen2501 added a commit that referenced this pull request Mar 10, 2025
1. all-to-all-v kernel writes out `output_splits` instead of total received
(so that we can use the split info in backward)

ghstack-source-id: 8d64775
Pull Request resolved: #941

2. Add backward for all_to_all_v

ghstack-source-id: 8d64775
Pull Request resolved: #943

3. [DeepSeek] Enable backward
This PR contains three changes:
    
    1. all-to-all-v kernel writes out `output_splits` instead of total received
    (so that we can use the split info as `input_splits` in backward)
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #941
    
    2. Add backward for all_to_all_v
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #943
    
    3. [DeepSeek] Enable backward

Test
```
$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done
```

cc yifuwang ngimel

[ghstack-poisoned]
kwen2501 added a commit that referenced this pull request Mar 10, 2025
1. all-to-all-v kernel writes out `output_splits` instead of total received
(so that we can use the split info in backward)

ghstack-source-id: fd767a0
Pull Request resolved: #941

2. Add backward for all_to_all_v

ghstack-source-id: fd767a0
Pull Request resolved: #943

3. [DeepSeek] Enable backward
@kwen2501

kwen2501 commented Mar 10, 2025 •

Copy link
Copy Markdown
Contributor Author

@yifuwang Good idea. I hope I can find a way to not used the summed received entirely in some later PRs. So just keeping things as is for now.

This PR contains three changes:
    
    1. all-to-all-v kernel writes out `output_splits` instead of total received
    (so that we can use the split info as `input_splits` in backward)
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #941
    
    2. Add backward for all_to_all_v
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #943
    
    3. [DeepSeek] Enable backward

Test
```
$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done
```

cc yifuwang ngimel

[ghstack-poisoned]
kwen2501 added a commit that referenced this pull request Mar 11, 2025
1. all-to-all-v kernel writes out `output_splits` instead of total received
(so that we can use the split info in backward)

ghstack-source-id: 77d7240
Pull Request resolved: #941

2. Add backward for all_to_all_v

ghstack-source-id: 77d7240
Pull Request resolved: #943

3. [DeepSeek] Enable backward
@kwen2501
kwen2501 requested a review from fduwjj March 12, 2025 00:10

@torch.no_grad()
def moe_infer(self, x, topk_ids, topk_weight):
def moe_forward(self, x, topk_ids, topk_weight):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would be nice to add docstring to moe_forward (well, probably to other methods too) that document the shapes of the input tensors, e.g. topk_ids: [seq_len, k]

# Since this is an "aritificial" index creation (final outcome being
# `idxs`), we don't need gradients here.
with torch.no_grad():
# [seq_len, n_routed_experts]

@wconstab wconstab Mar 18, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe collaps the 3 lines (cnts=, cnts.scatter_, tokens_per_expert) into a group of 3 and give one comment above them that says
# form a one_hot encoding of shape (seq_len, experts) and then sum to get #tokens per expert
and maybe rename tokens_per_expert to num_tokens_per_expert or something?

tokens_per_expert = cnts.sum(dim=0)
# Token indices for each expert
idxs = topk_ids.view(-1).argsort()
sorted_tokens_shape = idxs.shape + x.shape[1:]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so we flatten the idxs (each sequence is appended to one long row), then we shuffle them so that tokens from different sequences that are going to the same expert are next to each other in memory.

and x.shape is what, (bs,h)? if so, then i think it makes sense that sorted_tokens_shape would be (bs, h)

sorted_tokens_shape = idxs.shape + x.shape[1:]

# Take necessary space from the `token_send_buf` symm mem
sorted_tokens = self.token_send_buf[: idxs.shape[0]]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: is [: idxs.shape[0]] broken formatting? i thought it would be :idxs... (no space) - otherwise looked like it was 2 dim and missing comma.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I remember the space is required by formatter too.


# Take necessary space from the `token_send_buf` symm mem
sorted_tokens = self.token_send_buf[: idxs.shape[0]]
sorted_tokens.copy_(x[idxs // topk_ids.shape[1]])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

x: [bs, h]?
idxs: [b
s]?
topk_ids: [s, k]

idxs represents "the indices of tokens respective to b*s flattening, such that the tokens for expert0 come first, etc", right?

i'm confused about what idxs // topk_ids.shape[1] is doing.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok- the explanation is

  1. idxs contains the indexes of tokens in a sequence that is K times longer than the original input sequence, due to the view(-1) above before the argsort
  2. the index values logically refer to tokens in the original input sequence (x) so to make them useful again we floor-didide by k (the value used for topk).

output_splits: torch.Tensor,
input: torch.Tensor,
input_splits: torch.Tensor,
group: dist.ProcessGroup = dist.group.WORLD,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we default this? it feels like usually you need to know what group you're doing this over. i could see leaving it as 'world' or unit testing purposes but for any real usage in models it seems unlikely the default would be sufficient?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default here is similar to torch.dist defaulting group to None

grad_input_splits = torch.empty_like(grad_output_splits)
grad_input = grad_output.new_empty(*ctx.input_shape)
_on_device_all_to_all_v(
grad_input, grad_input_splits, grad_output, grad_output_splits, group=group

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I might be missing something but I don't think this backward() function is ever being called -- otherwise group would fail here since it should be ctx.group

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yea good point. but it does look like the on_device all2allv is called in forward part of moe layer in a part that has gradients enabled. (it is also called under 'with no_grad()` but not exclusively)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@EugenHotaj @wconstab Thanks. You are right.
I am backing out the backward function for on_device_all_to_all_v from this PR.
The reason is that autograd does not allow touching the buffer a second time between fwd and bwd. This conflicts with sharing the symm mem buffer across layers (to save memory) as in PR #958.

Instead, I am adding backward support via the traditional all_to_all_single_autograd (Yes, there is a CPU sync.) But the backward is more stable. PR is at #989.

on_device_all_to_all_v is now limited to inference / generation.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sounds good for short term. longer term we'd want to fix the backward+symm memm issue though right? can we mark the tensor as a 'buffer' to make autograd not care about it, or something?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Autograd does not allow touching the buffer that's going to be used by autograd, is that the case here? If you still need all this memory live, then registering multiple copies with symmetric memory shouldn't be overall memory hit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wconstab @ngimel yes.
@EugenHotaj and @yifuwang suggested something similar -- we can try moving the symm mem inside an autograd function, so that it is not visible to the autograd engine.

s = 0
for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
# TODO: remove `tolist()`
for i, k in enumerate(tokens_per_expert_group.tolist()):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is still a cuda-cpu sync point, right? can we avoid it by doing a scan on device or something?

returned_tokens[idxs] = gathered_tokens
final_out = (
new_x.view(*topk_ids.shape, -1)
returned_tokens.view(*topk_ids.shape, -1)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'd also like to see topk_weight documented at the top of the function. I am assuming that this helps to implement a weighted sum for combining the expert outputs into one output, but its a little hard to follow the code.

This PR contains three changes:
    
    1. all-to-all-v kernel writes out `output_splits` instead of total received
    (so that we can use the split info as `input_splits` in backward)
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #941
    
    2. Add backward for all_to_all_v
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #943
    
    3. [DeepSeek] Enable backward

Test
```
$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done
```

cc yifuwang ngimel

[ghstack-poisoned]
@kwen2501 kwen2501 changed the title [DeepSeek] Enable backward [DeepSeek] all-to-all-v kernel writes out output_splits Mar 20, 2025
This PR contains three changes:
    
    1. all-to-all-v kernel writes out `output_splits` instead of total received
    (so that we can use the split info as `input_splits` in backward)
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #941
    
    2. Add backward for all_to_all_v
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #943
    
    3. [DeepSeek] Enable backward

Test
```
$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done
```

cc yifuwang ngimel

[ghstack-poisoned]
@kwen2501

Copy link
Copy Markdown
Contributor Author

@wconstab thanks for all the requests for comments. I will put a PR on top of the current stack -- too hard to modify this one without resolving conflicts with other PRs on top.

@kwen2501
kwen2501 merged commit 71f4e5e into gh/kwen2501/5/base Mar 20, 2025
kwen2501 added a commit that referenced this pull request Mar 20, 2025
Reland of #941  since `ghstack land <PR>` does not work now.

Original PR description:
This PR contains three changes:

1. all-to-all-v kernel writes out `output_splits` instead of total
received
(so that we can use the split info as `input_splits` in the second
shuffle or backward)

2. Add backward for all_to_all_v (WIP)
  
3. Move parts of the model out of `no_grad()`

Test
```
$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done
```
kwen2501 added a commit that referenced this pull request Mar 26, 2025
A couple changes compared to previous try in #941:
- Make `OnDeviceAllToAllV` in functional form (easier to form autograd
graph).
- Move symm-mem based splits buffer inside `OnDeviceAllToAllV` (this
part does not need gradients). This would introduce a small copy from
normal split tensor to this symm-mem backed split tensor, but since this
copy is very small (of `ep_size`), so we should be able to tolerate it,
and reduce outside dependency.
- Create different symm mem space for data buffers of different
micro-batches (from pipeline parallel), because autograd does not allow
them to step on each other's toes.

Test:
`torchrun --standalone --nproc-per-node 8 run.py`
Using traditional `torch_all_to_all`:
```
loss=tensor(681.1560, device='cuda:4', grad_fn=<MeanBackward0>)
loss=tensor(681.1560, device='cuda:5', grad_fn=<MeanBackward0>)
loss=tensor(688.9081, device='cuda:7', grad_fn=<MeanBackward0>)
loss=tensor(688.9081, device='cuda:6', grad_fn=<MeanBackward0>)
torch.linalg.norm(param.grad)=DTensor(local_tensor=104.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=136.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=104.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=136.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
```
Using symm mem all_to_all_v:
```
loss=tensor(688.9081, device='cuda:7', grad_fn=<MeanBackward0>)
loss=tensor(688.9081, device='cuda:6', grad_fn=<MeanBackward0>)
loss=tensor(681.1560, device='cuda:5', grad_fn=<MeanBackward0>)
loss=tensor(681.1560, device='cuda:4', grad_fn=<MeanBackward0>)
torch.linalg.norm(param.grad)=DTensor(local_tensor=104.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=136.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=136.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=104.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
```
MaxiBoether pushed a commit to eth-easl/torchtitan-mixtera that referenced this pull request Apr 17, 2025
Reland of pytorch#941  since `ghstack land <PR>` does not work now.

Original PR description:
This PR contains three changes:

1. all-to-all-v kernel writes out `output_splits` instead of total
received
(so that we can use the split info as `input_splits` in the second
shuffle or backward)

2. Add backward for all_to_all_v (WIP)
  
3. Move parts of the model out of `no_grad()`

Test
```
$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done
```
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 13, 2026
Reland of pytorch#941  since `ghstack land <PR>` does not work now.

Original PR description:
This PR contains three changes:

1. all-to-all-v kernel writes out `output_splits` instead of total
received
(so that we can use the split info as `input_splits` in the second
shuffle or backward)

2. Add backward for all_to_all_v (WIP)
  
3. Move parts of the model out of `no_grad()`

Test
```
$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done
```
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 13, 2026
A couple changes compared to previous try in pytorch#941:
- Make `OnDeviceAllToAllV` in functional form (easier to form autograd
graph).
- Move symm-mem based splits buffer inside `OnDeviceAllToAllV` (this
part does not need gradients). This would introduce a small copy from
normal split tensor to this symm-mem backed split tensor, but since this
copy is very small (of `ep_size`), so we should be able to tolerate it,
and reduce outside dependency.
- Create different symm mem space for data buffers of different
micro-batches (from pipeline parallel), because autograd does not allow
them to step on each other's toes.

Test:
`torchrun --standalone --nproc-per-node 8 run.py`
Using traditional `torch_all_to_all`:
```
loss=tensor(681.1560, device='cuda:4', grad_fn=<MeanBackward0>)
loss=tensor(681.1560, device='cuda:5', grad_fn=<MeanBackward0>)
loss=tensor(688.9081, device='cuda:7', grad_fn=<MeanBackward0>)
loss=tensor(688.9081, device='cuda:6', grad_fn=<MeanBackward0>)
torch.linalg.norm(param.grad)=DTensor(local_tensor=104.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=136.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=104.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=136.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
```
Using symm mem all_to_all_v:
```
loss=tensor(688.9081, device='cuda:7', grad_fn=<MeanBackward0>)
loss=tensor(688.9081, device='cuda:6', grad_fn=<MeanBackward0>)
loss=tensor(681.1560, device='cuda:5', grad_fn=<MeanBackward0>)
loss=tensor(681.1560, device='cuda:4', grad_fn=<MeanBackward0>)
torch.linalg.norm(param.grad)=DTensor(local_tensor=104.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=136.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=136.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=104.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
```
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 25, 2026
Reland of pytorch#941  since `ghstack land <PR>` does not work now.

Original PR description:
This PR contains three changes:

1. all-to-all-v kernel writes out `output_splits` instead of total
received
(so that we can use the split info as `input_splits` in the second
shuffle or backward)

2. Add backward for all_to_all_v (WIP)
  
3. Move parts of the model out of `no_grad()`

Test
```
$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done
```
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 25, 2026
A couple changes compared to previous try in pytorch#941:
- Make `OnDeviceAllToAllV` in functional form (easier to form autograd
graph).
- Move symm-mem based splits buffer inside `OnDeviceAllToAllV` (this
part does not need gradients). This would introduce a small copy from
normal split tensor to this symm-mem backed split tensor, but since this
copy is very small (of `ep_size`), so we should be able to tolerate it,
and reduce outside dependency.
- Create different symm mem space for data buffers of different
micro-batches (from pipeline parallel), because autograd does not allow
them to step on each other's toes.

Test:
`torchrun --standalone --nproc-per-node 8 run.py`
Using traditional `torch_all_to_all`:
```
loss=tensor(681.1560, device='cuda:4', grad_fn=<MeanBackward0>)
loss=tensor(681.1560, device='cuda:5', grad_fn=<MeanBackward0>)
loss=tensor(688.9081, device='cuda:7', grad_fn=<MeanBackward0>)
loss=tensor(688.9081, device='cuda:6', grad_fn=<MeanBackward0>)
torch.linalg.norm(param.grad)=DTensor(local_tensor=104.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=136.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=104.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=136.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
```
Using symm mem all_to_all_v:
```
loss=tensor(688.9081, device='cuda:7', grad_fn=<MeanBackward0>)
loss=tensor(688.9081, device='cuda:6', grad_fn=<MeanBackward0>)
loss=tensor(681.1560, device='cuda:5', grad_fn=<MeanBackward0>)
loss=tensor(681.1560, device='cuda:4', grad_fn=<MeanBackward0>)
torch.linalg.norm(param.grad)=DTensor(local_tensor=104.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=136.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=136.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
torch.linalg.norm(param.grad)=DTensor(local_tensor=104.0, device_mesh=DeviceMesh('cuda', [[0, 1], [2, 3]], mesh_dim_names=('ep', 'fsdp')), placements=(Replicate(), _NormPartial(reduce_op='sum', norm_type=2.0)))
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants