Skip to content

fix(collector): don't root items nested inside kernel bodies as kernels - #358

Merged
nihalpasham merged 2 commits into
NVIDIA:mainfrom
haixuanTao:fix/nested-fn-kernel-roots
Jul 22, 2026
Merged

nihalpasham merged 2 commits into
NVIDIA:mainfrom
haixuanTao:fix/nested-fn-kernel-roots

Conversation

@haixuanTao

@haixuanTao haixuanTao commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

is_kernel_function matches the kernel marker by substring, so a named fn defined inside a #[kernel] body also matches — its def path carries the kernel's name as a path prefix (...::cuda_oxide_kernel_<hash>_k::helper). The collector's root scan then treats the nested fn as a kernel entry point: a generic monomorphization gets exported under a <kernel>__<fn>_TID_<hash> name (and tagged gpu_kernel) while its call sites reference the canonical mangled symbol, so the module fails verification with "Symbol ... not found".

Repro shape (verified against current main):

#[kernel]
pub fn nested_helper(a: &[f32], b: &[u32], mut out: DisjointSlice<f32>) {
    #[inline(never)]
    fn pick<T: Copy>(xs: &[T], i: usize) -> T { xs[i % xs.len()] }
    // ...
    *slot = pick::<f32>(a, i) + pick::<u32>(b, i) as f32;  // Symbol ..pick.. not found
}

The existing closure skip already handled the anonymous flavor of exactly this problem; this PR folds both into one shared predicate.

Changes

  • New is_kernel_entry_def_path predicate: a def path is a kernel entry point only when its final segment carries the kernel marker; closures and named fns nested inside kernel bodies are rejected and left to the call-graph walk, which collects them under their mangled symbols as before.
  • The root scan's inline closure check is replaced by the predicate (one skip path instead of two).
  • Four unit tests in collector.rs covering: bare/qualified kernel paths, nested named fns (single and deep nesting), closures, and non-kernel paths.

Testing

  • cargo test in crates/rustc-codegen-cuda — 12 passed (4 new).

  • Repro kernel above: fails device codegen on main with Symbol ..._pick... not found (the def exported as nested_helper__pick_TID_<hash>); with the fix it builds and runs correctly on an RTX 5080 (sm_120).

  • Downstream validation: a shader stack whose reduction kernels define generic tree-reduce helpers inside kernel bodies compiles and runs bit-identically with this fix.

  • cargo test --workspace passes (crate-local suite; see above)

  • New example added — not needed: covered by unit tests on the predicate (repro kernel included above for reference)

Checklist

  • All commits signed off (git commit -s)
  • SPDX headers on new source files (no new files)

🤖 Generated with Claude Code


