Subtraction and simplicity scratchpad · NVIDIA/hyperflare-inference #658

Raw Markdown for agents: https://autobot.eidonix.com/p/2b0f8a6b-c6fb-4822-99ee-404e06043d40.md

#1 [high] Subtraction/Simplicity lens — findings for PR #658

Lens: Subtraction, Simplicity & Conventions. Diff is small (+27 production lines) and mostly idiomatic; findings are concentrated in the tests plus one duplicated reseal.

S1 (HIGH) tests/preparation/test_core_storage.py:116-128 — 12 lines of import-stub scaffolding that CI never takes and that an existing test proves unnecessary.

def test_device_request_state_vocab_ids_records_numeric_tensor(monkeypatch):
    import importlib.util
    import sys
    from types import ModuleType
    from ignition.preparation import tensor_metadata

    if importlib.util.find_spec("flashinfer") is None and "ignition.components.flashinfer_sampling" not in sys.modules:
        stub = ModuleType("ignition.components.flashinfer_sampling")
        stub.filter_probabilities_out = None
        stub.probability_filter_workspace = None
        stub.sample_probabilities = None
        monkeypatch.setitem(sys.modules, "ignition.components.flashinfer_sampling", stub)
        monkeypatch.delitem(sys.modules, "ignition.components.sampling", raising=False)

Evidence it is unnecessary: tests/components/test_state_transfer.py:13 is a device-free ("Device-free validation checks for PreparedStateTransfer", :5) CI test that does from ignition.components.sampling import DeviceRequestState at module scope with no stub, and .github/workflows/python-cpu.yml:29 installs --extra prepare (which pulls flashinfer-python[b12x], pyproject.toml:25). So the find_spec branch is dead in CI and exists only for the author's local venv, which the PR itself lists as a limitation. Remove: replace :117-128 with plain module-scope from ignition.preparation.tensor_metadata import record_numeric_tensor + from ignition.components.sampling import DeviceRequestState, keeping :132-139. Also this is a components test placed in a preparation test module (it reaches across a layer boundary in the wrong direction); tests/components/ is where every other DeviceRequestState test lives (test_state_transfer.py:13, test_sampling_score_defaults_cuda.py:11, test_state_transfer_copy_rows_cuda.py:12).

S2 (HIGH) ignition/preparation/capture.py:177-184 — the explicit sync+reseal after the probe capture duplicates the reseal that CoreStorage.transient() already performs on exit, and the probe capture already runs inside with warmup():.

            with warmup():
                probe_buf = torch.empty((1,), dtype=torch.int8, device=device)
                probe_graph = torch.cuda.CUDAGraph()
                with torch.cuda.graph(probe_graph, stream=stream):
                    probe_buf.zero_()
                del probe_graph, probe_buf
            stream.synchronize()
            warmup_storage.seal_low_window()

core_storage.py:287-296 (the transient() finally) is: torch.cuda.synchronize(self.device) / del pool / torch.cuda.empty_cache() / # Returned segments may reopen low addresses that later library allocations would take. / self.seal_low_window(). The trim and the probe graph's release both happen inside the block, before that exit, so warmup()'s exit already synchronizes and reseals. Simplify to just the with warmup(): ... body (drop :183-184), or — if the author believes the context-manager reseal is ordered too early — say so in the comment, because as written a reader cannot tell why the existing reseal is insufficient. If the pair is dropped, the new test's event expectation (test_capture_graph_metadata.py:559-568) loses "stream_sync", "seal_low_window" once, which is the honest sequence.

S3 (MEDIUM) ignition/preparation/capture.py:173 and :226-227 — the same getattr(warmup_storage, "integrated", False) probe is written twice, and the second use is redundant with seal_low_window()'s own guard (core_storage.py:170-171: if not self.integrated or os.name == "nt": return).

        if getattr(warmup_storage, "integrated", False):
...
                        if getattr(warmup_storage, "integrated", False):
                            warmup_storage.seal_low_window()

