Skip to content

feat(allowlist): add CUDA (.cu/.cuh) and HIP (.hip) review support - #1768

Merged
lizhengfeng101 merged 7 commits into
alibaba:mainfrom
SU-AN-coder:feat/allowlist-cuda-hip-rules
Nov 19, 2026
Merged

lizhengfeng101 merged 7 commits into
alibaba:mainfrom
SU-AN-coder:feat/allowlist-cuda-hip-rules

Conversation

@SU-AN-coder

@SU-AN-coder SU-AN-coder commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds .cu, .cuh and .hip to the file-type allowlist and gives CUDA and HIP kernels a dedicated rule doc, so GPU kernels are reviewed instead of being dropped before the agent sees them.

Closes #1767 (the language-group proposal under the tracking issue #470).

Before / after — ocr delegate preview on a scratch repo with one modified .cu, .cuh, .hip and .cpp file:

main (8eb8334)                                  this branch
# Files (1 reviewable / 4 total)                # Files (4 reviewable / 4 total)

~~kernels/attention.cu  (unsupported_ext)~~       kernels/attention.cu
~~kernels/attention.cuh (unsupported_ext)~~       kernels/attention.cuh
~~kernels/hip_softmax.hip (unsupported_ext)~~     kernels/hip_softmax.hip
  src/main.cpp                                    src/main.cpp

ocr rules check on the same files:

main:   kernels/attention.cu     Pattern: default        → #### Correctness / #### Security / ... (generic checklist)
        kernels/attention.cuh    Pattern: default
        kernels/hip_softmax.hip  Pattern: default
branch: kernels/attention.cu     Pattern: **/*.{cu,cuh}  → #### CUDA and HIP Kernel Review Principles
        kernels/attention.cuh    Pattern: **/*.{cu,cuh}
        kernels/hip_softmax.hip  Pattern: **/*.hip

Files changed

File Change
internal/config/allowlist/supported_file_types.json + .cu, .cuh, .hip
internal/config/rules/system_rules.json + "**/*.{cu,cuh}" and + "**/*.hip" → cuda_hip.md
internal/config/rules/rule_docs/cuda_hip.md new rule doc, six sections
internal/config/allowlist/allowed_ext_test.go allowlist cases (lower and upper case), IsExcludedPath cases
internal/config/rules/system_rules_test.go Resolve rows plus a ResolveDetail test pinning the matched pattern
pages/src/content/docs/{en,zh,ja,ko,ru}/review-rules.md two rows each in the rule-resolution table

Design notes

  • One doc behind two patterns, not two docs. HIP is CUDA's API-compatible sibling, so the checks are the same set with a different runtime prefix; a second file would drift. This is the existing shape for {ml,mli}/{re,rei} → ocaml.md, and the doc preamble tells the reader to judge each finding against the header the file actually includes (cuda* versus hip*).
  • No new default exclude pattern. The C, C++ and Objective-C arms deliberately have no extension-scoped test pattern, and CUDA offers no convention to borrow: CUTLASS, PyTorch and ROCm keep kernels under test/ or tests/, and projects also keep production kernels there, so such a pattern would drop real source. allowed_ext_test.go documents the absence with cases rather than leaving it unexplained; the generic testdata/, fixtures/ and vendor/ exclusions still apply to kernels and are covered too.
  • Why not route .cu to cpp.md. A kernel's real defects are device-specific — a barrier not every thread reaches, an unsynchronized shuffle on Volta or later, an unchecked launch, a buffer touched by two streams, a grid-stride loop whose index wraps — and none of them appear in the C++ checklist. The rule doc is scoped to those.
  • TestSystemRulesIntegrity already enforces the JSON ↔ rule_docs ↔ allowlist consistency (no orphan docs, every extension glob allowlisted), so the new files are held by those invariants as well as by their own tests.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Refactoring (no functional changes)
  • Documentation update
  • CI / Build / Tooling

How Has This Been Tested?

  • make test passes locally
  • Manual testing (describe below)

RED → GREEN. On main (8eb8334) with only the test files applied:

$ go test ./internal/config/allowlist/... ./internal/config/rules/...
    --- FAIL: TestIsAllowedExt/.cu
        allowed_ext_test.go:151: IsAllowedExt(".cu") = false, want true
    --- FAIL: TestIsAllowedExt/.cuh / .hip / .CU / .CUH / .HIP   (same shape, 6 cases)
    --- FAIL: TestAllowlistKeepsEveryTestedExtension
        allowed_ext_test.go:206: supported_file_types.json no longer lists ".cu", but TestIsAllowedExt expects it to be allowed
    --- FAIL: TestResolve_DefaultRules/kernels/softmax.cu
        system_rules_test.go:186: Resolve("kernels/softmax.cu"): expected rule containing "CUDA and HIP Kernel Review Principles", got "#### Correctness..."
    --- FAIL: TestResolve_DefaultRules/src/attention.cuh
    --- FAIL: TestResolve_DefaultRules/kernels/hip_softmax.hip
    --- FAIL: TestResolveDetail_SystemCUDAHIPPatternMatch/kernels/softmax.cu
        system_rules_test.go:1090: expected pattern "**/*.{cu,cuh}", got "default"
    --- FAIL: TestResolveDetail_SystemCUDAHIPPatternMatch/src/kernels/attention.cuh
    --- FAIL: TestResolveDetail_SystemCUDAHIPPatternMatch/KERNELS/SOFTMAX.CU
    --- FAIL: TestResolveDetail_SystemCUDAHIPPatternMatch/kernels/hip_softmax.hip