Maintainer note (2026-07-22): Follow-up commits extended this PR beyond the original description: is_kernel_function now delegates to the exact final-segment classifier directly (the root scan's manual skip path is gone entirely), near-miss negative tests were added, the helper_fn example gained a nested generic helper with two monomorphizations, and the smoketest gained a compile-only PTX assertion pinning the expected shape, so the "new example" item above is now covered after all. The branch was also rebased across #340's scoped-cache protocol: the classifier accepts the current or legacy kernel prefix on the final def-path segment (is_current_kernel_symbol / is_legacy_kernel_symbol), keeping legacy roots on the explicit protocol diagnostic path instead of silently dropping them.

haixuanTao and others added 2 commits July 22, 2026 12:06
`is_kernel_function` matches the kernel marker by substring, so a named `fn`
defined inside a `#[kernel]` body also matched — its def path carries the
kernel's name as a path prefix (`...::cuda_oxide_kernel_<hash>_k::helper`).
The root scan then treated the nested fn as a kernel: a generic
monomorphization was exported under a `<kernel>__<fn>_TID_<hash>` name (and
tagged gpu_kernel) while its call sites reference the canonical mangled
symbol, failing module verification with "Symbol ... not found".

Repro shape:

    #[kernel]
    pub fn k(...) {
        #[inline(never)]
        fn pick<T: Copy>(xs: &[T], i: usize) -> T { xs[i % xs.len()] }
        ... pick::<f32>(...) ...
    }

The closure skip already handled the anonymous flavor of this; fold both
into a shared `is_kernel_entry_def_path` predicate — a def path is a kernel
entry only when its *final* segment carries the kernel marker — with unit
tests. Nested items are collected transitively via the call-graph walk under
their mangled names, as before.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: haixuantao <[email protected]>
Use one exact final-segment kernel-entry classifier for both the preliminary CGU count and collector rooting. Extend helper_fn with two nested generic monomorphizations and make the compile-only smoketest assert one real kernel entry, two canonical helper functions, and no helper _TID_ exports.

Signed-off-by: nihalp <[email protected]>
@nihalpasham
nihalpasham force-pushed the fix/nested-fn-kernel-roots branch from 703d680 to 55fb298 Compare July 22, 2026 06:53
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks for the PR. LGTM. The diagnosis looks right: substring matching let items nested inside a #[kernel] body be rooted as kernels themselves.

  • The collector now classifies kernel entry points by the final def-path segment, so named fns and closures nested inside a kernel body are no longer rooted; they are collected transitively through the call-graph walk under their canonical mangled symbols.
  • This fixes the failure where rooting a nested generic fn minted a _TID_<hash> export name that no call site references, failing module verification with "Symbol ... not found".
  • I pushed maintainer follow-ups that unify is_kernel_function on the exact classifier (making the manual root-scan skip block redundant), add near-miss negative tests, give the helper_fn example a nested generic helper with two monomorphizations, and add a compile-only smoketest assertion pinning the expected PTX shape.
  • The branch was rebased onto current main across feat(codegen): opt-in build-time cubin materialization for embedded artifacts #340's scoped-cache protocol change: the classifier accepts the current or legacy prefix on the final segment (via is_current_kernel_symbol / is_legacy_kernel_symbol), so legacy roots still flow to the explicit protocol diagnostic instead of silently disappearing, and the tests derive their names from the prefix constants.

For example:

my_crate::<KERNEL_PREFIX>softmax                 -> kernel entry point (rooted)
my_crate::<KERNEL_PREFIX>softmax::helper         -> device helper (call-graph walk)
my_crate::<KERNEL_PREFIX>softmax::{closure#0}    -> device helper (call-graph walk)
my_crate::not_<KERNEL_PREFIX>softmax             -> ordinary host function

Reviewer note: All 21 backend unit tests passed, strict clippy and formatting are clean, and the compile-only smoketest passed with the new helper_fn PTX assertions (exactly one .entry, both mangled nested-helper .func definitions present, no stray _TID_ exports). Three independent adversarial reviews of the rebase reconciliation found no defects; the legacy-root diagnostic path is byte-identical to main. All hosted CI checks passed on the final head. There is no matching open issue to close.

@nihalpasham
nihalpasham merged commit 072318b into NVIDIA:main Jul 22, 2026
33 checks passed
nihalpasham added a commit to niklebedenko/cuda-oxide that referenced this pull request Jul 23, 2026
The compile-only gate required the two nested_identity monomorphizations
to survive as .visible .func in the final PTX. Internalizing non-root
helpers deliberately inlines and deletes them there, which is the
optimization this branch adds. What the NVIDIA#358 regression actually needs
pinned is canonical mangling and non-kernel classification, and both
are decided before the middle-end runs: assert them in the pre-opt
LLVM IR instead, and keep the PTX assertions for the single kernel
entry and the absence of _TID_ helper symbols.
nihalpasham added a commit that referenced this pull request Jul 23, 2026
* fix(ptx): internalize non-root device helpers

Signed-off-by: nik <[email protected]>

* refactor(llvm-export): compute one root list for @llvm.used and internalization

emit_llvm_used and public_symbols each re-implemented the
kernels-if-any-else-device-functions rule, so the @llvm.used set and the
internalize public-API list could silently drift apart. Compute the root
list once, as the union of kernel entries and #[device] definitions:
a #[device] export now stays visible even in a module that also has
kernels, while anonymous helpers carry neither marker and remain
internalizable.

* test(codegen): thread the kernel root through the libdevice PTX test

The #410 libdevice test predates public_symbols; pass the module's
kernel as the internalization root so the test now also covers the
llvm-link + internalize composition.

* refactor(codegen): group PTX module inputs into one parameter struct

Threading public_symbols through generate_ptx alongside #410's libdevice
parameter pushed both entry points past clippy's argument limit. The
module-shaped inputs (IR path, PTX output path, symbol roots) already
had a struct inside the impl; take PtxModule at the public boundary too
instead of three loose parameters.

* test(smoke): pin helper_fn's nested-helper contract in the pre-opt IR

The compile-only gate required the two nested_identity monomorphizations
to survive as .visible .func in the final PTX. Internalizing non-root
helpers deliberately inlines and deletes them there, which is the
optimization this branch adds. What the #358 regression actually needs
pinned is canonical mangling and non-kernel classification, and both
are decided before the middle-end runs: assert them in the pre-opt
LLVM IR instead, and keep the PTX assertions for the single kernel
entry and the absence of _TID_ helper symbols.

---------

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

Labels

bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX) examples Example kernels and host harnesses under crates/rustc-codegen-cuda/examples tests Adds or improves test coverage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants