Conventions report · NVIDIA/hyperflare-inference #231

Raw Markdown for agents: https://autobot.eidonix.com/p/a950b167-2699-4e79-957c-302c461fd527.md

Review of PR #231 — Race a Triton tile kernel against cuBLAS for GLM's BF16 head projections

Lens: conventions and duplication. Every one of the six changed files was read in context (ignition/components/bf16_bmm.py in full, ignition/components/linear.py, ignition/preparation/tuning.py, tests/components/test_bf16_bmm.py, tests/components/test_bf16_bmm_cuda.py, tests/preparation/test_toolchain.py), against the charter, AGENTS.md (lines 73-78, 79-82, 289-297), docs/preparation-development.md, and the closest precedents (native_operator.py, window_staging.py, selected_attention.py, qk_norm_rope.py, gated_norm_preparation.py, moe_sm103.py (not opened), sm103_projection.py, fixtures/bf16_gemv.py, fixtures/projection.py, fixtures/resources.py). Every claim below was re-verified in the head commit (0ba78eb) code or diff.

Key findings


Should fix

1. ignition/components/linear.py:89-96 — orphaned flare::bmm_out custom op

Before this PR, BatchedUnquantizedProjection.__call__ called _bmm_out(source, self.weight, self.output). The diff replaces exactly that line with bf16_bmm.execute(source, self.weight, self.output, self.plan.handle) (linear.py:85) and does not touch the definition:

89  @torch.library.custom_op("flare::bmm_out", mutates_args=("out",))
90  def _bmm_out(source: torch.Tensor, weight: torch.Tensor, out: torch.Tensor) -> None:
91      torch.bmm(source, weight, out=out)
94  @_bmm_out.register_fake
95  def _fake_bmm_out(source, weight, out):
96      pass

Verified: a search for bmm_out across the head commit returns only this definition/fake and the unrelated sm103_bmm_out (defined linear.py:463-469, called linear.py:452). Nothing under tests/, ignition/recipes/, helios/src or heliopause references flare::bmm_out.

Why it matters: AGENTS.md:73-78 requires that refactoring "directly support the requested behavior or remove a demonstrated source of defects or cost" and rejects churn; a registered but uncallable custom op is exactly the residue the rule targets, and it stays in the operator namespace that captured-graph tests enumerate. Nothing is lost by deleting it: the behaviour (torch.bmm into a caller-owned strided view) is now a strict subset of bf16_bmm.State.run (bf16_bmm.py:124-126). This also trips the CI lint surface for dead code.

Fix: delete linear.py:89-96 (op and fake registration). If it must stay for an out-of-tree user, say so in the docstring — currently there is no citation anywhere.

2. ignition/components/bf16_bmm.py:174 — input_factory called without session=

174  inputs = input_factory(source, output, storage=getattr(session, "benchmark_storage", None))

Every other preparation-time caller passes the session: linear.py:130-131, linear.py:143, linear.py:354, mla_norm_quant.py:46-47, varlen_attention.py:56-57. input_factory forwards it to candidate_inputs (fixtures/projection.py:37-42 → fixtures/resources.py:15-38), which uses it for exactly this situation:

30  if isinstance(session, RecordedPreparationSession):
31      # A preceding operator can leave its fixture in the session cache.
32      # Live trials own their storage independently of that cache entry.
33      session.release_benchmark_cache()

Why it matters: without session=, the new batched-projection race does not release the previously prepared operator's cached benchmark fixture, so the race runs while that cache entry is still resident. This is a behavioural divergence from the documented fixture contract, not a naming preference: at GLM's 8,192-row stacks the cached sibling fixture is hundreds of MB, which is precisely the memory the release call exists to reclaim before a race allocates. It is the only caller in the repository that omits the argument, so it looks like an oversight rather than a decision.

Fix: input_factory(source, output, storage=..., session=session).

3. ignition/components/bf16_bmm.py:176-179 — duplicates fixtures/bf16_gemv.benchmark_call

176  def benchmark(state):
177      operands = inputs()
178      return PreparedCall(run=lambda: state.run(operands.source, weight, operands.output),
179                          produce=operands.produce, output=operands.output, owners=(operands, weight))

ignition/preparation/fixtures/bf16_gemv.py:10-16 is documented as "Private activation trials for BF16 projection backend selection" and builds the same PreparedCall from the same input_factory operands — and it is already the fixture used by both other BF16 projection paths in linear.py (line 129 via partial(bf16_fixtures.benchmark_call, ...) and line 142). The only difference is the callee signature: state.run(operands.source, weight, out=operands.output, bias=bias) versus this PR's positional state.run(source, weight, output) and no bias in owners.

