Skip to content

[DeepSeek] Re-enable backward for on-device all_to_all_v - #1013

Merged
kwen2501 merged 12 commits into
mainfrom
symm_bwd
Mar 26, 2025
Merged

kwen2501 merged 12 commits into
mainfrom
symm_bwd

Conversation

@kwen2501

@kwen2501 kwen2501 commented Mar 24, 2025 •

Copy link
Copy Markdown
Contributor

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)))

@facebook-github-bot facebook-github-bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 24, 2025
@kwen2501
kwen2501 requested review from lessw2020 and wconstab March 24, 2025 21:53
@kwen2501

Copy link
Copy Markdown
Contributor Author

cc @EugenHotaj

@EugenHotaj

EugenHotaj commented Mar 25, 2025 •

Copy link
Copy Markdown
Contributor

@kwen2501 Weirdly I'm still getting the double backwards issue when running for more than 1 step. First step works fine but second fails:

[rank4]: RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.

@lessw2020

lessw2020 commented Mar 25, 2025 •

Copy link
Copy Markdown
Contributor

@kwen2501 - Single pass forward/backward is working nicely. Inference works as well.

However, similar to what @EugenHotaj reported - I made a quick training loop and hit the same issue re: double backward error if you continue to the next iteration:

Epoch 1/3, Step 1/10, Loss: 705.1830
[rank6]: Traceback (most recent call last):
[rank6]:   File "/home/less/.conda/envs/tritondev/lib/python3.12/site-packages/torch/distributed/pipelining/_backward.py", line 352, in stage_backward
[rank6]:     torch.autograd.backward(
[rank6]:   File "/home/less/.conda/envs/tritondev/lib/python3.12/site-packages/torch/autograd/__init__.py", line 353, in backward
[rank6]:     _engine_run_backward(
[rank6]:   File "/home/less/.conda/envs/tritondev/lib/python3.12/site-packages/torch/autograd/graph.py", line 824, in _engine_run_backward
[rank6]:     return Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
[rank6]:            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank6]: RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.

token_gather_buf: Optional[torch.Tensor] = None
input_splits: Optional[torch.Tensor] = None
output_splits: Optional[torch.Tensor] = None
token_send_buf: Optional[torch.Tensor] = []

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.

eh.. Optional[torch.Tensor] or List?


# Assuming worst case, 2x tokens are routed to one EP rank
overflow = 2
OnDeviceAllToAllV.max_output_len = (

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.

might be better if we don't modify the attributes of a global that could be shared by other usages? (I realize for now this is only used here..). I guess a cleaner pattern might be to create a class that encapsulates the states of the kernel- perhaps both its 'buffers' and its 'max-size' - then we can instantiate this object at the init of MoE and share it between layers?

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.

That's a good point. I don't know if a torch.autograd.Function is instantiatable (as an object). The reason it that its forward and backward methods are staticmethod, which have no access to self. So, is torch.autograd.Function by design shared?

MoE.output_splits = symm_mem.empty(
self.ep_size, dtype=torch.int64, device=device
)
for _ in range(self.microbatches):

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.

we start to bleed more parallelism info into the model def.. seems logical to do it this way for now but conceptually what other options would we have?

normally the pipeline runtime manages the lifetime of the microbatch activations indirectly: it holds onto microbatch activations until running backward, then frees them via cuda caching allocator for reuse.

I guess for symm memm, we could rely on an allocator too? we could just ask the symm_memm allocator for new buffers on each forward pass. when would they be freed- would they naturally be kept alive as 'activations' and freed automatically (returned to the cache) once the pipelining runtime cleared their backward pass? I think that would be a lot cleaner than having to keep track of current microbatch inside model state.

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.

we start to bleed more parallelism info into the model def..

True and false. I sort of treat setup_symm_mem as a "side" helper to model definition in strict term. This is also the practice when people need to setup KV cache.

we could rely on an allocator too?

Yep, great idea.

device=grad_output.device,
)

# TODO: is there a way to tell autograd to feed grad_output directly to

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.

what is preventing this today?

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.

cc @janeyx99 @soulitzer @albanD. This is what we talked about last week.
Is there a way to control where grad_output is fed (by a downstream op) so that we can avoid a copy (into comm-optimized memory) here?

@soulitzer soulitzer Mar 26, 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.

How much do we care about eager? It feels like compile is probably the right place for these types of optimizations.

General support in eager is tricky because the backward formula rather than the engine is what produces the grad_output, so you'd essentially either need to rewrite all backward formulas to use the out-variant or interpose on the out-of-place op via some kind of mode or subclass. Also, we don't even always have control over the backward formula, e.g. if it is a custom backward kernel.

If we care about a specific set of ops only, maybe one thing to try is just to have the all_to_all return a TorchFunctionSubclass that overrides a specific set of ops that you care about. You can also expose this as an extension point if users have their own ops they'd like to do this optimization for.
The torch function implementations of those ops would be custom autograd.Functions whose backward returns a grad_output in symmetric memory.

If we're looking for something fully general and automatic, maybe we need a lower level abstraction, e.g. some kind of context manager than can control how new tensor outputs are allocated. Even then its not very easy, because we'd need to somehow only apply this new context manager on the very last operation which produces the grad_output.

@kwen2501

kwen2501 commented Mar 25, 2025 •

Copy link
Copy Markdown
Contributor Author

@EugenHotaj @lessw2020 Thank for trying and reporting the error!
I just uploaded a solution per @wconstab 's suggestion -- we need to call .detach() on the symm-mem buffer before a second use. The purpose is to detach it from autograd's computational graph.

@kwen2501

Copy link
Copy Markdown
Contributor Author

I have also bumped the steps to 2 in run.py to provide test coverage.

@lessw2020 lessw2020 left a comment

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.

working nicely!
1 - I ran with 10 iters and also implemented a memory check to ensure that max_reserved memory is not inflating during the iters. It is not and remains stable.

2 - Will has good points re: potential allocator class and maybe improving kernel config encapsulation but I'd prefer to approve and land this working code sooner, so I can start expanding a full training loop on real data instead of holding this out, but maybe talk with Will. (also, these other items should be made as issues for tracking? )

@EugenHotaj

EugenHotaj commented Mar 25, 2025 •

Copy link
Copy Markdown
Contributor

@kwen2501 thanks this worked for me as well! For DSV2-lite it seems to be slower (and maybe uses slightly more memory) than using non-symm memory. Do we expect to only see benefits once we scale to DSV3?

Edit: for comparison here is the non-symm memory:

loss=1.7231|grad_norm=12.8125|res=106.24|time_per_step=42.08
loss=1.7459|grad_norm=12.8750|res=115.99|time_per_step=7.84
loss=1.8076|grad_norm=12.3125|res=116.03|time_per_step=7.58
loss=1.2751|grad_norm=8.0625|res=116.03|time_per_step=8.21
loss=1.7593|grad_norm=10.6875|res=116.21|time_per_step=7.48
loss=1.3248|grad_norm=8.1250|res=116.21|time_per_step=7.95
loss=1.5555|grad_norm=8.7500|res=116.35|time_per_step=7.50

vs the symm memory

loss=1.7231|grad_norm=12.8125|res=111.11|time_per_step=41.19
loss=1.7450|grad_norm=12.8750|res=120.85|time_per_step=9.53
loss=1.8054|grad_norm=12.2500|res=120.90|time_per_step=9.36
loss=1.2764|grad_norm=8.0625|res=120.90|time_per_step=9.39
loss=1.7592|grad_norm=10.6875|res=119.10|time_per_step=9.85
loss=1.3240|grad_norm=8.1250|res=121.93|time_per_step=9.32
loss=1.5543|grad_norm=8.8125|res=121.93|time_per_step=9.30

@kwen2501

kwen2501 commented Mar 25, 2025 •

Copy link
Copy Markdown
Contributor Author

@EugenHotaj Thanks for the comparison!
The reason is symm-mem is slower atm is likely due to:
(1) an extra copy before the "outbound" shuffle:
https://github.com/pytorch/torchtitan/pull/1013/files#diff-6d9125c2135d1f9e278b7430dddbed0af3deccf10257201240c01bb7b2bfaed1R608-L583
(2) an extra copy inside backward:
https://github.com/pytorch/torchtitan/pull/1013/files#diff-495402880411484ed0f60f3875cfc3d2630b335aa21c801263a3fed537ee0a2eR236-R240

If we don't need the training, these two copies are both avoidable.

To make them go away, we may need more changes from pytorch side, for example as @wconstab and @lessw2020 mentioned, having an allocator backed by symm mem, so that the last op's output are directly generated there, rather than the copy.

@kwen2501
kwen2501 merged commit 1daca4c into main Mar 26, 2025
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
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