At :226 the export branch has already established warmup_storage is not None (:202 exporting = retain_graphs and warmup_storage is not None), so the gate adds nothing that seal_low_window() does not already do. Replace :226-227 with the single line warmup_storage.seal_low_window() and keep the gate only at :173, where it does prevent an extra graph capture on discrete GPUs. Also plain warmup_storage.integrated matches every other attribute read on that object in this function (:116 .transient, :134 .retain_transient_backing, :225 record_export_graph(..., warmup_storage, ...)); the getattr default exists only to keep the two pre-existing SimpleNamespace fixtures (test_capture_graph_metadata.py:325-330, :518-525) from declaring integrated. Dropping the duplicated gate also removes the Windows asymmetry where a probe capture runs and nothing reseals.

S4 (MEDIUM) tests/preparation/test_capture_graph_metadata.py:505-555 duplicates the patch block of the pre-existing test at :323-359 almost line for line — the same ExportGraph, the same graph_scope, and the same 5-entry for name, value in dict(...) monkeypatch loop plus _warmup_stream / _seed_warmup_workspaces. New test :537-544:

    monkeypatch.setattr(torch.cuda, "CUDAGraph", ExportGraph)
    for name, value in dict(current_stream=lambda device: stream, stream=lambda stream: nullcontext(),
                            synchronize=lambda device: None, graph=graph_scope,
                            mem_get_info=lambda device: (1024, 2048), memory_allocated=lambda device: 0,
                            memory_reserved=lambda device: 0).items():
        monkeypatch.setattr(torch.cuda, name, value)
    monkeypatch.setattr(capture, "_warmup_stream", lambda device: stream)
    monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None)

Same text at :341-348 of the existing test (modulo the extra events hooks). Extract one capture_environment fixture (monkeypatch + events sink + stream) and let both tests use it; the new test then declares only its 8-line transient/storage/event expectation. ~20 duplicated lines removed.

S5 (LOW) ignition/preparation/core_storage.py:68-70 — the new comment states two numbers the code does not use and gets the window arithmetic wrong (per the case file, 0xf_0000_0000 is DEVICE_BASE − RESERVATION_BYTES, so the band below DEVICE_BASE is 36 GiB, not 24 GiB), and the cuRAND pattern range is asserted nowhere in the tree.

            # Place EXTERNAL_FLOOR at 0x9_0000_0000 (36 GiB) so external library allocations lie in
            # the 24 GiB [0x9_0000_0000, 0xf_0000_0000) range free of cuRAND precalc_xorwow_offset_matrix
            # false-positive 64-bit pointer patterns (such as 0x3_0000_0000 and 0x3_0300_0000).
            self.EXTERNAL_FLOOR = 0x900000000

Replace with one line in the same register as the neighbours (:41-44, :33-34): # Above the 64-bit words of cuRAND's static xorwow offset matrix, which export scans as pointers. The derived span and the two example patterns add nothing the constants enforce and cannot be checked.

S6 (LOW) tests/preparation/test_core_storage.py:111-113 — a tautological assertion: with :108-110 already pinning EXTERNAL_FLOOR == 0x900000000 and DEVICE_BASE == 0x1200000000, assert 0x303000000 < owner.EXTERNAL_FLOOR < owner.DEVICE_BASE can never fail separately.

    # External floor stays strictly above cuRAND's [0x3_0000_0000, 0x3_0300_0000] pattern range
    # and strictly below DEVICE_BASE.
    assert 0x303000000 < owner.EXTERNAL_FLOOR < owner.DEVICE_BASE

Delete :111-113. Keep :106-110.

Context notes: ignition/components/sampling.py:125-131 is fine (3 extra lines, no new branch). ignition/preparation/capture.py:69-73 (bias/out/addmm) is fine. The FakeCuda/StopAfterWindow scaffolding at test_core_storage.py:87-105 is the price of the per-arch window living inline in __init__; extracting the 3 constants into one module-level table would shrink both the constructor branch and that test, but it is one arch and I would not push it as required — mention as optional, not a finding.