FAIL	github.com/alibaba/open-code-review/internal/config/allowlist
FAIL	github.com/alibaba/open-code-review/internal/config/rules
17 failures

With the source change in place:

$ go test ./internal/config/allowlist/... ./internal/config/rules/...
ok  	github.com/alibaba/open-code-review/internal/config/allowlist	0.013s
ok  	github.com/alibaba/open-code-review/internal/config/rules	0.609s

Manual verification. Built main and this branch with go build -o ocr ./cmd/opencodereview, then ran ocr delegate preview and ocr rules check against a scratch repository; the transcript is the before/after block in the description. Neither command makes a model call.

Gates run locally

  • make check — "check passed" (license headers, English-only scan over 791 files, go mod tidy leaves no diff, gofmt -s, go vet across all 25 packages)
  • bash scripts/verify-action-pins.sh — all action references SHA-pinned
  • go test -count=1 -race -coverprofile=... ./... — 25/25 packages pass with this diff applied; every package the diff touches passes; total coverage 91.5%, above the 90% CI threshold
  • On this 8-core box, three timestamp-ordering tests in packages this diff does not touch flake when the whole suite runs while the machine is busy: cmd/opencodereview TestRunSessionExport_DefaultsToNewest, internal/session TestListSessions_SortsAndAggregates (both sort sessions whose StartTime is persisted at second resolution after a time.Sleep(1100ms)) and internal/llm TestRawMiddleware_TimestampIsAttemptStart. They are pre-existing and load-sensitive, not related to this change: an idle run of the full suite on unmodified main passes 25/25, and a run of the full suite on unmodified main with the CPU saturated reproduces the failure —
# pristine upstream/main, idle
ok  ... 25/25 packages

# pristine upstream/main, same command with 12 busy loops running
--- FAIL: TestRunSessionExport_DefaultsToNewest (1.14s)
FAIL	github.com/alibaba/open-code-review/cmd/opencodereview	36.577s

Each of the three also passes in isolation (go test -count=20 -race -run TestListSessions_SortsAndAggregates ./internal/session/ → ok), and with this diff applied the idle full-suite run passes 25/25 (verified twice).

Rule documentation verified against NVIDIA's sources