Why it matters: the race-fixture shape (run/produce/output/owners including the weight) is a single convention implemented once per fixture module; a hand-rolled copy inside a component is the pattern AGENTS.md:73-78 asks reviewers to reject ("Do not add … fallback layers … without a concrete requirement"), and bf16_bmm.State.run would need a bias=None/out=-compatible signature to be reusable — which is a one-line change, since State.run already takes the output positionally last.

Fix: adapt State.run to accept bias=None and out= like bf16_gemv's states, then use partial(bf16_fixtures.benchmark_call, inputs=..., weight=weight, bias=None); or, if the signature divergence is deliberate, state it in the module docstring.

4. ignition/components/bf16_bmm.py:153 and :102-103 — re-implements tensor_facts / metadata_tensor

query_from_call stores tuple((tuple(t.shape), tuple(t.stride())) for t in tensors) and compile_bmm rebuilds meta tensors with torch.empty_strided(shape, stride, dtype=torch.bfloat16, device="meta"). The repository already has this exact round-trip pair:

The new copy drops the dtype field (defensible, BF16 is fixed and query_from_call:144 enforces it) but silently forks the "operands as JSON facts" convention that the other three components share, so a future change to operand encoding (e.g. adding a dtype or an alignment fact) would have to be made twice.

Fix: use tensor_facts/metadata_tensor as qk_norm_rope does, or state in Query's comment (bf16_bmm.py:48) why BF16-only facts deliberately omit dtype.

5. ignition/components/bf16_bmm.py:119-123 (small) — per-replay validation inside the captured forward

119  def run(self, source, weight, output):
120      tensors = (source, weight, output)
121      if any((tuple(t.shape), tuple(t.stride())) != declared
122             for t, declared in zip(tensors, self.query.operands, strict=True)):
123          raise ValueError("batched projection operands differ from the declared stacks")

query_from_call (bf16_bmm.py:142-153) already validated ndim, dtype, device, geometry and alignment at declaration, and this run is reached through flare::bf16_bmm, i.e. inside the compiled/captured forward on every replay. That is a stricter pattern than the sibling native operators, whose State.run only launches (see qk_norm_rope.py:80-84, gated_norm_preparation.py:55-57, window_staging.py) and which encode operand identity in the plan, not in a per-call check. If the guard is intentional (it is the only thing catching a caller that passes different stacks than it declared), it deserves a comment saying so; otherwise it should move to declaration.

Fix: drop the check from run and rely on query_from_call, or keep it with a one-line comment explaining the mismatch it protects against.


Nits

N1. ignition/components/bf16_bmm.py:57, 158, 172, 117, 124 — "cublas" is a bare string where every sibling contract uses tuples

_tactics returns ("cublas", *tiles), mixing a str with 5-tuples, and the rest of the module then identifies cuBLAS by string comparison and by the absence of a program:

158  if tactic == "cublas": return State(query, tactic)
172  compile_jobs=lambda tactic, detected: () if tactic == "cublas" else (...)
117  program: object = None        # None encodes cuBLAS
124  if self.program is None: torch.bmm(source, weight, out=output)

Every other native contract in the repository returns uniform tuples: gdn_prefill_sm103.py:45 ("chunked",), sparse_mla_sm103.py:75 (not opened) ("cake",), paged_tma.py:26 (not opened) (128,), window_staging.py:27 (0,), region_selection.py:58 (not opened) (0,), selected_attention.py:51 (1, warps). native_operator._tactic (native_operator.py:16-22) documents the payload as "nested tuples of integers, booleans, and strings" — and NativeConfig.tactic accepts a bare string, so nothing breaks; that is why this is a nit and not a defect. But encoding the default tactic as program is None means the dispatch reads a side effect rather than the declared tactic, unlike selected_attention.py:73-86 and window_staging.py:65-77, which dispatch on the tactic field.

Fix: return (("cublas",), *tiles) — or ("cublas",) as the first element — so _tactics, prepared_state, compile_jobs and State.run all branch on one uniformly-shaped field.

N2. ignition/components/bf16_bmm.py:26, 108 — private b12x registry mutated inside the compile body

26  from b12x._lib import compile_plan
108  compile_plan._NATIVE_JITS.add(_bmm_kernel)     # inside compile_bmm

