Skip to content

feat(compiler): in-process library-mode compiler (Rust kernel to PTX) - #312

Closed
alejandro-soto-franco wants to merge 1 commit into
NVIDIA:mainfrom
alejandro-soto-franco:feat/library-mode-compiler
Closed

alejandro-soto-franco wants to merge 1 commit into
NVIDIA:mainfrom
alejandro-soto-franco:feat/library-mode-compiler

Conversation

@alejandro-soto-franco

Copy link
Copy Markdown
Contributor

Summary

Compile a device-kernel crate to PTX in-process, with no cargo or rustc
subprocess. This is the library-mode deliverable in #96. The existing backend
(rustc-codegen-cuda) is unchanged.

Added

  • crates/cuda-oxide-compiler: core (compile_core.rs) driving
    rustc_driver::run_compiler with a Callbacks::after_analysis that runs the
    existing collect_device_functions, generate_device_code, and
    run_pipeline, then returns Compilation::Stop. Backend modules are reused
    via #[path] include, not forked. Plus a CLI bin. API:
    compile_to_ptx(&CompileRequest) -> Result<Vec<u8>, _>.
  • crates/cuda-oxide-compiler-cdylib: the same core behind an extern "C" API.
    Both targets #[path]-include the one compile_core.rs.
  • crates/libmode-consumer: a normal Rust binary (no rustc_private) that
    dlopens the cdylib via libloading and compiles in-process.
  • Golden sm_80 PTX parity test for vecadd.

Design

A rustc_driver host cannot link as an rlib or Rust dylib (the std and
object graphs double). The in-process form is a cdylib with a C ABI, loaded
via libloading, the same way rustc loads this project's backend. Codegen stops
after analysis, so the target is device-only crates.

Error handling

A kernel compile error is recoverable: rustc raises a FatalError unwind, caught
by catch_fatal_errors, so compile_to_ptx returns Err and the C ABI returns
a nonzero code. The host process is not terminated. The C ABI body is also
wrapped in catch_unwind (code 6) so no panic crosses the boundary. Return
codes: 1 null, 2 utf8, 3 missing source, 4 dep resolve, 5 compile error, 6 panic.

Performance

Measured on vecadd at sm_80, RTX 5060 Laptop, CUDA 13.1.

Path Per-kernel
cargo oxide build (subprocess) ~445 ms
in-process via cdylib (steady-state) ~158 ms (~2.8x faster)
one-time dlopen load ~5.6 ms

The in-process PTX is byte-identical to cargo oxide build (2079 bytes), locked
by the golden test. The ~158 ms still includes the llc and opt subprocesses
inside run_pipeline, so ~2.8x is conservative: the saving comes from removing
the per-kernel cargo startup, rustc spawn, and backend dlopen.

Runtime and test requirements

  • GLIBC_TUNABLES=glibc.rtld.optional_static_tls=2097152 (or LD_PRELOAD
    librustc_driver): librustc_driver uses initial-exec TLS and is dlopened
    after process start.
  • LD_LIBRARY_PATH="$(rustc --print sysroot)/lib".
  • Tests need RUST_MIN_STACK=16777216.

Limitations and follow-ups

  • Compiles must be serialised (compile_to_ptx mutates CUDA_OXIDE_TARGET and
    CARGO_PKG_*). Per-call state is a follow-up.
  • sysroot() and workspace_root() panic on misconfiguration; should return
    Result.
  • llc and opt remain subprocesses.
  • One op and dtype golden-tested (vecadd); the API is general.
  • This is the delivery mechanism. The CubeCL-IR to #[kernel] bridge is separate.

Testing

  • cargo build of the three crates: clean, no warnings.
  • Stock cargo test is unaffected: the tests that need the rustc_private
    runtime and prebuilt release rlibs are #[ignore]d.
  • Run them explicitly: cargo build --release -p cuda-core -p cuda-host -p cuda-device, then RUST_MIN_STACK=16777216 LD_LIBRARY_PATH="$(rustc --print sysroot)/lib" cargo test -p cuda-oxide-compiler -- --ignored (golden parity
    and the broken-kernel recovery test included).
  • cargo clippy on the three crates: clean, no #[allow].
  • rustc-codegen-cuda and mir-importer unchanged.

DCO

All commits signed off.