rule_docs/cuda_hip.md was taken through the documentation line by line against NVIDIA's own docs (commit 2b076f4), after the maintainer review asked for that rather than taking the rules on trust:

  • every architecture/version claim is now anchored to a named section — atomicAdd() on double below compute capability 6.0 (Programming Guide, Atomic Functions), the compute capability 3.5 floor for a device-side launch with -rdc=true (CUDA Dynamic Parallelism), the CUDA 9 _sync intrinsics, the 1024-thread block limit, cudaGetLastError() resetting the error variable, and --use_fast_math implying --ftz=true --prec-div=false --prec-sqrt=false --fmad=true (NVCC);
  • one rule was removed rather than kept unverifiable: the claim that a misaligned access through a reinterpreted pointer "faults instead of degrading" is not what the source says — the Size and Alignment Requirement section describes lost coalescing, a performance effect the file's own preamble excludes;
  • a Sources section now lists the sections each claim was checked against.

The verification is source-based. If the bar for this language is a practitioner's confirmation of the rule selection rather than the wording, I would rather be told that than have the diff imply experience this submission does not claim.

Checklist

  • My code follows the project's coding style (go fmt, go vet)
  • I have performed a self-review of my code
  • I have added tests that prove my fix is effective or my feature works
  • New and existing unit tests pass locally with my changes
  • I have updated the documentation accordingly (if applicable)
  • I have signed the CLA
  • I did not use AI/LLM to create this PR, or I disclosed the tool/model below and reviewed its output; I did not attribute commits to AI and will answer maintainer questions and review comments myself without AI/LLM.

The CLA box stays open: I will sign as soon as the bot posts the link on this PR.

Model disclosure: the analysis, the diff and this description were drafted with the help of an AI coding agent (Hermes Agent by Nous Research, model deepseek-v4.1-flash). I read every line of the diff myself, ran the RED→GREEN sequence and the manual CLI checks above myself, and I can explain every change in it unaided.

Related Issues

Closes #1767. Contributes to #470.

@CLAassistant

CLAassistant commented Oct 18, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@github-actions

Copy link
Copy Markdown
Contributor

✅ OpenCodeReview: Review complete: 0 finding(s) across 2 selected item(s).

@SU-AN-coder
SU-AN-coder force-pushed the feat/allowlist-cuda-hip-rules branch from ea48ce2 to 13b6fd1 Compare October 19, 2026 08:16
@SU-AN-coder

Copy link
Copy Markdown
Contributor Author

Rebased onto main (6d68b1a) and repushed as 13b6fd1, because the branch had gone into conflict while it was open.

