Skip to content

feat(device): run offload and CUDA graphs on non-CUDA accelerators (MUSA) - #111

Open
cennn wants to merge 19 commits into
mainfrom
feat/device-agnostic-main
Open

cennn wants to merge 19 commits into
mainfrom
feat/device-agnostic-main

Conversation

@cennn

@cennn cennn commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator

🗂️ PR Category

  • ✨ New Feature
  • 🚀 Optimization (performance, memory, etc.)
  • 💥 Breaking Change
  • 🐛 Bug Fix
  • 🛠️ Development / Refactoring
  • 📚 Documentation
  • 🧹 Chore (Dependencies, CI/CD, Configuration, etc.)
  • 🧪 Testing

📝 Description

The offload runtime, the CUDA graph manager, the runtime estimator, NVTX profiling and EVT fusion called torch.cuda directly, so MagiCompiler could not run on other PyTorch accelerator backends such as Moore Threads MUSA, where offload matters most: models that do not fit a card are exactly what these devices are asked to run. This PR makes those paths device-agnostic with CUDA behaviour unchanged, and supersedes #90 and #96. It is #98 (with #107, keep_on_device_bytes, underneath) merged with current main and opened against main, since a stacked PR never triggers the integration CI.

1. One Platform object per accelerator holds every device difference.
magi_compiler.accelerator.PLATFORM is a CudaPlatform or a MusaPlatform (MUSA when torch_musa is installed). It carries what the code branches on (device_type, sm, nvtx, emit_nvtx, host_register, profiler_start/stop, graph_cls, graph_capture_error_mode, has_symm_mem) and forwards everything else to torch.<device_type>, so PLATFORM.Stream() or PLATFORM.graph(...) is exactly torch.cuda.Stream() / torch.cuda.graph(...) on NVIDIA. The offload runtime's streams, events, H2D copies and host pinning, the CUDA graph manager, the runtime estimator and the NVTX helpers all go through it, and no module outside accelerator/ compares device types any more. The MUSA-specific findings live in MusaPlatform:

  • Graph capture fails under the default capture_error_mode="global", even for a bare x * 2, so MUSA captures in "relaxed" mode. CUDA keeps "global".
  • There is no NVTX, emit_nvtx or cudart profiler, so those are no-ops; nsys profile_start() used to crash off CUDA.
  • torch_musa wraps Tensor.to as orig_to, so fix_graph_device_placement rewrites that too; otherwise an in-graph .to(device=x.device) stays on CPU and a Triton kernel gets a CPU pointer.
  • Inductor's runtime pointwise autotune benchmarks each config with do_bench, whose synchronize trips the MUSA kernel-execution watchdog on the large fused mHC kernel ("the launch timed out and was terminated"). PLATFORM.runtime_pointwise_autotune is False on MUSA and the piecewise compile clears torch._inductor.config.triton.autotune_pointwise; CUDA has no such watchdog and keeps it on.
  • FSDP weight-gather auto-bucketing merges gathers into all_gather_into_tensor_coalesced, which MCCL hangs on while plain all_gather_into_tensor works. PLATFORM.coalesced_all_gather is False on MUSA and gates FsdpAutoBucket; CUDA/NCCL keeps bucketing.

2. CUDA-only features stay off on other accelerators instead of failing mid-run.
EVT epilogue fusion and the SM90 TMA checks gate on PLATFORM.sm, which is (0, 0) off CUDA, so they stay disabled. fsdp_config.transport="copy_engine" needs PLATFORM.has_symm_mem and fails before lowering, pointing to "nccl". sm reads the current device, as torch.cuda.get_device_capability() does, rather than device 0.

3. A device_agnostic pre-commit hook keeps it that way.
Under magi_compiler/ it rejects torch.cuda.*(...) calls and == "cuda" / == "musa" comparisons, except in accelerator/ and in the modules that are CUDA-only by design (symm_mem/, the depyf examples). Type annotations such as torch.cuda.CUDAGraph are left alone; they resolve on a MUSA build too.