Add cuda-oxide-compiler: compile a device-kernel crate to PTX in-process via
rustc_driver, with no cargo or rustc subprocess, addressing the library-mode
deliverable in NVIDIA#96.

- crates/cuda-oxide-compiler: a parameterised core (compile_core.rs) driving
  rustc_driver::run_compiler + Callbacks::after_analysis, reusing the existing
  collector/device_codegen/run_pipeline via a path-include (backend
  unchanged), plus a thin CLI bin.
- crates/cuda-oxide-compiler-cdylib: the same core behind an extern "C" API.
- crates/libmode-consumer: a normal Rust binary (no rustc_private) that dlopens
  the cdylib via libloading and compiles in-process, modelling a runtime-JIT host.
- Golden sm_80 PTX parity test for vecadd.

PTX is byte-identical to cargo oxide build; in-process steady-state compile is
about 2.8 times faster than the cargo path. Device-only crates (codegen stops
after analysis). Runtime requires GLIBC_TUNABLES=glibc.rtld.optional_static_tls
and LD_LIBRARY_PATH to the rustc sysroot; llc and opt remain subprocesses.

Hardening:

- Broken kernels are recoverable, not fatal to the host. A kernel that fails
  rustc's front-end (e.g. a type error in a #[kernel] fn) makes rustc abort by
  unwinding with a sentinel FatalError; compile_to_ptx now wraps run_compiler in
  catch_fatal_errors (the hook rustc itself uses) so this returns a clean Err
  instead of a panic. A new (ignored) test compiles a deliberately broken kernel
  and asserts the Err.
- The cdylib C ABI wraps its body in std::panic::catch_unwind, returning the
  distinct code 6 on a caught panic rather than unwinding across the FFI boundary
  (which aborts the host). A new (ignored) test asserts the C ABI returns a
  nonzero code, not an abort, for a broken kernel.
- The in-process tests require the rustc_private runtime and prebuilt release
  rlibs, so they are marked #[ignore] and skipped by a plain cargo test; the
  README and module docs give the explicit --ignored run recipe.
- compile_to_ptx removes its per-call output dir after reading the PTX back.
- The three new manifests inherit edition/authors/license/repository from the
  workspace.

Signed-off-by: Alejandro Soto Franco <[email protected]>
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks for the PR.

Just a quick note: For compiler-embedding changes of this size, I'd recommend starting with a Discord/design discussion next time. It helps hash out the intended users, distribution model, and API boundary before committing to a significant change.

After reviewing this PR, I understand it aims to:

  • Compile generated Rust kernel source at runtime.
  • Avoid launching Cargo for each compilation.
  • Expose that functionality through a C ABI for frameworks such as CubeCL/Burn.

The main concern is that CubeCL already has its own compiler IR. Converting that IR back into Rust source adds an unnecessary compiler frontend:

PR #312:

CubeCL IR
    ↓
generated Rust source
    ↓
embedded rustc
    ↓
Rust MIR
    ↓
cuda-oxide backend
    ↓
PTX

I think the direct approach proposed by #314 is a better fit:

CubeCL IR
    ↓
dialect-mir
    ↓
cuda-oxide backend
    ↓
PTX

#314 's compiler boundary better matches CubeCL. CubeCL should not need to generate Rust source and host a full Rust compiler just to reach a backend IR.

#312 would make sense only for a separate use case where the input really is arbitrary Rust source and the caller needs Rust language semantics at runtime.

The distribution requirements are also much larger than the shared library suggests:

cuda-oxide compiler library
    ├── exact nightly rustc_driver
    ├── matching libLLVM
    ├── Rust sysroot and rustc-dev
    ├── opt and llc
    └── prebuilt cuda-oxide dependency rlibs

The PR does not invoke Cargo for each kernel, but it still requires an exact Rust compiler environment. It also searches for cuda-oxide rlibs using a build-time checkout path, so the resulting C library is not currently relocatable.

There is also a process-safety problem. The library changes global environment variables during a safe compile call:

compile request changes CUDA_OXIDE_TARGET
                ↓
unrelated application threads can observe it

Serializing compiler calls does not protect other Burn/CubeCL threads or libraries that read the process environment.

