torchada
English | 中文
Run your CUDA code on Moore Threads GPUs — zero code changes required
torchada is an adapter that makes torch_musa (Moore Threads GPU support for PyTorch) compatible with standard PyTorch CUDA APIs. Import it once, and your existing torch.cuda.* code works on MUSA hardware.
Why torchada?
Many PyTorch projects are written for NVIDIA GPUs using torch.cuda.* APIs. To run these on Moore Threads GPUs, you would normally need to change every cuda reference to musa. torchada eliminates this by automatically translating CUDA API calls to MUSA equivalents at runtime.
On torch_musa releases before 2.11.0.post2, the log / log_ overrides use the input tensor's device and its current stream, even when another GPU is current; the caller's current device is restored after dispatch. From 2.11.0.post2 on, the vendor kernels provide those operators and torchada installs no override.
Prerequisites
- torch_musa: You must have torch_musa installed (this provides MUSA support for PyTorch)
- Moore Threads GPU: A Moore Threads GPU with proper driver installed
The reference stack is the MUSA 5.2.0 stack the vLLM-MUSA v0.32.0-dev line pins:
| Component |
Version |
| PyTorch and torch_musa |
2.13.0.post1+musa5.2.0 |
| Python |
3.12 — the torch 2.13 MUSA wheels are cp312 only |
| MUSA SDK |
5.2.0 |
| GPU |
MTT S5000 (mp_31) |
Older torch_musa 2.9 and 2.11 releases are covered by the version gates below;
each shim installs only on the releases that still need it.
Installation
pip install torchada
# Or install from source
git clone https://github.com/MooreThreads/torchada.git
cd torchada
pip install -e .
Quick Start
import torchada # ← Add this one line at the top
import torch
# Your existing CUDA code works unchanged:
x = torch.randn(10, 10).cuda()
print(torch.cuda.device_count())
torch.cuda.synchronize()
That's it! Supported torch.cuda.* APIs are automatically redirected to torch.musa.*.
What Works
| Feature |
Example |
| Device operations |
tensor.cuda(), model.cuda(), torch.device("cuda") |
| Tensor factories |
torch.zeros(..., device="cuda"), torch.asarray(..., device="cuda"), the *_like family |
| Memory management |
torch.cuda.memory_allocated(), empty_cache(), torch.cuda.memory.*, CUDA memory-pool APIs |
| Synchronization |
torch.cuda.synchronize(), Stream, Event, torch.cuda.streams |
| Mixed precision |
torch.cuda.amp.autocast(), GradScaler() |
| CUDA Graphs |
torch.cuda.CUDAGraph, torch.cuda.graph(), executable rotation for deep models |
| CUDA Runtime |
torch.cuda.cudart() → uses MUSA runtime, torch._C._cuda_getCurrentRawStream and inductor _C shims, torch.cuda.current_blas_handle(), pooled-workspace clearing |
| Profiler |
ProfilerActivity.CUDA → uses PrivateUse1 |
| Custom Ops |
Library.impl(..., "CUDA") → PrivateUse1; torch.library.infer_schema / custom_op accept torch.device annotations |
| Distributed |
dist.init_process_group(backend='nccl') → uses MCCL |
| torch.compile |
Inductor, AOT-cacheable factory wrappers, FX device builtin, torch.cuda._get_device_index |
| C++ Extensions |
CUDAExtension, BuildExtension, in-place source porting, stable-ABI shims |
| FlexAttention |
torch.nn.attention.flex_attention works on MUSA |
| C++ nvJPEG porting |
nvJPEG source and build settings → MTJPEG |
| ctypes Libraries |
ctypes.CDLL with CUDA function names → MUSA equivalents |
| Unified Accelerator API |
torch.accelerator.empty_cache(), memory_stats(), get_memory_info(), Stream, Event, ... |
| FlashAttention providers |
flash_attn_interface redirection, plus only_qv and _flash_attn_forward shims |
| Rotary embedding |
torchada.apply_rope_inplace() joint in-place RoPE, patched into SGLang-Omni's fused-RoPE provider |
| Triton CUDA Extra |
tl.extra.cuda → tl.extra.musa compatibility on MUSA |
| Triton Fused MoE |
Triton 3.2.0 MTT S5000 tuning configs for vLLM and SGLang |
| MUSA operator fixes |
Asynchronous isfinite (always); float64 log_ and mm/bmm out_dtype= where the vendor release still needs them — see torch_musa compatibility |
torch_musa Compatibility
Some patches exist only because a particular torch_musa release was missing a kernel
or had a broken one. Each of those is version-gated: it installs itself only on the
releases that need it and steps aside on the release that fixes the problem, so
nothing has to be configured when the underlying stack moves.
On the reference stack every release-gated shim is skipped: the four legacy
< 2.11.0.post2 overrides, the out_dtype wrapper, and the stable-ABI backport that
torch 2.11 and newer make unnecessary. The installed releases carry the kernel fixes
(2.11.0.post2 and 2.13.0), and the box header's always-on declarations still apply
to every stable translation unit. The rows marked Yes still apply, the
torch.cuda.streams one only when torch_musa.core.stream is importable. The legacy
shims stay in the wheel for stacks pinned to an older torch_musa.
| Shim |
Installed when |
On 2.13 |
What it does |
float64 in-place Tensor.log_ |
torch_musa < 2.11.0.post2 |
No |
Reuses the supported out-of-place log and writes the result back, preserving the in-place contract |
Compiled multinomial / log / log_ |
torch_musa < 2.11.0.post2 |
No |
MUSA PrivateUse1 operator overrides in torchada's JIT-built C++ extension, replay-safe under CUDA graph capture |
| Inductor MUSA template heuristics |
torch_musa < 2.11.0.post2 |
No |
Fills the musa keys of Inductor's template-heuristic registry from the CUDA entries |
torch.accelerator memory APIs |
torch_musa < 2.11.0.post2 |
No |
Routes empty_cache() / memory_stats() / ... to torch.musa, because the pre-release dispatch was broken |
torch.mm / torch.bmm out_dtype= |
torch_musa < 2.13.0 |
No |
Reuses the plain overloads and accumulates in fp32; a runtime probe decides per process whether the native overload is healthy |
Asynchronous torch.isfinite |
Always, on MUSA float tensors |
Yes |
Evaluates abs() < inf on float16/bfloat16/float32/float64 tensors, because ATen's composite runs a boolean mul that blocks the host until the device queue drains. Other dtypes keep the original operator |
| libtorch stable-ABI headers |
torch < 2.11 on MUSA |
No |
Backports the torch::stable accessors that torch_musa's 2.9 snapshot omits, so vLLM and SGLang stable kernels build |
torch.cuda.streams module path |
MUSA, whenever torch_musa.core.stream is importable |
Yes, if importable |
Exposes it as torch.cuda.streams, which the PyTorch 2.11 Dynamo guards resolve |
The out_dtype wrapper is installed below torch_musa 2.13.0 and nothing is
installed from 2.13.0 on, so a 2.13.0.post1+musa5.2.0 call reaches the native
overloads without torchada's runtime probe. The native path was measured on MTT
S5000 during the vLLM-MUSA v0.32.0-dev upgrade: torch.mm and torch.bmm with
out_dtype=torch.float32 on bf16 and fp16 inputs return non-zero results with a
maximum relative error of about 1e-7 against the fp32 product. That measurement
covers those builds and cases. The shim stays for pre-2.13 stacks, where the overload
was measured broken on 2.11.0.post1+musa5.2.0 (mm wrote zeros, bmm wrote wrong
values).
On those older stacks the gate only decides whether a Python wrapper sits in front of
torch.mm/torch.bmm; correctness is decided per process by the runtime probe, which
forwards to a healthy overload and emulates a broken one - so a fix backported into
2.12.x is picked up automatically. An unknown or unparsable __version__ ranks
lowest and therefore stays armed.
Not covered: builds whose binding has no *_Dtype overload keep raising on out_dtype=. That is
the binding's contract, not a defect torchada repairs, so CUDA parity for that case is out of scope.
Examples
Mixed Precision Training
import torchada
import torch
model = MyModel().cuda()
scaler = torch.cuda.amp.GradScaler()
with torch.cuda.amp.autocast():
output = model(data.cuda())
loss = criterion(output, target.cuda())
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
Distributed Training
import torchada
import torch.distributed as dist
# 'nccl' is automatically mapped to 'mccl' on MUSA
dist.init_process_group(backend='nccl')
CUDA Graphs
import torchada
import torch
g = torch.cuda.CUDAGraph()
with torch.cuda.graph(cuda_graph=g): # cuda_graph= keyword works on MUSA
y = model(x)
To dump MUSA graph dot files for debugging, set
TORCHADA_CUDA_GRAPH_DEBUG_DUMP_PATH before running your program. torchada will
call enable_debug_mode() before each graph capture and debug_dump(path) after
the capture completes:
TORCHADA_CUDA_GRAPH_DEBUG_DUMP_PATH=./graph_dumps \
python serve.py
The value is a dump directory. torchada creates it if needed and writes
timestamped files such as graph_1783512345678900000.dot inside it, so
repeated captures do not overwrite one another.
Deep models get a second transparent fix. The MUSA driver caps the number of live
graph executables per process (~2048), and piecewise CUDA graphs instantiate
capture_sizes * num_layers of them, so models deeper than roughly 40 layers used to
exceed the cap and could not use piecewise graphs at all. torchada keeps every
captured template alive, LRU-caps the live executables (1900 by default), and
re-instantiates an evicted graph's executable from its template on the next replay,
which costs about 0.3 ms and needs no forward re-run. It is zero-cost until the cap
is exceeded, and can be tuned or disabled through the
environment variables below.
torch.compile
import torchada
import torch
compiled_model = torch.compile(model.cuda(), backend='inductor')
Tensor factory calls such as torch.zeros(..., device="cuda"),
torch.asarray(..., device="cuda"), and the *_like family also translate
explicit CUDA devices to MUSA. The factory wrappers remain compatible with
CUDA Graph capture and torch.compile AOT caching. The patched
torch.device(...) also remains usable from TorchScript.
Device metadata saved after importing torchada can also be restored with
torch.load(..., weights_only=True): torchada registers its device constructor
with PyTorch's safe-global allowlist when that API is available. Unrelated custom
checkpoint classes still require their own explicit allowlisting.
Three more patches keep compiled code working end to end:
torch.cuda._get_device_index is mapped to its MUSA counterpart, which is what
TorchDynamo calls to model torch.cuda.device(...). Without it, compiling a
function that opens a device context raises AttributeError: module 'torch_musa' has no attribute '_get_device_index'.
- The patched
torch.device is registered as the FX device builtin, so a
GraphModule holding a device constant still binds the name device and runs with
the eager and aot_eager backends. (Inductor executes its own generated code, so
it is unaffected either way.)
MUSA_VISIBLE_DEVICES is authoritative and mirrored to CUDA_VISIBLE_DEVICES; when
only the CUDA variable is set, it is copied to the MUSA variable. Inductor's autotune
subprocess reads the MUSA variable.
On torch_musa releases before 2.11.0.post2, missing musa entries in Inductor's
matmul template-heuristic registry are filled in from the CUDA entries; newer releases
register their own and torchada leaves them alone.
Triton Fused MoE Tuning
torchada bundles Triton 3.2.0 fused-MoE configurations tuned on MTT S5000 for
vLLM and SGLang. The bundled set includes BF16, FP8 W8A8, and shared-expert
shapes, plus a consistent up/down-projection layout for JoyAI-LLM-Flash. Tuning
results are environment-specific; use custom configurations for other Triton,
hardware, or workload combinations.
On import, torchada points SGLang and vLLM to the bundled configurations through
SGLANG_MOE_CONFIG_DIR and VLLM_TUNED_CONFIG_FOLDER. Existing environment
values are never overwritten, so set either variable before importing torchada
to use custom configurations.