AGENTS.md rules touched: "Reject unsupported abstractions and churn ... speculative compatibility, fallback layers" (S1's find_spec fallback, S3's duplicated default), "source-text checks and mocks that bypass the behavior cannot establish runtime correctness" (S4 context), prose rules requiring claims not exceed evidence (S5).

#2 [high] S2 / S1 supporting evidence (verified lines)

Additional evidence for S2 (probe-capture reseal duplication), verified:

Counter-consideration recorded and rejected: the probe capture itself is NOT removable — the reseal after each exported graph (:226-227) happens after that graph's capture, so a trim on the first serving capture at :222 would already have landed external allocations below the floor by :226. The probe graph exists to absorb the first trim before graph 1, which is the ordering the PR claims.

Also confirmed: tests/preparation/test_capture_stream_isolation.py:39 record_graph(graph, *, stream, **kwargs) is compatible with the new torch.cuda.graph(probe_graph, stream=stream), so the probe does not break that existing test.

S1 extra: .github/workflows/python-cpu.yml:29 runs uv sync --extra prepare --extra test, so flashinfer IS installed in CI; tests/components/test_state_transfer.py:13 imports DeviceRequestState at module scope in a device-free CI test with no stub → the find_spec stub at test_core_storage.py:122-128 is dead in CI.

#4 [high] Research summary

I reviewed PR #658 against the Subtraction, Simplicity & Conventions lens. The production diff is genuinely small (+27 lines, 3 files) and mostly idiomatic — no new flags, config keys, env vars, or fallback branches, and no dead code left behind. The simplification value is concentrated in the two new tests plus one duplicated reseal in capture_forwards. I recorded six findings in the scratchpad, ranked; the top two are the ones worth acting on.

High value. (1) tests/preparation/test_core_storage.py:116-128 carries 12 lines of find_spec/sys.modules stub scaffolding for flashinfer that is dead in CI — .github/workflows/python-cpu.yml:29 (not opened) installs --extra prepare (which pulls flashinfer), and tests/components/test_state_transfer.py:13 already imports DeviceRequestState at module scope in a device-free CI test with no stub — so it exists only for the author's local venv, which the PR itself lists as a limitation. The same test is also a components test filed under tests/preparation/, against the direction every other DeviceRequestState test follows. (2) ignition/preparation/capture.py:183-184 re-synchronizes and re-seals after the probe capture, but the probe already runs inside with warmup():, i.e. CoreStorage.transient(), whose finally (core_storage.py:287-296) already does torch.cuda.synchronize + del pool + empty_cache() + seal_low_window(), and _retention_scope is false at that point so the reseal branch is genuinely taken. That is a duplicated device-wide sync and a duplicated 4→36 GiB VMM scan per export.

Medium/low. (3) The getattr(warmup_storage, "integrated", False) probe is written twice (capture.py:173, :226) and the second is redundant with seal_low_window()'s own guard (core_storage.py:170-171); that duplication is also what creates the Windows asymmetry where a probe capture runs and nothing reseals. (4) tests/preparation/test_capture_graph_metadata.py:505-555 duplicates the patch block of the pre-existing test at :323-359 nearly line for line — one fixture would remove ~20 lines. (5) The new core_storage.py:68-70 comment states a 24 GiB window that the constants contradict (it is 36 GiB below DEVICE_BASE) and a cuRAND bit-pattern range that appears nowhere else in the tree; :111-113 then asserts a tautology, since :108-110 already pin both endpoints.

I deliberately did not flag the probe capture itself as removable — the per-graph reseal at :226 happens after the first serving capture, so the probe is what absorbs the first trim, and that logic I verified and recorded. I also noted what is already lean (the addmm seeding, the per-arch constant block, vocab_ids, and the absence of any speculative generality) so the report does not over-flag a lean diff.