Results

H200, the 8 CI shards plus the EVT suite: 706 passed. The two magi_depyf timeline tests that fail with a cold inductor cache fail the same way on main.

S5000, torch_musa 2.9.0:

  • tests/feature_tests/test_cuda_graph.py and test_cpu_offload.py, with modules and tensors moved to "musa": 10 passed, including FULL and PIECEWISE capture, with the PIECEWISE output also checked against eager.
  • A 4-layer bf16 MLP under offload, 1 and 2 ranks × BASE / COST_EFFECTIVE / HEURISTIC × gpu_resident_weight_ratio 0 / 0.5: in all 12 runs the weights stay on CPU and pinned, and the relative error vs eager is 4.24e-3.

Other

  • Graph weight offload from main (graph_weight_offload, [Feat] Offload V2: compile-time graph weight offload, sharing one overlap scheduling core with SimpleFSDP weight gathers #80 / [Dev]: Add rank-shared host weight offload #99) goes through PLATFORM too: its H2D stream, events and synchronizes, the bandwidth probe, the stand-in device, the move probe that decides parking, and the NUMA lookup. utils.numa.cuda_device_numa_node is now device_numa_node (None when the runtime reports no PCI address); magi_compiler.cuda.event_work is now magi_compiler.utils.event_work. magi::h2d_load registers under PLATFORM.dispatch_key ("CUDA" / "PrivateUse1") instead of "CUDA". On 8x S5000 (torch_musa 2.9.1), with the tests' device names swapped for MUSA: offload/test_weight_offload.py 102, test_weight_offload_e2e.py 10 (multi-rank over MCCL, real Inductor compiles), test_h2d_reorder.py 37 passed. Not yet run on H200 after the merge, nor on a large model.
  • Main's lazy pin / PCIe share (Feat/lazy pin pcie share #106) and the link collective op go through PLATFORM as well: host page-locking is PLATFORM.host_register / host_unregister, and utils.device.has_active_nvlink is now PLATFORM.has_active_nvlink (None off CUDA). defer_host_materialization and keep_on_device_bytes both stay; deferral leaves the residents to the compile, so it ignores the device-kept prefix.
  • Breaking for importers: magi_compiler.cuda.cudart.pin_memory_in_place is now magi_compiler.accelerator.pin_memory_in_place, and magi_compiler.utils.device_capability() / device_capability_major() are PLATFORM.sm / PLATFORM.sm[0].
  • pin_memory_in_place skips tensors that are already pinned: registering host memory twice leaves a sticky runtime error that the next kernel launch reports as its own.
  • Caveat for model code: offload traces the first call with CPU stand-ins for its inputs, so a x.device.type == "cuda" / x.is_cuda branch in the traced model takes its CPU path, silently and for good.
  • The MUSA image ships Python 3.10 while pyproject.toml asks for 3.12. The package imports and runs there, but tests/model_definition.py needs typing.Self (3.11+).
  • Re-validating a large model on S5000 is still pending.
cennn and others added 17 commits October 16, 2026 16:35
The offload path hard-coded torch.cuda, "cuda", .is_cuda and libcudart, so it failed on MUSA unless
torchada remapped torch.cuda. Use the current accelerator's device module instead; on CUDA this is
torch.cuda, so behaviour there is unchanged.

- utils/device.py: accelerator_module() / accelerator_type().
- offload executor, schedulers, profiler: streams, events, synchronize and H2D copies go through them.
- _api.py: detect .to(<accelerator>) by device type rather than .is_cuda.
- magi_backend.py: fix_graph_device_placement and the offload fake args target the accelerator.
- cuda/cudart.py: pin_memory_in_place falls back to libmusart musaHostRegister when libcudart is absent.
- utils/nvtx.py: skip NVTX ranges when torch is built without NVTX.

8x S5000 (torch 2.9.0, no torchada), toy 4-layer block, ratio 0/0.5, BASE/COST_EFFECTIVE/HEURISTIC:
weights stay on CPU and pinned, rel err vs eager 4.2e-3 (bf16); 2 ranks: giant buffers pinned,
1.24 ms/call vs 4.23 ms unpinned. H200: test_cpu_offload, test_ep_shared_memory, test_fix_to_cpu_in_graph,
test_shm_memory_peak, cache/test_cache_topology_isolation and api_tests pass (140).
# Conflicts:
#	magi_compiler/magi_backend/magi_backend.py
Dynamo lifts unspecialized Python floats (e.g. a module's eps) into 0-dim CPU tensor inputs and reads
them back with .item() where a Python float is required (custom op float args, Triton launches). The
offload path moved every tensor input to the accelerator: the fake copy loses its constant, so the
piecewise fake run raised DataDependentOutputException, and at runtime the scalar was a device tensor.

Leave 0-dim CPU tensors alone in the offload fake args, fix_graph_device_placement and the executor's
input preparation; device kernels accept CPU scalars as before.

test_cpu_offload_float_attribute fails without the fix (DataDependentOutputException) and passes with it
on H200; the H200 offload/cache/api suites still pass (147). Found on MAGI-2 400B, where every RMSNorm
eps and mHC scale hit this once the Triton paths were traced.
torch_musa replaces Tensor.to with a wrapper that calls self.orig_to, so on MUSA Dynamo records
call_method orig_to. fix_graph_device_placement only matched 'to', so an in-graph
.to(device=x.device) traced with the offload's CPU inputs stayed device_put(..., cpu), and a Triton
kernel then received a CPU pointer at runtime.

MAGI-2 400B W8A8 on 8x S5000, gpu_resident_weight_ratio=0.0: compiles and runs, 5.15 s/step vs
5.08 s/step without offload, peak device memory 21.7 GB/card vs 73.8 GB.
pin_memory_in_place tried libcudart first and used cudaHostRegister whenever it loaded, so a MUSA host
that also ships libcudart called the CUDA runtime and raised. Select musaHostRegister or
cudaHostRegister from accelerator_type() instead.

Also rename the offload executor/scheduler/profiler attributes rt -> device_module and
device -> device_type (it holds the type string, not a torch.device).
# Conflicts:
#	magi_compiler/magi_backend/magi_backend.py
#	magi_compiler/offload/offload_warpper.py
- matmul epilogue fusion's SM90 TMA checks use device_capability()
- fullgraph overlap rejects transport='copy_engine' off CUDA
… utils.device

cuda_graph_mgr, runtime_estimator and evt_runtime called torch.cuda directly. They now go through\naccelerator_module(), plus a new accelerator_graph_cls() for the one name get_device_module() does not\nnormalise (CUDAGraph vs MUSAGraph). On MUSA graphs are captured with capture_error_mode=relaxed: under the\ndefault global mode torch_musa fails every capture. device_capability() defaults to the current device, as\ntorch.cuda.get_device_capability() does. A device_agnostic pre-commit hook keeps torch.cuda calls out of\neverything but the CUDA-only modules.
Device differences were spread over utils/device.py helpers and inline device-type checks in cudart.py,\nnvtx.py, cuda_graph_mgr.py and magi_backend.py, and nsys profiling still called cudart unconditionally.\nmagi_compiler.accelerator now exposes PLATFORM (CudaPlatform / MusaPlatform): device_type, sm, nvtx,\nemit_nvtx, host_register, profiler_start/stop, graph_cls, graph_capture_error_mode and has_symm_mem, with\neverything else forwarded to torch.<device_type>. utils/device.py and cuda/ are gone.\n\npin_memory_in_place now skips pinned tensors: registering host memory twice leaves a sticky runtime error\nthat the next kernel launch reports. The device_agnostic hook also rejects device-type comparisons outside\nmagi_compiler/accelerator.
main replaced _apply_fsdp_fullgraph_overlap with WeightTransferPipeline; the copy-engine check
(PLATFORM.has_symm_mem) moves into its config validation. main's new code still imported the
magi_compiler.cuda package this branch removed: event_work moves to magi_compiler.utils, and
pin_memory_in_place comes from magi_compiler.accelerator.
The graph weight offload that came in from main (Offload V2, #80 / #99) called torch.cuda and
compared device types with "cuda" directly: its H2D stream, events and synchronizes, the bandwidth
probe, the stand-in device, the move probe that decides parking, and the NUMA lookup. They now go
through PLATFORM, so MUSA parks and streams weights the same way. cuda_device_numa_node becomes
device_numa_node and returns None for a runtime that reports no PCI address.
… key

The op had a "CUDA" kernel only, so on MUSA every compiled load failed with
"Could not run 'magi::h2d_load' with arguments from the 'musa' backend".
Platform.dispatch_key is "CUDA" / "PrivateUse1".

On 8x S5000 (torch_musa 2.9.1) with the tests' device names swapped for MUSA:
test_weight_offload.py 102, test_weight_offload_e2e.py 10, test_h2d_reorder.py 37 passed.
…h no host copy

offload_keep_on_device_mib leaves the leading offloadable weights, in parameter order, as plain device
weights: host-first neither reserves pinned memory for them nor loads them. Residents of
offload_max_device_weight_mib keep their host copy, so they cannot shrink a model whose shards
overflow host memory.
Two MagiCompiler defaults deadlock on MUSA while CUDA is unaffected, because
MUSA has a kernel-execution watchdog and its MCCL lacks a working coalesced
all-gather. Gate both behind platform facts instead of a global change:

- Inductor runtime pointwise autotune benchmarks each config with do_bench,
  whose synchronize trips the MUSA watchdog on the large fused mHC kernel. Add
  a runtime_pointwise_autotune platform fact (False on MUSA) and clear
  torch._inductor.config.triton.autotune_pointwise in the piecewise compile.
- FsdpAutoBucket merges weight gathers into all_gather_into_tensor_coalesced,
  which MCCL hangs on (plain all_gather_into_tensor works). Add a
  coalesced_all_gather platform fact (False on MUSA) and gate auto-bucketing.
main's lazy pin / PCIe sharing (#106) landed next to this branch's accelerator split:

- weight_lifecycle: defer_host_materialization (main) and keep_on_device_bytes (#107) are
  orthogonal, so both survive. Deferral leaves the residents to the compile and has no
  device-kept prefix to honor, so only the parking path takes the prefix.
- has_active_nvlink moved from utils/device.py, which this branch deletes, to the platform:
  it is NVML and torch.cuda, and CUDA is the only accelerator that can answer it.
- host_memory_pool and link_collective_op, both new on main, now page-lock, stream and
  record events through PLATFORM; event_work follows its move out of the cuda package.
@cennn cennn added the ci:run Trigger CI integration tests label Nov 18, 2026
@github-actions github-actions Bot removed the ci:run Trigger CI integration tests label Nov 18, 2026
CudaPlatform.host_register raises main's "cudaHostRegister of a N MiB host region failed with error code E"
again, and the two #106 tests that disabled the by-name libcudart lookup drop that patch: magi_compiler.cuda
and its lookup are gone, so the region pins through torch's runtime regardless.
@cennn cennn added the ci:run Trigger CI integration tests label Nov 18, 2026
@github-actions github-actions Bot removed the ci:run Trigger CI integration tests label Nov 18, 2026
Inductor launches a collective and defers its wait to the first use, so a compiled SimpleFSDP layer had an FSDP
weight all_gather (one communicator) in flight while a CP all_to_all (another) was still running. MCCL hangs on
that, and the MUSA kernel watchdog kills the stalled kernel after ~5 minutes: the 400B W8A8 base on 8x S5000
never finished its first compiled forward, while the eager backend and MUSA_LAUNCH_BLOCKING=1 both did.

Platform.concurrent_collectives (False on MUSA) installs a reorder pass that schedules each wait right after its
collective; graphs whose FSDP / offload pipeline already places their transfers keep it. CUDA is unchanged.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant