Skip to content

feat(core): add an opt-in cuda-oxide route behind fused_add_rms_norm - #3451

Merged
inureyes merged 6 commits into
mainfrom
feature/issue-2833-cuda-oxide-rmsnorm-adapter
Nov 26, 2026
Merged

inureyes merged 6 commits into
mainfrom
feature/issue-2833-cuda-oxide-rmsnorm-adapter

Conversation

@inureyes

@inureyes inureyes commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Summary

The precompiled cuda-oxide fused residual-add + RMSNorm module from #2832 now runs inside MLX lazy evaluation as an optional implementation behind fused_add_rms_norm. It is off at build time and at run time, GB10 only. The only change to MLX's CUDA overlay is one defaulted parameter on get_jit_module (see below), so the stop condition was not reached.

  • The kernel is an MLX primitive (kernels/fused_norm_oxide.cpp): get_jit_module loads the PTX, malloc_async allocates outputs, the stream's command encoder registers the buffers and add_kernel_node_raw enqueues, all inside eval_gpu. fast::precompiled_cuda_kernel could not be reused because the entry interleaves (pointer, u64 length) pairs with the scalars.
  • fused_add_rms_norm calls the adapter before select_kernel_port. No artifact, a dtype pair without an entry, more than 2^32-1 elements, more than 2^31-1 rows (CUDA grid limit) or a CPU default device build the existing kernel's node, with the reason recorded. A failure during evaluation throws and is not retried.
  • MLXCEL_CUDA_OXIDE_FUSED_NORM=1 (with MLXCEL_FUSED_ADD_RMSNORM=1) validates the embedded artifact against its manifests and ABI schemas, checks that device 0 is sm_121 and installs it. A refused artifact prints one line and the existing kernel keeps serving. MLXCEL_CUDA_OXIDE_FUSED_NORM_DIR loads another copy through the same validation.
  • The JIT module name carries the payload digest, target, ABI version and compiler revision, and the module bypasses the PTX disk cache entirely, so a planted or stale cache file can never be loaded in its place. Route and launch counters are the test-visible route marker.

Overlay change

overlays/cuda/mlx/backend/cuda/jit_module.{cpp,h} gain enum class DiskCache { Use, Bypass } and a trailing DiskCache disk_cache = DiskCache::Use on JitModule and cu::get_jit_module. Bypass neither reads nor writes the disk cache for the module. Only the adapter passes Bypass, by name; every existing caller keeps its behavior. It is a typed enum rather than a second bool so it cannot be confused with or swapped for upstream's use_disk_cache, which the header now documents as kept only for signature parity. Upstream's use_disk_cache argument has been ignored since #2492, and caching a precompiled PTX saves no compile time, so bypassing was simpler and safer than comparing on hit. Editing the overlay rebuilds MLX once in each build profile. Documented in the file header and src/lib/mlxcelverse/README.md.