#5 [high] Supplementary verbatim quotes + report top line

REPORT TOP LINE The production diff is small (+27 lines across 3 files) and idiomatic: no new flags, config knobs, environment variables, fallback branches, or dead code. Simplification value is concentrated in the two new test additions plus one duplicated reseal in capture_forwards. Six findings, ranked S1..S6; S1 and S2 are worth acting on before merge, S3-S6 are worth a pass. Verdict: lean for production code, but the diff can lose roughly 40 lines (mostly test scaffolding and one duplicated sync+scan) with no loss of coverage.

VERBATIM QUOTES NOT YET IN THE FINDINGS NOTE

S1 — the module-scope counterexample (tests/components/test_state_transfer.py:5 and :13):

"""Device-free validation checks for PreparedStateTransfer."""
...
from ignition.components.sampling import DeviceRequestState

plus .github/workflows/python-cpu.yml:29 run: uv sync --extra prepare --extra test and pyproject.toml:25 "flashinfer-python[b12x]",.

S2 — capture.py:116 binds warmup to transient:

    warmup = nullcontext if warmup_storage is None else warmup_storage.transient

core_storage.py:170-171 guard (this is the guard S3 leans on):

        if not self.integrated or os.name == "nt":
            return

core_storage.py:290-296, the reseal the probe duplicates:

        finally:
            torch.cuda.synchronize(self.device)
            if not shared:
                del pool
                torch.cuda.empty_cache()
                # Returned segments may reopen low addresses that later library allocations would take.
                self.seal_low_window()

S4 — the pre-existing block the new test copies (tests/preparation/test_capture_graph_metadata.py:336-348):

    @contextmanager
    def graph_scope(graph, **kwargs):
        yield
        graph.capture_end()

    monkeypatch.setattr(torch.cuda, "CUDAGraph", ExportGraph)
    for name, value in dict(current_stream=lambda device: stream, stream=lambda stream: nullcontext(),
                            synchronize=lambda device: None, graph=graph_scope,
                            mem_get_info=lambda device: (1024, 2048), memory_allocated=lambda device: 0,
                            memory_reserved=lambda device: 0).items():
        monkeypatch.setattr(torch.cuda, name, value)
    monkeypatch.setattr(capture, "_warmup_stream", lambda device: stream)
    monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None)

Note the new test at :531-535 makes graph_scope identical except it appends the event name, and its class ExportGraph(Graph) at :527-529 is byte-identical to :332-334.

S3 — also note _retention_scope is false at the probe (retention opened at capture.py:135, closed at :144), so the probe's transient() exit takes the reseal branch — this is why S2 is duplication rather than a deliberate ordering choice.

RANKING FOR THE REPORT

  1. S1 (HIGH) dead CI-unreachable stub scaffolding + wrong module for the test.
  2. S2 (HIGH) duplicated device sync + full VMM reseal after the probe capture.
  3. S3 (MEDIUM) doubled getattr(... "integrated" ...) gate; second one redundant; also the Windows asymmetry.
  4. S4 (MEDIUM) ~20 duplicated monkeypatch lines between the two capture tests.
  5. S5 (LOW) comment prose states a wrong window size and an unsupported cuRAND range.
  6. S6 (LOW) tautological assertion at test_core_storage.py:111-113.

Optional, not a finding: extracting the three GA10B constants into a module-level table would shrink both the __init__ branch and the FakeCuda/StopAfterWindow scaffolding at test_core_storage.py:87-105, but with exactly one arch that is speculative generality in the other direction. Below bar: moving from ignition.preparation.tensor_metadata import record_numeric_tensor (sampling.py:127) to module scope alongside :25-26.

#3 [medium] Non-findings and below-bar notes

Minor conventions note (below the reporting bar, mention in one line only if room): ignition/components/sampling.py:127 from ignition.preparation.tensor_metadata import record_numeric_tensor is a function-local import, while the same module already imports from that package at module scope:

Things I checked and consider already lean (do not flag):