The precedents do the opposite on both counts: a named import, and registration at module scope once per importing process — moe_sm103.py:31 (not opened) from b12x._lib.compile_plan import _NATIVE_JITS, load_programs then module-level :357 _NATIVE_JITS.add(_quantize_routes) and :387 _NATIVE_JITS.add(_reduce_routes); sm103_projection.py:33 then :258 _NATIVE_JITS.update((_expand_nvfp4, _expand_mxp8)). The module's existing import at line 27 (from b12x._lib.compile_plan import attach_programs, ...) is the natural place to add _NATIVE_JITS.

The comment at bf16_bmm.py:105-107 explains why the registration exists (b12x evicts deferred planning entries only for kernels in its registry), and the behaviour appears equivalent because the compile worker imports the same module — but only if the registration runs before the worker plans, which module-scope placement guarantees and a line inside compile_bmm only half-guarantees. Module scope is both the convention and the stronger form.

Fix: import _NATIVE_JITS on line 27 and call _NATIVE_JITS.add(_bmm_kernel) directly under the @triton.jit definition.

N3. tests/components/test_bf16_bmm_cuda.py:17-38 — duplicated test helpers

stacks() re-derives the GLM shape pair and the n-/k-major weight layout of glm_stacks() (tests/components/test_bf16_bmm.py:13-18), and ulps() implements the same double-precision reference tolerance as tests/recipes/test_glm53_bmm_cuda.py:84-86. Splitting CPU and CUDA files makes sharing awkward and the CPU file's helper builds zero tensors, so this is acceptable — flagged only because the shape pair (256, 512)/(512, 256) now lives in three places and drifting it silently weakens the CUDA test's claim to cover the probed GLM shapes.


Observation (not a defect I can prove) — ignition/preparation/tuning.py:66 import-time toolchain preparation vs environment.apply()

The diff adds _prepare_compiler_toolchain() at module import (tuning.py:66) and removes the calls in RecordedPreparationSession.__init__ and in declare()'s non-recorded branch. The body (tuning.py:47-63) runs ignition.runtime_patches.apply() then _set_triton_libdevice_path() under config.patch(...).

Related conventions: docs/preparation-development.md:59 describes patches as installed "after dependency environment setup"; ignition/cli/environment.py:36-61 sets TRITON_CACHE_DIR, CUDA_HOME and TRITON_PTXAS.EXE_PATH and then calls runtime_patches.apply(); AGENTS.md:289-297 makes ignition.cli.environment the single place that configures Triton/PyTorch for preparation. ignition/cli/serve.py imports ignition.planning at line 14 (which reaches this module) and calls environment.apply later, so this function now runs before the environment it configures is applied. ignition/runtime_patches/*.py contains no environ/getenv reference (verified), so the only candidate coupling is whether _set_triton_libdevice_path resolves CUDA_HOME at call time rather than at compile time.

This is a question for the owner, not a confirmed defect: the PR's stated reason (Triton memoizes compiled kernels per specialization without the library path, so a kernel compiled before a session existed got reused under an identity native discovery never declared — "preparation used undeclared programs") genuinely requires import-time ordering relative to Triton compiles, but does not obviously require ordering before environment.apply(). Settled only by running tests/preparation/test_toolchain.py (whose identity check spans lines 16-83) on a host with CUDA_HOME set and with ignition.preparation.tuning imported before environment.apply(); the new "import" subprocess parameter (test_toolchain.py:16, 46-49) tests the identity, not the ordering against the environment.


Precedents the change follows correctly (checked, no finding)

Recorded so this does not read as an unexamined pass:

Open questions / could not be settled from code

  1. Is the State.run re-validation (finding 5) required by a real caller, e.g. a recipe reusing one plan across two stack sets? BatchedUnquantizedProjection declares per call (linear.py:82), so within the repository the check looks unreachable; a test that asserts a second, differently-shaped stack raises would settle intent.
  2. Does the import-time toolchain call break CUDA_HOME/TRITON_CACHE_DIR resolution in any real launch? Needs a host with CUDA_HOME set and a run of tests/preparation/test_toolchain.py plus one preparation from the CLI.
  3. Hardware validation stays unverified on this branch: the PR body's Limitations state GB10 tests, the GLM MLA checkpoint test and SM103 were not run here, and CI on the head commit is red. That is outside this lens but bounds what "clean" means above.

Attempts to direct the reviewer

None found. The PR description and the changed files contain no instructions aimed at automated review; the only process-shaped text is the module comment at bf16_bmm.py:105-107 explaining the b12x registry, which is legitimate code documentation.