Other API problems remain:

  • The documented Rust library API does not exist; the crate is currently binary-only.
  • The C ABI cannot describe general Cargo features, build scripts, or arbitrary dependencies.
  • crate_name is used as a filesystem path component without sufficient validation.
  • The meaningful end-to-end compiler tests are ignored by default.

I think for the stated CubeCL/Burn motivation, we should not pursue this source-compilation approach. The cleaner direction is to extract a rustc-independent cuda-oxide backend and let CubeCL provide IR directly, following the general direction of #314.

If arbitrary Rust-source JIT compilation is still desired as a separate feature, it needs its own design discussion. I would expect that design to include:

  1. A clearly versioned and distributable compiler toolchain.
  2. Relocatable dependency discovery.
  3. No process-global environment mutation.
  4. A complete compile-request and diagnostic API.
  5. Strong isolation, potentially through a persistent compiler worker process.

Though this would likely be a decision that would need much deliberation prior

@nihalpasham nihalpasham added enhancement New feature or request safety Memory safety, soundness, or undefined behavior codegen Device code-generation pipeline (Rust MIR to IR to PTX) build-related Build scripts, toolchain discovery, or compilation setup interop Interop with external compilers / frontends on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves out-of-scope Outside the project's current scope or direction labels Jul 2, 2026
@alejandro-soto-franco

Copy link
Copy Markdown
Contributor Author

Agreed on the compiler boundary. The direct dialect-mir route in #314 is the one my downstream work uses: cubecl-cuda-oxide lowers CubeCL KernelDefinitions straight to dialect-mir and compiles through #314's compile_module_to_ptx, running Burn elementwise add end to end on sm_120, bit-exact against the stock nvrtc backend, with warm JIT latency at parity. CubeCL never needs Rust source or a hosted rustc on that path.

Your findings on this PR are accurate. The README documents a Rust API the bin-only crate does not export; the cdylib resolves dep rlibs through a path baked in at build time and the C ABI has no way to override it; the env mutation is process-global; crate_name reaches file paths unvalidated. Arbitrary Rust-source JIT should wait for a concrete user and its own design thread, and would need the work you list, likely with a persistent worker process as the isolation story.

Withdrawing this PR in favour of #314. The design context for the CubeCL direction is in #313 and the #96 thread; for the next change of this size I'll open the discussion before the code, on Discord or wherever the project prefers.

One #314 question worth settling early: whether compile_module_to_ptx should move toward a rustc-independent home, since mir-importer currently requires consumers to link against the project nightly with rustc_private. That seems aligned with the extracted-backend direction you describe.

@alejandro-soto-franco
alejandro-soto-franco deleted the feat/library-mode-compiler branch September 9, 2026 17:08
meefs pushed a commit to meefs/cuda-oxide that referenced this pull request Sep 30, 2026
Bumps the all-actions group with 2 updates: [taiki-e/install-action](https://github.com/taiki-e/install-action) and [github/codeql-action](https://github.com/github/codeql-action).


Updates `taiki-e/install-action` from 2.87.16 to 2.87.17
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](taiki-e/install-action@9114bf4...94c31af)

Updates `github/codeql-action` from 4.38.0 to 4.38.1
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](github/codeql-action@v4.38.0...v4.38.1)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-version: 2.87.17
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: all-actions
- dependency-name: github/codeql-action
  dependency-version: 4.38.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: all-actions
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
meefs pushed a commit to meefs/cuda-oxide that referenced this pull request Sep 30, 2026
…ping it (NVIDIA#313)

NVIDIA#312 moved taiki-e/install-action to v2.87.17 (94c31af), which is not on
the organization's Actions allowlist, so `pr` and `cargo-deny` fail at
startup on main since df048dc. Pin back to v2.87.16 (9114bf4), the commit
the allowlist admits, in both workflows.

Dependabot ignores install-action and rust-cache from now on: both are
allowlisted by exact commit, so any bump it proposes is unmergeable until
the list changes; they are bumped by hand together with the allowlist.

Signed-off-by: Melih Elibol <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

build-related Build scripts, toolchain discovery, or compilation setup codegen Device code-generation pipeline (Rust MIR to IR to PTX) enhancement New feature or request interop Interop with external compilers / frontends on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves out-of-scope Outside the project's current scope or direction safety Memory safety, soundness, or undefined behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants