Repository navigation
Conversation
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.
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.
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 was referenced Nov 18, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
🗂️ PR Category
📝 Description
The offload runtime, the CUDA graph manager, the runtime estimator, NVTX profiling and EVT fusion called
torch.cudadirectly, 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
Platformobject per accelerator holds every device difference.magi_compiler.accelerator.PLATFORMis aCudaPlatformor aMusaPlatform(MUSA whentorch_musais 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 totorch.<device_type>, soPLATFORM.Stream()orPLATFORM.graph(...)is exactlytorch.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 outsideaccelerator/compares device types any more. The MUSA-specific findings live inMusaPlatform:capture_error_mode="global", even for a barex * 2, so MUSA captures in"relaxed"mode. CUDA keeps"global".emit_nvtxor cudart profiler, so those are no-ops; nsysprofile_start()used to crash off CUDA.Tensor.toasorig_to, sofix_graph_device_placementrewrites that too; otherwise an in-graph.to(device=x.device)stays on CPU and a Triton kernel gets a CPU pointer.do_bench, whosesynchronizetrips the MUSA kernel-execution watchdog on the large fused mHC kernel ("the launch timed out and was terminated").PLATFORM.runtime_pointwise_autotuneis False on MUSA and the piecewise compile clearstorch._inductor.config.triton.autotune_pointwise; CUDA has no such watchdog and keeps it on.all_gather_into_tensor_coalesced, which MCCL hangs on while plainall_gather_into_tensorworks.PLATFORM.coalesced_all_gatheris False on MUSA and gatesFsdpAutoBucket; 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"needsPLATFORM.has_symm_memand fails before lowering, pointing to"nccl".smreads the current device, astorch.cuda.get_device_capability()does, rather than device 0.3. A
device_agnosticpre-commit hook keeps it that way.Under
magi_compiler/it rejectstorch.cuda.*(...)calls and== "cuda"/== "musa"comparisons, except inaccelerator/and in the modules that are CUDA-only by design (symm_mem/, the depyf examples). Type annotations such astorch.cuda.CUDAGraphare left alone; they resolve on a MUSA build too.Results
H200, the 8 CI shards plus the EVT suite: 706 passed. The two
magi_depyftimeline 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.pyandtest_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.BASE/COST_EFFECTIVE/HEURISTIC×gpu_resident_weight_ratio0 / 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, [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 throughPLATFORMtoo: 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_nodeis nowdevice_numa_node(None when the runtime reports no PCI address);magi_compiler.cuda.event_workis nowmagi_compiler.utils.event_work.magi::h2d_loadregisters underPLATFORM.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.py102,test_weight_offload_e2e.py10 (multi-rank over MCCL, real Inductor compiles),test_h2d_reorder.py37 passed. Not yet run on H200 after the merge, nor on a large model.PLATFORMas well: host page-locking isPLATFORM.host_register/host_unregister, andutils.device.has_active_nvlinkis nowPLATFORM.has_active_nvlink(None off CUDA).defer_host_materializationandkeep_on_device_bytesboth stay; deferral leaves the residents to the compile, so it ignores the device-kept prefix.magi_compiler.cuda.cudart.pin_memory_in_placeis nowmagi_compiler.accelerator.pin_memory_in_place, andmagi_compiler.utils.device_capability()/device_capability_major()arePLATFORM.sm/PLATFORM.sm[0].pin_memory_in_placeskips tensors that are already pinned: registering host memory twice leaves a sticky runtime error that the next kernel launch reports as its own.x.device.type == "cuda"/x.is_cudabranch in the traced model takes its CPU path, silently and for good.pyproject.tomlasks for 3.12. The package imports and runs there, buttests/model_definition.pyneedstyping.Self(3.11+).