Deviations from the brief

  • Build switch is MLXCEL_BUILD_CUDA_OXIDE_FUSED_NORM=1, not a Cargo feature. A feature or a build dependency changes the build script's OUT_DIR and rebuilds MLX from source on every toggle (the reason recorded in build_support/ptx_cache_test_hooks.rs and mlxcel-mlx-pin/Cargo.toml). Measured: 57 s to turn it on after a default build, 12 min 22 s cold. The build-time digest check therefore uses a SHA-256 written out in build_support/, unit-tested in mlxcel-mlx-pin.
  • The primitive lives in kernels/, not in the overlay. MLX installs its CUDA backend headers, so an opted-in bridge build reaches them with two extra include paths. The cost is one file that uses MLX CUDA internals directly, listed in CONTRIBUTING.md for pin bumps (including the CommandEncoder #ifndef NDEBUG layout note).
  • Layout is not decided before enqueue. A lazy input has no layout yet, so non-contiguous inputs are copied inside eval_gpu, as fast::cuda_kernel does for the existing port.

Test plan

GB10, driver 580.178.04, every GPU run under gpu-lock with --test-threads=1. Commands and results are in docs/mlxcelverse/cuda-oxide-mlx-adapter-evidence.md.

  • cuda_oxide in the opted-in lib binary: 31 passed with CUDA graphs on and 31 with MLX_USE_CUDA_GRAPHS=0. Matrix: cases=130 elements=2181390 failed=0 bitwise_identical_to_fused_cuda=130 oxide_routes=130 launches=130 native_routes=0.
  • Lazy chain, 60 graph replays, joins between captured cuBLAS child graphs (graph dump inspected for the edges), allocator reuse, dropped inputs, non-contiguous inputs, four threads on one stream, and three threads on three distinct GPU streams (60 routes, 60 launches, bit-identical to the existing kernel).
  • Wrong manifest and missing artifact against a warm module; a planted disk-cache entry under the module name is never loaded or rewritten; unloadable payload and wrong target surface through try_eval with 0 launches and 0 reroutes; a lazy shape over the grid limit takes the existing kernel.
  • layers::fused_add_rms_norm with the real environment switches: graph path, existing kernel, cuda-oxide (2 routes, 2 launches), also with graphs off and with the directory override.
  • Whole opted-in lib binary in one process: 2517 passed, 0 failed (on ff479507; later commits reran the narrow filters above).
  • Default build: 0 adapter symbols, fused_norm_parity_tests 10 passed, check-clean-build.sh passes.
  • mlxcel-mlx-pin build-gate tests 8 passed; clippy -D warnings on mlxcel-core lib and tests (default and opted-in); cargo fmt --check; the argument-free scripts/ci/check_*.py gates.

Not verified: no checkpoint was loaded, so which dtype pairs real models present is unmeasured; no non-CUDA or Windows build was compiled; workspace-wide clippy and tests were not run; no throughput measurement (#2834).

Known follow-ups, out of scope here: the route decision takes a shared lock per call; last_fallback() is last-writer-wins across threads; the override directory is read without a size bound or regular-file check; the existing port's static_cast<int>(x.size() / dim) in fused_norm.cpp wraps above 2^31-1 rows (predates this PR).

Closes #2833

Issue #2833 asks whether the precompiled cuda-oxide fused residual-add + RMSNorm module from #2832 can run inside MLX lazy evaluation without replacing MLX's CUDA backend. It can: the kernel is now an MLX primitive (kernels/fused_norm_oxide.cpp) that loads the module through get_jit_module, allocates outputs with malloc_async, registers buffers with the stream's command encoder and enqueues with add_kernel_node_raw inside eval_gpu. A dedicated primitive is needed only because the entry interleaves (pointer, u64 length) pairs with the scalars, which CustomKernel cannot pack. No file under overlays/ changes.

The route is off twice. MLXCEL_BUILD_CUDA_OXIDE_FUSED_NORM=1 (Linux CUDA only) compiles the adapter and embeds the committed sm_121 PTX after the build script checks its SHA-256 against the manifests. It is a build environment variable, not a Cargo feature or build dependency, because either would change the build script's OUT_DIR and rebuild MLX from source. At run time MLXCEL_CUDA_OXIDE_FUSED_NORM=1 validates the artifact against its manifests and ABI schemas, checks that device 0 is sm_121 and installs it.

fused_add_rms_norm calls the adapter before select_kernel_port. Unsupported dtype pairs, more than 2^32-1 elements and a CPU default device take the existing kernel when the node is built; a failure during evaluation throws and is never retried. The JIT module name carries the payload digest, target, ABI version and compiler revision. Route and launch counters let tests prove which implementation ran.

Validated on GB10 under gpu-lock with CUDA graph capture on and off; commands, results and gaps are in docs/mlxcelverse/cuda-oxide-mlx-adapter-evidence.md. No checkpoint was run and no throughput is claimed (#2834).

Refs #2833
Follow-up to the cuda-oxide adapter for #2833. The parameter-role types and the argument-list check move from cuda_oxide_artifact.rs into cuda_oxide_abi.rs so both files stay under 500 lines; fused_norm.cpp and fused_norm_oxide.cpp lose comment lines for the same reason. No behavior changes.

The evidence report now records two observations instead of inferring them: the CUDA graph dump of the captured-child-graph test (three matmul child graphs and two fused_add_rms_norm_f32 kernel nodes in one graph, with the dependency edges listed), and a run of the whole opted-in mlxcel-core lib binary in one process (2517 passed, 0 failed). It also stops claiming each test thread had its own stream, which was not inspected. Adds the changelog entry.

Refs #2833
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:linux Linux (CUDA / packaging) specific labels Nov 26, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Run the precompiled cuda-oxide fused residual-add + RMSNorm PTX inside MLX lazy evaluation as a default-off alternative behind fused_add_rms_norm (#2833).

Findings Addressed

No CRITICAL or HIGH findings, so nothing was changed.

Remaining Items

  • Concurrency test uses a single MLX stream (MEDIUM). several_threads_can_drive_the_route_at_once drives four threads through the default stream; the issue asks for concurrent requests/streams. A variant that evaluates on a second GPU stream would close the gap. The evidence doc already says stream use was not inspected.
  • Bridge vs MLX NDEBUG layout (LOW). CommandEncoder has an #ifndef NDEBUG member (registered_data_ptrs_), and the bridge only gets -DNDEBUG when the build script itself is compiled without debug assertions. The adapter only touches inline members declared before that field (device_, temporaries_), so it is safe today; worth a line in the pin-bump note.
  • Grid limit (LOW). rows may reach 2^32-1 when dim is tiny, which is over CUDA's grid.x limit. It surfaces as a launch error, not a silent fallback, and the existing port has the same int limit.
  • The unloadable-payload test leaves one entry in the PTX disk cache (LOW, documented in the evidence doc).

Deviations

Both hold. A Cargo feature changes the build-script metadata hash and therefore OUT_DIR, the same reason recorded in ptx_cache_test_hooks.rs. The installed jit_module.h is byte-identical to the overlay copy, and the overlay is untouched.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow (layers::fused_add_rms_norm -> ensure_from_env; llama3, gemma, arcee, iquestloopcoder call it)
  • Project conventions followed
  • Existing modules reused where applicable (get_jit_module, the encoder, malloc_async, copy_gpu, fused_norm_threads)
  • No unintended structural changes
  • Tests pass

Re-run on GB10 under gpu-lock: cuda_oxide 28/28 with graphs on and with MLX_USE_CUDA_GRAPHS=0. Matrix: cases=130 failed=0 bitwise_identical_to_fused_cuda=130 oxide_routes=130 launches=130 native_routes=0. The layer route test with both switches gives oxide_routes=2 launches=2 existing_kernel_routes=0. The default build's fused_norm_parity_tests pass. All six scripts/ci gates and cargo fmt --check pass. Arg packing matches the 13-param ABI through the KernelArgs variant (CUdeviceptr, uint32_t, float). The module name carries ABI, target, revision and digest. The disk cache stays active even with use_disk_cache=false (overlay #2492), so the warm-cache test is meaningful.

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL or HIGH findings, so nothing was changed or pushed.

Checked and clean:

  • Override directory: the PTX is read once, hashed in memory, and installed from the same buffer, so there is no digest-to-load TOCTOU. Manifest and schema parsing is serde into typed fields; argument_roles uses roles.get(i) and never indexes or does arithmetic on manifest values. The docs already say the manifests give integrity, not authenticity.
  • Build-time SHA-256: FIPS vectors (including 1M a) pass, the committed PTX hashes to b54c1c93... with sha256sum, matching all five manifests, and the runtime re-hashes with sha2.
  • Kernel bounds: shapes are validated in fused_add_rms_norm before the branch, the u64 lengths are the real a.size() of each (contiguous-copied) buffer, and KernelArgs storage is a std::deque, so argument pointers stay valid.
  • Default builds: everything is behind cfg(mlxcel_cuda_oxide_fused_norm) / MLXCEL_CUDA_OXIDE_FUSED_NORM, so the default hot path is unchanged. Per-eval cost on the opted-in path matches CustomKernel (shared lock plus a string lookup in get_jit_module, then the get_kernel mutex).

LOW, left for follow-up:

  • fused_norm_oxide.cpp:196: a disk-cache hit loads the cached PTX without comparing it to the validated payload, so a planted entry is stopped only by the fix(cuda): harden the JIT PTX disk cache's trust and keying #2539 owner and mode checks. Caching a precompiled PTX saves no compile time, so a cleaner option is to skip the disk cache for this module or compare on hit.
  • fused_norm_oxide.cpp:354: the element limit allows rows up to 2^32-1 at small dim, which is above CUDA's grid-x limit of 2^31-1. That fails at launch rather than falling back before enqueue. Adding rows <= INT32_MAX to the kElementLimit check closes it.
  • cuda_oxide_artifact.rs:213: read_dir has no size limit and follows FIFOs. It runs inside the OnceLock, so a bad override path can stall the first fused join. The operator controls this path.
  • try_oxide_fused_add_rms_norm takes a shared_mutex on every routed call. std::atomic<std::shared_ptr> would remove that; the cost is small.
  • g_last_fallback is process-wide and keeps only the last writer, so under concurrent routing it only means something in serialized tests.
  • an_evaluation_time_failure_is_an_error_not_a_retry leaves a junk .ptx entry, under a test-only name, in the real per-user cache.

Distinct streams: add distinct_gpu_streams_can_drive_the_route_at_once, which drives the oxide route from three threads on three streams made with new_stream_on_gpu, asserts the stream indices differ, compares every output with the existing fused kernel and checks 60 routes, 60 launches and 0 existing-kernel routes.

Grid limit: the route decision now refuses more than 2^31-1 rows (one block per row, CUDA's grid.x cap) before enqueue and records the new Fallback::GridLimit; a lazy-shape test covers both sides of the limit.

Disk cache: the oxide module no longer reads or writes MLX's PTX disk cache, so a cached entry can never stand in for the validated payload. This needs a trailing read_disk_cache parameter (default true, so no other caller changes) on JitModule and get_jit_module in the CUDA jit_module overlay, which makes the overlay-untouched claim in the docs false and is documented as such. A test plants a different payload under the module name and checks it is neither loaded nor rewritten. The same change stops an_evaluation_time_failure_is_an_error_not_a_retry from leaving a junk entry in the per-user cache, and the test now asserts that.

Docs: CONTRIBUTING.md notes that CommandEncoder has an NDEBUG-conditional member, so the bridge's NDEBUG must agree with MLX's for fused_norm_oxide.cpp. The evidence report records the new results and lists the deferred follow-ups.

Validation on GB10 (opted-in build, gpu-lock, --test-threads=1): cuda_oxide filter 31 passed with CUDA graphs on and with MLX_USE_CUDA_GRAPHS=0, the 130-case matrix line unchanged, fused_norm_parity_tests 10 passed, layer-route test passed with both switches. cargo fmt --check and clippy -D warnings on mlxcel-core --lib --tests --features cuda pass for the default and opted-in builds.

Refs #2833
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 26, 2026
The overlay's `get_jit_module` carried two trailing bools: upstream's `use_disk_cache`, which this overlay has ignored since #2492, and the new `read_disk_cache`, which also turned off writes despite its name. The cuda-oxide adapter called it as `(..., false, false)`, which did not say which flag did what and let the two be swapped silently.

The second parameter is now `cu::DiskCache disk_cache = DiskCache::Use` with `enum class DiskCache { Use, Bypass }`. `Bypass` neither reads nor writes the PTX disk cache for the module, the adapter passes it by name, and a bool can no longer be passed in its place. The header documents that upstream's flag is kept only for signature parity. Every existing caller still gets the default, so their behavior is unchanged.

Comments, the mlxcelverse README and the adapter evidence report are updated to the new name.

GB10, opted-in test-fast build, under gpu-lock with --test-threads=1: cuda_oxide 31 passed with CUDA graphs on and 31 with MLX_USE_CUDA_GRAPHS=0 (matrix 130/130 on the oxide route, bit-identical to the fused CUDA kernel), fused_norm_parity_tests 10 passed, layer-route test with both switches 1 passed (2 oxide routes, 2 launches). No mlxcel_oxide entry in the PTX disk cache afterwards.

Refs #2833
…da-oxide-rmsnorm-adapter

# Conflicts:
#	CHANGELOG.md
The Windows build job checks out with core.autocrlf on, which rewrote the committed PTX with CRLF so its SHA-256 no longer matched the manifests and three mlxcel-mlx-pin build_support tests failed. Mark the spike artifacts and ABI schemas -text so git never converts them.

Refs #2833
@inureyes
inureyes merged commit 2f39471 into main Nov 26, 2026
32 of 33 checks passed
@inureyes
inureyes deleted the feature/issue-2833-cuda-oxide-rmsnorm-adapter branch November 26, 2026 17:22
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:linux Linux (CUDA / packaging) specific priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Integrate an optional cuda-oxide RMSNorm path with MLX execution

1 participant