Repository navigation
Capture short kernel sequences to graph - #4318
Conversation
|
@inkcherry, can you please give more description of this PR? |
@tjruwase added : ) |
|
Sorry for not replying in time due to regional holidays~. import torch
b=None
def func(a):
global b
b = a
for _ in range(10):
b = b + 1
s = torch.cuda.Stream()
a = torch.full((1000,), 1, device="cuda")
static_mem = a.data_ptr()
with torch.cuda.stream(s):
g = torch.cuda.CUDAGraph()
torch.cuda.empty_cache()
with torch.cuda.graph(g):
func(a)
torch.cuda.current_stream().wait_stream(s)
# # 1 This may lead to a crash because the static_mem is freed, or if another variable reallocates static_mem, it will lead to incorrect behavior.
# a = None
# torch.cuda.empty_cache()
# #...
# g.replay()
# print(b.sum().item())
# # 2 This will not crash but could produce incorrect results due to the memory change
# a = torch.full((1000,), 2, device="cuda")
# g.replay()
# print(b.sum().item())
# #3 This is correct, we need to make the memory fix.
# a.copy_(torch.full((1000,), 2, device="cuda"))
# g.replay()
# print(b.sum().item()) So if the address changes, will lead to unexpected behavior. i-th_call_update_hp_grads_mem_list += f"{hp_grad.data_ptr()},{lp.grad.data_ptr()}"and check if each |
accelerator interface for graph API
| def create_graph(self): | ||
| return torch.cuda.CUDAGraph() | ||
|
|
||
| def capture_to_graph(self, graph): |
There was a problem hiding this comment.
please change the interface to add parameters such as (graph, pool=None, stream=None) to align with https://pytorch.org/docs/master/generated/torch.cuda.graph.html#torch.cuda.graph
There was a problem hiding this comment.
this API at https://pytorch.org/docs/master/generated/torch.cuda.CUDAGraph.html#torch.cuda.CUDAGraph.pool is also important, it is used to share the memory pool between graphs, we can add this API in this PR or in future PR when it is really required.
|
Thank you all for your reviews and suggestions. |
|
It seems that the failure is not caused by this modification, and I can pass it locally. Could you please retrigger the check? Thank you very much! @tjruwase |
|
@inkcherry, can you please check the formatting issue? |
Thanks for your reminder . I have now fixed the formatting. @tjruwase |
|
It seems that this CI workflow is a bit unlucky. Two of the commit passed the ci check, while others seem to have encountered some failures that were not caused by this PR. |
|
@inkcherry, thanks it is no trouble at all. We appreciate your great contributions! |
|
@tjruwase The CI has all passed. Just a reminder in case you missed it |
**Motivation:** 1. This is a series of cases where short kernel sequences are launched and executed serially(no dynamic shape), with the launch overhead being much higher than the execution overhead. We can use a graph to solve this problem. Compared to ```multi-tensor-apply```, using graph is more concise and only requires PyTorch as a dependency. 2. Some device software stacks also support lazy-mode PyTorch, enabling full utilization of the compiler to perform graph optimization. However, in lazy mode, operation accumulation time (host time) could become significantly higher compared to device time in such scenario, and devices are usually not well utilized. By using the same API(after adding to accelerator cc @delock ) with cuda graph, this issue could also be resolved. **Change:** We modified three functions, ```update_hp_grads```. Here, we executed the operations for the CPU and GPU separately because the graph is unable to record the execution of CPU operations. Additionally, the data input required by the graph must not have its address modified, or the address modification must be captured by the capture operation(In this case, set ```replay_first_step``` to ```True```). Therefore, we changed ```grad=None``` to ```grad.zero_()```. Similarly, we have also placed some inputs that require fixed addresses in the ```graph_cache``` For ```clip_tensors_by_global_norm```, ```clip_coef``` is a scalar with a non-fixed value, so it needs to be moved to the GPU when using a graph. For ```total_norm = sum ([t. data. float (). norm (norm_type). item () * * norm_type for t in input_tensors])```, ```item () ```, synchronous operation is also not supported by graph. We directly put the ```sum``` and ```* * norm_type``` on the GPU to execute the computation. Other similar scenarios can also use this ```graph_process()```, or a slightly modified version of ```graph_process()``` you can checkout [4abab21](deepspeedai@4abab21) and set it to True here to do some benchmarking. deepspeedai@4abab21#diff-f8f0b3feb55b0374615405e542c1c3e0f017982b177c46c562bf688532ac935cR42 --------- Co-authored-by: Olatunji Ruwase <[email protected]>
Fixes deepspeedai#8604 Follow-up to deepspeedai#4318 (graph operations for short kernel sequences). ## Summary - Implement create_graph / capture_to_graph / replay_graph on NPU_Accelerator via the graph API torch_npu ships: torch.npu.NPUGraph() creates the graph object, torch.npu.graph(graph, pool, stream) is the capture context manager, and graph.replay() replays. Previously NPU_Accelerator carried the stub that deepspeedai#4318 originally left (None / a no-op context / nothing), so graph_process cached an empty graph and every subsequent "replay" did nothing: with graph_harvesting enabled, gradient norms silently went stale, clipping silently stopped, and the hp→lp gradient write-back silently stopped — reproduced on hardware (see below). - Mirrors the HPU (deepspeedai#4912), MLU (deepspeedai#6472), and SUPA (deepspeedai#8054) implementations, which wrap their runtime graph APIs the same way. - Adds tests/unit/accelerator/test_npu_accelerator.py with three hardware-independent contract tests that stub torch.npu and run on CPU-only CI, following the pattern of tests/unit/accelerator/test_mps_accelerator.py. ## Implementation notes The torch_npu graph API. NPUGraph wraps the runtime's graph object with capture_begin / capture_end / replay / reset / pool. torch.npu.graph(graph, pool, stream) is the context manager that performs the synchronization, cache cleanup, side-stream switching, and capture begin/end around the with block. pool and stream pass through positionally and default to None; graph_process captures without pool/stream, so the defaults are part of the contract. The graph APIs are core torch_npu APIs available across the torch versions DeepSpeed supports, so the methods call them directly with no existence checks — matching the CUDA/HPU/MLU/SUPA implementations. What it unblocks. The whole graph_harvesting chain already existed and is accelerator-agnostic: ds_config["graph_harvesting"]: true → engine.graph_harvesting → BF16_Optimizer(graph_harvesting=True) → graph_process (gradient norm, clipping, update_hp_grads). Implementing the trio is the only missing piece on NPU. Performance on Ascend 910B4 Whole-block timing with torch.npu.synchronize() on both sides of the block, 3 rounds, best round (shared-box methodology), CANN 8.5.0, torch 2.9.0+cpu, torch_npu 2.9.0.post7, Ascend 910B4 (aarch64): | Workload | eager (us/iter) | graph replay (us/iter) | speedup | |---|---|---|---| | 200 independent tiny ops (norm-style) | 6456 | 910 | 7.1x | | 50-step chained small ops (clip-style) | 3067 | 135 | 22.7x | | 20 ops on a 1M-element tensor | 1271 | 307 | 4.1x | End-to-end: with graph_harvesting: true on Ascend 910B4, _norm_tensors, clip_tensors, and _update_hp_grads_func are all captured into graph_cache, and 5 training steps (BF16_Optimizer, bf16 + fp32 gradient accumulation) are bitwise-identical to eager execution (equal losses, torch.equal parameters). Before/after: the same graph_process scenario run against the stub vs. this implementation — with the stub the reported norm froze at its first-step value, clipping stopped being applied, and the hp accumulation stopped, with no error raised; with this change all three track eager exactly. ## Test plan - pre-commit run --files on touched paths — yapf, flake8, check-torchdist, check-torchcuda, check-license, codespell all pass - pytest tests/unit/accelerator/ — 5 passed (3 new NPU contract tests + 2 existing MPS tests) - pytest tests/unit/v1/pin_memory/ — 45 passed (no regression) - Real-device on Ascend 910B4: capture → replay parity across two consecutive replays and explicit pool/stream arguments; graph_harvesting end-to-end chain; stub-vs-fix corruption demonstration ## Known limitation - Pre-existing and unrelated to NPU: engine.step() calls zero_grad() with the torch default set_to_none=True, which trips the graph_harvesting assert in deepspeed/runtime/bf16_optimizer.py on every accelerator. The end-to-end validation above calls optimizer.step() with zero_grad(set_to_none=False); worth a separate issue. --------- Signed-off-by: Zizhao Tang <[email protected]>

Motivation:
multi-tensor-apply, using graph is more concise and only requires PyTorch as a dependency.Change:
We modified three functions,
update_hp_grads. Here, we executed the operations for the CPU and GPU separately because the graph is unable to record the execution of CPU operations. Additionally, the data input required by the graph must not have its address modified, or the address modification must be captured by the capture operation(In this case, setreplay_first_steptoTrue). Therefore, we changedgrad=Nonetograd.zero_(). Similarly, we have also placed some inputs that require fixed addresses in thegraph_cacheFor
clip_tensors_by_global_norm,clip_coefis a scalar with a non-fixed value, so it needs to be moved to the GPU when using a graph.For
total_norm = sum ([t. data. float (). norm (norm_type). item () * * norm_type for t in input_tensors]),item (), synchronous operation is also not supported by graph. We directly put thesumand* * norm_typeon the GPU to execute the computation.Other similar scenarios can also use this
graph_process(), or a slightly modified version ofgraph_process()you can checkout
4abab21 and set it to True here to do some benchmarking.
4abab21#diff-f8f0b3feb55b0374615405e542c1c3e0f017982b177c46c562bf688532ac935cR42