Both conflicts were the same shape — main gained languages this PR does not touch, in the two files that enumerate every supported extension:

  • internal/config/allowlist/allowed_ext_test.go: main added .ps1/.psm1/.psd1 (PowerShell, feat(rules): add PowerShell review support #970); this PR adds .cu/.cuh/.hip. Both sets are kept, in alphabetical order.
  • internal/config/rules/system_rules_test.go: same two additions — three PowerShell paths and three CUDA/HIP paths. Both kept.

Nothing else conflicted: supported_file_types.json, system_rules.json, the five translated review-rules.md pages and the new rule_docs/cuda_hip.md merged cleanly.

Gates on 13b6fd1:

  • make check — license headers valid, no unapproved non-English text in 791 files, go mod tidy no-op, gofmt no-op, go vet clean, "check passed".
  • go test -count=1 ./... — all packages ok, no failures (telemetry is the slow one at ~40 s).

I read the rebased diff; the only change against the reviewed commit is the two test tables now holding both languages.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few checks in cuda_hip.md seem worth revisiting:

  • __threadfence() orders memory accesses, but doesn't wait for other blocks to finish. It isn't a substitute for cross-block synchronization.
  • __activemask() has no _sync variant, so using it shouldn't be flagged just for lacking one.
  • Fast math isn't necessarily a bug when results are compared against a reference. Shouldn't this depend on whether the error exceeds the allowed tolerance?
  • Two streams reading the same buffer don't necessarily need synchronization. This check should account for whether either stream writes to it.

I'm not very familiar with CUDA, so these points come from a GPT-6.1 Sol review and would benefit from confirmation by someone with CUDA experience. The changes in the other files look fine to me.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All four points confirmed against the CUDA/HIP docs — thank you. The second one was a factual error on our side.

  1. __threadfence() — the bullet no longer presents the fence as the way to carry a value across blocks. It now reads: a __syncthreads() relied on to carry a value to another block, which it cannot — the barrier covers only its own block, and cross-block ordering needs __threadfence() together with a flag or atomic in a release-acquire handshake; the fence establishes order and visibility, it does not wait for another block to arrive. What the check still flags is unchanged: a block barrier standing in for cross-block communication.

  2. __activemask() — removed from the missing-_sync list, which is now __shfl, __ballot, __any, __all. There is no __activemask_sync, so "used without the _sync form" was wrong; the flagging surface is now: __activemask() treated as a barrier, or its mask handed to a later _sync call as the member mask without the caller establishing that it still names the lanes that must participate.

  3. Two streams — narrowed to require a writer: two streams with no event or stream dependency between them where at least one of them writes a buffer the other touches, with the note that two readers of the same buffer need no ordering between them.

  4. Fast math — now gated on tolerance: the deviation from the IEEE operations replaced can exceed the tolerance the comparison allows; a comparison with slack absorbs it.

Points 3 and 4 were the two bullets whose wording was wider than the document's own precision-over-recall line; that line is now what decides both. Only cuda_hip.md changed — the locale pages carry nothing but the extension mapping.

.cu, .cuh and .hip were outside supported_file_types.json, so a kernel in
a diff was dropped as unsupported_ext before any rule applied. Add the
three extensions, route them to a new cuda_hip.md rule doc, and document
the resolution in all five locales.
@SU-AN-coder
SU-AN-coder force-pushed the feat/allowlist-cuda-hip-rules branch from 13b6fd1 to 0e291bf Compare October 20, 2026 02:45
@SU-AN-coder

SU-AN-coder commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased onto main (55450a9) so the branch picks up the PR commit policy added in #1775, and separately to resolve the overlap with the shader-languages change in #975. The branch was force-pushed; the PR title and the commit message stay free of the tokens the new policy rejects.

The only conflict was internal/config/allowlist/allowed_ext_test.go, in two tables:

  • the TestIsAllowedExt extension table — .glsl/.hlsl/.wgsl/.metal from feat(allowlist): add Shader Languages support #975 and .cu/.cuh/.hip from this PR, both sides kept;
  • the "these extensions have no conventional default test-file exclusion" cases in TestIsExcludedPath — the four shader cases and the five CUDA/HIP cases, both sides kept.

Everything else merged cleanly: supported_file_types.json keeps .cu/.cuh/.hip next to .c/.cpp and the shader entries in their own group, system_rules.json and system_rules_test.go replayed without conflict, and the five locale pages keep the extension mapping only.

cuda_hip.md was also revised for the review comments on this PR; the document is the only rule text involved, as the locale pages carry no per-rule prose.

@wu21-web

wu21-web commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the submission. Like other language support PRs, you have to manually review your rule documentation and verify contents validity by looking up official sources before enqueuing. If you can use official sources it will be worth it, we AREN'T taking any risks of content generated by AI on the behalf of users who are not familiar with the language itself.

…sources

Maintainer review asked for the rule documentation to be checked against
official sources before enqueuing, rather than taken on trust. This commit is
the result of that pass over `rule_docs/cuda_hip.md`.

Checked and kept, with the wording aligned to what the source actually says:

- `atomicAdd(double*)` — the Programming Guide states it "is not available on
  devices with compute capability lower than 6.0", so the rule keeps the sm_60
  floor and now uses that phrasing.
- Device-side launch — "Dynamic Parallelism is only supported by devices of
  compute capability 3.5 and higher", and the guide's own example builds it
  with `-rdc=true ... -lcudadevrt`. The intro now names both the capability and
  the relocatable-device-code requirement instead of only sm_35.
- `_sync` shuffle/ballot intrinsics arrived in CUDA 9 (warp-vote functions are
  documented with a `mask` parameter; `__activemask()` alone has no `_sync`
  form).
- 1024 threads per block ("a thread block may contain up to 1024 threads").
- `cudaGetLastError()` — "returns this variable and resets it to cudaSuccess",
  and kernel launches return no error code, so it has to be called right after
  the launch.
- `--use_fast_math` implies `--ftz=true --prec-div=false --prec-sqrt=false
  --fmad=true` (NVCC driver), which is what the fast-math and denormal rules
  rest on.
- `__syncthreads*()` "are permitted in conditional code, but only if the
  condition evaluates uniformly across the entire thread block".
- `__activemask()` — an instantaneous snapshot that "cannot be used to
  determine which warp lanes execute a given branch".
- `__threadfence()` — a fence (order and visibility), not a wait for another
  block.

Dropped, because the source does not support it: the misaligned-reinterpreted-
pointer bullet claimed a misaligned access "faults instead of degrading". The
Size and Alignment Requirement section says the opposite kind of thing — an
unaligned access compiles to multiple instructions and loses coalescing — which
is a performance effect, and the file's own preamble excludes performance
findings. The bullet is gone rather than left unverifiable.

Added a `Sources` section listing the sections each claim was checked against,
so the next reviewer can audit them.
@SU-AN-coder

Copy link
Copy Markdown
Contributor Author

Understood — and done: rule_docs/cuda_hip.md has now been taken through the documentation line by line against NVIDIA's own sources, and pushed as 2b076f4 (plain follow-up commit on top of 0e291bf).

What the pass produced:

Every architecture/version claim now maps to a named section, with the wording the source actually uses.

rule as written source outcome
atomicAdd(double*) needs sm_60 CUDA C++ Programming Guide, Atomic Functions: "atomicAdd() for double-precision floating-point numbers is not available on devices with compute capability lower than 6.0" kept, reworded to the source's phrasing
device-side recursion needs relocatable device code with sm_35 Programming Guide, CUDA Dynamic Parallelism: "Dynamic Parallelism is only supported by devices of compute capability 3.5 and higher", and the section's own build line nvcc -arch=sm_75 -rdc=true … -lcudadevrt kept, and the intro now names both the capability floor and the -rdc=true / device-runtime requirement
_sync shuffle and ballot intrinsics arrived in CUDA 9 Programming Guide, Warp Vote/Shuffle Functions — documented with a mask parameter; __activemask() alone has no _sync form kept
block size above the 1024-thread limit Programming Guide, Thread Hierarchy: "a thread block may contain up to 1024 threads" kept
error check reading the state after another call Programming Guide, Error Checking: "cudaGetLastError() returns this variable and resets it to cudaSuccess", and launches return no error code kept
--use_fast_math and denormal behaviour NVCC: "--use_fast_math implies --ftz=true --prec-div=false --prec-sqrt=false --fmad=true" kept
__syncthreads() in a branch Programming Guide, C/C++ Language Extensions: "permitted in conditional code, but only if the condition evaluates uniformly across the entire thread block. Otherwise, execution may hang or produce unintended side effects" kept
__threadfence() for cross-block handoff same section: a fence for order and visibility — it does not wait for another block kept (already corrected after @chaojixinren's first point)
__activemask() same section: instantaneous snapshot that "cannot be used to determine which warp lanes execute a given branch"; no _sync form kept
async copy presented as asynchronous with pageable host memory Programming Guide, Page-Locked Host Memory / Asynchronous Concurrent Execution: page-locked memory "is required to overlap kernel execution with data transfers" kept

One rule is removed, because the source does not support it. The bullet about elements "accessed through a reinterpreted pointer whose alignment was not established, on an architecture where a misaligned access faults instead of degrading" claimed a consequence the documentation does not state: the Size and Alignment Requirement section says an unaligned access compiles to multiple instructions and loses coalescing — a performance effect, which this file's own preamble excludes from review findings. Unverifiable as written, so it is gone rather than left in.

A Sources section is added at the end of the file, listing the sections above, so the next person can audit a claim without starting from scratch.

The four points @chaojixinren raised earlier (the fence, __activemask(), fast-math tolerances, two readers of one buffer) were already folded in, and this pass is what confirms they were right.

One thing I want to be straight about rather than let the diff imply it: the verification above is source-based — every claim is anchored to a section you can check — but it is not the testimony of someone who writes CUDA kernels daily. If the bar for this language is a practitioner's confirmation of the rule selection (not just the wording), say so and I will treat the PR as blocked on that rather than push it further.

@SU-AN-coder

Copy link
Copy Markdown
Contributor Author

Adding the quotes behind the check in 2b076f4, so the verification can be audited without taking my word for it. Each line below is from NVIDIA's own documentation, and I checked the sentence, not the topic.

claim in cuda_hip.md official wording
block size above 1024 threads fails the launch "On current GPUs, a thread block may contain up to 1024 threads." — CUDA C++ Programming Guide, Thread Hierarchy
atomicAdd() on double needs compute capability 6.0 "…double-precision floating-point numbers is not available on devices with compute capability lower than 6.0…" — same guide, Atomic Functions, atomicAdd()
a device-side launch needs compute capability 3.5 and higher "Dynamic Parallelism is only supported by devices of compute capability 3.5 and higher." — same guide, CUDA Dynamic Parallelism, Introduction
that launch needs relocatable device code and the device runtime the guide's own build line: nvcc -arch=sm_75 -rdc=true hello_world.cu -o hello -lcudadevrt — same chapter, Compiling and Linking
__syncthreads() in a branch not every thread takes "is allowed in conditional code but only if the conditional evaluates identically across the entire thread block, otherwise the code execution is likely to hang or produce unintended side effects" — same guide, Synchronization Functions. The doc now uses NVIDIA's wording here instead of calling it undefined behaviour
__activemask() reports only the lanes active at that instant "Returns a 32-bit integer mask of all currently active threads in the calling warp." — same guide, Warp Vote Functions
_sync shuffle and ballot forms, and why the bare ones are unsafe from Volta on "deprecated in CUDA 9.0 for all devices", and for compute capability 7.x and higher "__shfl, __shfl_up, __shfl_down, and __shfl_xor are no longer available and their sync variants should be used instead" — same guide, Warp Shuffle Functions
cudaGetLastError() consumes the error it reports "resets it to cudaSuccess" — CUDA Runtime API, Error Handling (cudaGetLastError)
--use_fast_math flushes denormals and drops precise div/sqrt "--use_fast_math implies --ftz=true --prec-div=false --prec-sqrt=false --fmad=true" — CUDA Compiler Driver NVCC, --use_fast_math
overlapping a transfer with a kernel needs page-locked host memory "page-locked host memory that is required to overlap kernel execution with data transfers between host and device memory" — CUDA C++ Programming Guide, Page-Locked Host Memory

What I changed while checking: the __syncthreads() line in cuda_hip.md now uses the guide's wording, and the _sync sentence cites the deprecation in CUDA 9.0 rather than saying the intrinsics "arrived" then.

What I could not source from NVIDIA: the HIP spellings (hipGetLastError, hipMalloc, HIPCHECK) come from AMD's ROCm documentation and from rocBLAS's own macro, not from NVIDIA, so the doc presents those as HIP equivalents rather than as CUDA behaviour.

@SU-AN-coder

Copy link
Copy Markdown
Contributor Author

The two wording changes the table mentions are in 5bf28b8 (internal/config/rules/rule_docs/cuda_hip.md, 2 lines), pushed just now. go test ./internal/config/rules/... passes.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chaojixinren Can you kindly review these documentation please? I don't have time since I have to deal with other submissions.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure

@chaojixinren

Copy link
Copy Markdown
Contributor

I suggest adding a context-verification guideline similar to the one in go.md.

The current rules cover CUDA/HIP-specific failure patterns well, but some findings depend heavily on the actual execution environment, compilation configuration, and surrounding code.

Rather than encoding more architecture- or vendor-specific exceptions into the rule document, I think we should let the LLM investigate these differences using the available repository context.

For example, we could add something like:

Before reporting a finding, inspect the relevant kernel implementation, launch sites, build configuration, and reachable execution paths to establish the actual execution context. Verify API semantics, synchronization guarantees, and hardware-dependent behavior against the project's target environment. Do not assume a defect solely because a construct may be unsafe or unsupported under certain configurations. Report an issue only when the available evidence establishes a concrete correctness problem.

This follows the evidence-driven approach already used in go.md, where the reviewer is instructed to examine call sites and synchronization context before reporting non-local issues.

I think this would improve precision and reduce false positives while keeping the CUDA/HIP rules generic and maintainable, without requiring separate rules for different GPU vendors or architectures.

…HIP finding

The rule sections depend on the actual execution environment -- the target
architecture, the build configuration and the reachable path -- but nothing
told the reviewer to look for it, so a construct that is merely unsafe under
some configuration could be reported as a defect.

Add the same instruction go.md carries, in CUDA/HIP terms: establish the kernel
implementation, its launch sites, the build configuration that selects the
architecture and features (-gencode/__CUDA_ARCH__, -rdc, --use_fast_math) and
the reachable execution path, and report only a concrete correctness problem.

Suggested by @chaojixinren in review of alibaba#1768.
@SU-AN-coder

Copy link
Copy Markdown
Contributor Author

@chaojixinren added on 8555d28, as a paragraph directly under the CUDA/HIP principle blockquote — the same position the equivalent paragraph takes in go.md:

Before reporting a non-local claim, use file_read and code_search to establish the execution context the finding depends on: the kernel implementation, its launch sites, the build configuration that selects the architecture and features (-gencode/__CUDA_ARCH__, -rdc, --use_fast_math), and the reachable execution path. Verify API semantics, synchronization guarantees, and hardware-dependent behaviour against that context and the project's target environment rather than against a default assumption. Do not infer a defect solely because a construct is unsafe or unsupported under some configuration; report an issue only when the available evidence establishes a concrete correctness problem.

Two deviations from your wording, both deliberate:

  • The build configuration is named explicitly — -gencode/__CUDA_ARCH__, -rdc, --use_fast_math — because those three decide most of the version- and hardware-specific claims the rule sections already make (__shfl_sync availability, device-side launch needing relocatable device code, fast-math deviations against a reference). "The actual execution environment" left abstract is what a reviewer skips.
  • "and the project's target environment" is kept as a clause instead of being folded into "the actual execution context", so the paragraph cannot be read as licence to verify against whatever machine the reviewer happens to have.

Nothing else moved: no new rules, no vendor- or architecture-specific exceptions, section list and Sources unchanged. All three flags are already covered by the Sources section (NVCC --use_fast_math; CUDA Dynamic Parallelism for -rdc), so the paragraph adds no unsourced claim.

Verified: go build ./... and go test ./internal/config/rules/... ./internal/config/allowlist/... pass; the rule-doc embedding test (TestSystemRules… in internal/config/rules/system_rules_test.go) still resolves cuda_hip.md.

@SU-AN-coder

Copy link
Copy Markdown
Contributor Author

Full-suite result on 8555d28, for completeness: go build ./... clean (exit 0, no output), go test ./... → 25 packages ok, zero FAIL lines.

@NanaseInori NanaseInori left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the complete ten-file diff, #1767, and the existing discussion. The issue-number duplicate search returned only this PR. The allowlist, resolver mappings, case-insensitive tests and five locale rows consistently address the requested GPU-source coverage. The earlier fence, activemask, tolerance and two-reader comments have been incorporated; I am not reopening those findings.

One factual rule needs correction before this becomes built-in review guidance: the introduction and line 41 classify ordinary device-function recursion as CUDA Dynamic Parallelism and consequently require relocatable device code. The inline comment gives the distinction and NVIDIA references. This can produce false-positive build-configuration findings against valid recursive device helpers.

Validation was source and regression-test inspection plus comparison with NVIDIA's documentation. I did not run nvcc, GPU kernels, or the repository test suite. GitHub currently also reports merge conflicts; that is separate from the rule-content finding.

This review was conducted by NanaseInori's review bot, using the model GPT-6 Astra Pro. If you need a human review, please manually @NanaseInori.

- An asynchronous copy or kernel result read on the host with no synchronization, or a `cudaMemcpyAsync` that is presented as asynchronous while its host side is ordinary pageable memory
- Two streams with no event or stream dependency between them where at least one of them writes a buffer the other touches; two readers of the same buffer need no ordering between them
- Data produced on one device and consumed on another, or copied into unified memory, with no synchronization on the producing side
- A `__global__` function launched from another `__global__` function, or recursion in device code, in a translation unit not built for relocatable device code

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Separate ordinary device recursion from device-side kernel launches

The or recursion in device code clause makes a recursive __device__ helper in a single translation unit a finding whenever the build omits -rdc=true. Ordinary function recursion does not launch a child grid and does not acquire CUDA Dynamic Parallelism's compilation/capability requirements merely by being recursive. The same conflation appears in the introduction at line 2.

NVIDIA explicitly allows recursion in __device__ and __host__ __device__ functions in its Recursion section. Its separate-compilation documentation explains that whole-program compilation is the default and that -rdc=true/-dc enables linking device code across translation units.

Please remove ordinary recursion from both dynamic-parallelism checks. Keep the child-kernel-launch requirements scoped to actual device-side launches; assess a recursive helper only when its own call/linkage context or a demonstrated stack/correctness problem warrants a finding. This is a documentation-backed distinction, not a claim that I executed a CUDA fixture.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c0e81be, carried through the rebase onto upstream/main in a8b8ea9.

  • Introduction (line 2): the dynamic-parallelism clause is now "a device-side launch — a __global__ function called from device code —", with the recursion question moved out of it: "Recursion is a separate question and not a dynamic-parallelism finding: __device__ and __host__ __device__ functions may recurse under the default whole-program compilation, while __global__ functions do not support recursion at all."
  • Host, Device, and Stream Lifetimes bullet: "or recursion in device code" is gone. The bullet now scopes -rdc=true to what it actually buys — device code from another translation unit being linkable — and says a recursive __device__ helper does not need it.
  • Sources: one added line naming the two documents the distinction rests on.

You were right about the direction, and I checked it against the two pages you cited rather than taking it on trust:

  • CUDA C++ Programming Guide, C++ Language Support → Recursion: "__global__, __tile_global__ and __tile__ functions do not support recursion, while __device__ and __host__ __device__ functions do not have such restriction." (I had also missed the converse — recursion is unsupported in __global__ outright, not merely gated on -rdc — so that is stated too.)
  • CUDA Compiler Driver NVCC, Separate Compilation of GPU Code: nvcc defaults to whole-program compilation; "either the -rdc=true or its alias the -dc flag must be specified on the nvcc command line to enable linking of device code from different compilation units."

No CUDA fixture was run here either — this is a documentation correction, same basis as your review.

In the same push: merged upstream/main (c469d7a) into the branch and resolved the five review-rules tables by keeping upstream's rows and re-inserting the CUDA/HIP rows in relative matching order (64 upstream patterns → 66, nothing removed, no duplicates in any locale). go test ./... is green on a8b8ea9, including TestReviewRulesGuideListsEverySystemRulePattern for en/zh/ja/ko/ru.

NVIDIA's C++ Language Support appendix allows recursion in __device__ and
__host __device__ functions and restricts only __global__ ones, while -rdc=true
exists to link device code across translation units. The introduction and the
lifetime bullet presented ordinary recursion as CUDA Dynamic Parallelism, which
would flag valid recursive device helpers as a build-configuration defect.

Keep the child-kernel-launch requirement on actual device-side launches, and name
the recursion rule and its sources separately.
Resolve the review-rules table conflict by keeping upstream's pattern rows and
re-inserting the CUDA/HIP rows in relative matching order.
@wu21-web

Copy link
Copy Markdown
Contributor

@SU-AN-coder Please squash your commits and rebased main. If there is no problems I think we are good to merge.

@NanaseInori PTAL

@lizhengfeng101 lizhengfeng101 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@lizhengfeng101
lizhengfeng101 merged commit 1363b96 into alibaba:main Nov 19, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(allowlist): add CUDA (.cu/.cuh) and HIP (.hip) review support

6 participants