Subtraction & Simplicity audit — PR #728
Scope reviewed: all 24 declared files, with full reads of the Python production hunks (source_identity.py, aot.py, inductor_tuning.py, capture.py, core_storage.py, compile_pool.py, forward_metadata.py, rebuild_manifest.py) and the Rust hunks (reachability.rs, binding.rs, capture.rs, source_identity.rs, build.rs). Note on tooling: the local main ref is stale, so pr_diff mixes in already-merged upstream work (seal_low_window, HostVmmRegion/EXTERNAL_FLOOR, _SMALL_INTEGRATED_*, _b12x_forward_env/_atomic_write_file/_save_compiled_function, validate_external_extents, async_transfers — confirmed absent on main in results 24/32). I excluded all of that from the findings below; every citation is real #728 content.
The diff is not lean. Below are the concrete subtractions, ordered by value.
1. Delete _seed_auxiliary_workspaces's duplicate seed body — it re-implements _seed_warmup_workspaces (HIGH)
ignition/preparation/capture.py:53-79 and :82-107 are the same 6-line cuBLAS seed sequence, copy-pasted:
# :74-78 (_seed_warmup_workspaces)
operand = torch.empty((512, 512), dtype=torch.bfloat16, device=device)
bias = torch.empty((512,), dtype=torch.bfloat16, device=device)
out = torch.empty_like(operand)
torch.mm(operand, operand, out=out)
torch.addmm(bias, operand, operand, out=out)
# :100-106 (_seed_auxiliary_workspaces)
operand = torch.empty((512, 512), dtype=torch.bfloat16, device=device)
bias = torch.empty((512,), dtype=torch.bfloat16, device=device)
out = torch.empty_like(operand)
torch.mm(operand, operand, out=out)
torch.addmm(bias, operand, operand, out=out)
batched = operand.view(1, 512, 512)
torch.bmm(batched, batched, out=out.view(1, 512, 512))
The only differences are the stream and the bmm. One helper serves both:
def _seed_blas_workspaces(stream, device, pool=None, *, batched=False):
... # existing body, with `if batched: torch.bmm(...)` appended
with _seed_warmup_workspaces reduced to a thin alias, or better, call _seed_warmup_workspaces(aux, device, pool=graph_pool) from the auxiliary path and drive batched from a parameter. That removes ~20 lines and, more importantly, removes the drift hazard: the sizes (512), dtypes and op list must now be kept in sync by hand in two places.
2. _seed_warmup_workspaces's new pool=None default creates an unreachable-in-export branch that exists only for a test (HIGH)
ignition/preparation/core_storage.py:309-318 adds CoreStorage.warmup_pool(). ignition/preparation/capture.py:151-157 then does:
warmup_pool = warmup_storage.warmup_pool() if hasattr(warmup_storage, "warmup_pool") else None
if warmup_pool is not None:
_seed_warmup_workspaces(warm, device, warmup_pool)
else:
# Keep the 2-argument call for non-export callers and existing test stubs.
_seed_warmup_workspaces(warm, device)
Three branches (hasattr, is not None, else) to express "pass a pool if the storage has one". The else comment states its own justification: existing test stubs. Note the fallback also doesn't work as intended — the four test doubles monkeypatch _seed_warmup_workspaces with a 2-argument lambda (tests/preparation/test_capture_graph_metadata.py:185 (not opened),342, test_capture_roce_wait.py:43 (not opened), test_capture_stream_isolation.py:44: lambda stream, device: None), so the 3-argument call at :153 raises TypeError whenever warmup_storage is a real CoreStorage in those tests. The compatibility branch is dead for the stubs it claims to serve.
Simplification: make the pool a required argument on _seed_warmup_workspaces, have capture_forwards do pool = warmup_storage.warmup_pool() if warmup_storage is not None else _module_pool(device), and update the four stub lambdas to *_. Deletes hasattr probing, the None re-fetch at :70, and the misleading comment.
3. _seed_warmup_workspaces's module-level fallback is now double-keyed and does nothing new (MEDIUM)
capture.py:67-72 inside an existing with torch.cuda.device(device)::
index = torch.cuda.current_device()
if pool is None:
pool = _warmup_pools.get(index)
if pool is None:
pool = _warmup_pools[index] = torch.cuda.MemPool()
This is exactly the pre-PR two-line _warmup_pools.get / setdefault behaviour re-wrapped in a redundant if pool is None: guard on an already-None pool. _warmup_pools is not reset by anything in production; warmup_storage.warmup_pool() memoizes in _warmup_pool (core_storage.py:313-317). So the module dict is now a third memoization tier for a path only non-export callers take. Collapse to:
if pool is None:
pool = _warmup_pools.setdefault(index, torch.cuda.MemPool())
4. prepared_module_roots() is a second, divergent source-root enumerator; it should read _EXTRA_ROOTS once (MEDIUM-HIGH)
ignition/preparation/source_identity.py:31-58 invents a fresh prefix list including a basename rule:
resolved_name = Path(path).name
if resolved_name and resolved_name != label:
candidates.append(resolved_name)
This is speculative generality with real cost: it widens "this module's state must be stripped" to any package whose directory happens to be named the same as a bound root (source_identity.py:37-39), it must re-validate identifiers (:43), it re-walks _EXTRA_ROOTS on every is_prepared_object_module() call — which is the hot path in _GuardPickler.reducer_override (aot.py:225) and rebuild_manifest.weight_views' recursive walk (rebuild_manifest.py:369) — and it duplicates the root-normalization already done in source_roots() (:23) and again in forward_source_identity (:127-130) and a fourth time in source_identity (:154). Nothing in the diff demonstrates a case where the label differs from the basename in a way the basename covers. Delete the basename branch and cache the tuple; four call sites then share one normalized root form instead of three slightly different ones.
5. _prune_static_compile_results has four exits and a require_single axis that is never used in the "many" mode productively (MEDIUM)
ignition/preparation/inductor_tuning.py:21-57. Call-site census (result 23/37): require_single=True at :71 (_selected), :108 (_snapshot), :366 via _sanitize_static_bundle(frozen=True), aot.py:128 via frozen=True; require_single=False only from aot.py:128 with frozen=frozen on the non-frozen peer-load path. So the function must express "return one" and "return many, pruning silently". That produces the awkward intermediate re-binding of both tuner.compile_results and the local results at :37-39, and a RuntimeError/TypeError split (:41 vs :53) that reports the same underlying condition (unusable compile results) under two classes with two message shapes.
Simplification: split into two named predicates — _static_results(tuner) (pure: prune-to-launcher + partition, no exceptions) and then:
_selected/_snapshot/freeze:result, = _static_results(tuner) or raise_load_inductornon-frozen: drop the mutation entirely and just assert.
Additionally, _sanitize_static_bundle (:60-65) is a two-line loop with an if bundle is None guard whose only effect for frozen=True is to raise; for frozen=False it mutates. Both callers already know which they are. Inlining it removes a helper and a parameter that encodes the caller's identity.
6. ForwardCache.__init__'s exclusion-splitting is a hand-rolled partition of two constants (MEDIUM)
ignition/preparation/aot.py:905-910:
excluded_dirs = [ignition_root / entry for entry in _COMMAND_SOURCES if not entry.endswith('.py')]
excluded_files = [
ignition_root / '__main__.py (not opened)',
*(ignition_root / entry for entry in _COMMAND_SOURCES if entry.endswith('.py')),
*(ignition_root / entry for entry in _PUBLICATION_SOURCES),
]
Two constants (aot.py:793,795) that already encode file-vs-directory by whether the name ends in .py, re-partitioned with an endswith('.py') test repeated twice, plus '__main__.py (not opened)' spliced in by literal. Because export_source_identity now takes both lists and concatenates them into one excluded vec anyway (heliopause/src/export/binding.rs:1154-1159: excluded.extend(files); source_identity.rs:43 tests one flat list), the split has no meaning at either end. Replace all three with one flat _CACHE_EXCLUDED_SOURCES = ('__main__.py (not opened)', 'cli', 'direct', 'errors.py (not opened)', 'planning.py (not opened)', 'progress.py (not opened)', 'preparation/model_core.py (not opened)', 'preparation/core_file.py (not opened)', 'preparation/protection.py (not opened)') and pass a single excluded_paths= argument — deleting the .py-sniffing, the second list, and the excluded_files parameter from the pyfunction signature.
7. unresolved_report's two-phase example selection is far more machinery than the stated goal (MEDIUM)
heliopause/src/export/reachability.rs:246-320. The requirement is "up to 10 examples, prefer distinct symbols". The implementation allocates examples: Vec<&(u64, UnresolvedEntry)>, chosen: vec![false; n], then a HashSet keyed by a hand-rolled Result<&str, usize> (:288-294):
let symbol_key = functions
.get(entry.first.function)
.map_or(Err(entry.first.function), |function| {
Ok(function.symbol.as_str())
});
then a second backfill pass over chosen, then selected.sort_unstable(), then a shown_occurrences accumulator justified only by the trailing "not shown" line. UNRESOLVED_EXAMPLES = 10 is a const used once. Since entries are already ordered by order (the encounter index) and unresolved is a HashMap<u64, _>, a BTreeMap<usize, (u64, &Entry)> keyed by order — or simply recording candidates in a Vec at insert time and keeping the HashMap only for occurrence counting — removes the sort, the chosen bitmap, and the order field entirely. This is the largest single block of removable Rust in the PR (~40 lines of selection logic → ~12) and it is pure diagnostic formatting, not correctness.
Related: unresolved_count() and unresolved_unique_addresses() (:230-239) are two public methods whose bodies are sum() and len(), called from exactly one production site (:248,258) plus tests. Inline them.
8. Site/Source plumbing threads a 4-field borrow into every scan for diagnostics only (LOW-MEDIUM)
reachability.rs:56-72 adds Site<'a>, and blob()/scan() gain a site/misses parameter pair threaded through three call sites (:205, :378, :443). scan()'s signature becomes:
fn scan(&mut self, data: &[u8], base: usize, mut misses: Option<&mut Vec<(usize, u64)>>)
where every non-kernel caller passes None (:443, :447). And blob() re-keys its memo HashSet into a HashMap<(Vec<u8>, Vec<(usize, usize)>), Vec<(usize, u64)>> (:85) so cached misses can be replayed at a new Site (:207-210) — i.e. the memo now returns positions in a blob which are then re-attributed. That's inherent to the feature, but Option<&mut Vec<...>> plus as_deref_mut() plus base + offset alignment is the most convoluted way to express it. A two-method split (scan_pointers for the reference-retaining path; scan_misses for the kernel path) would remove the Option and the base parameter from half the calls and let the alignment filter live in one place.
9. Dead/low-value knobs and duplicates elsewhere
heliopause/src/export/binding.rs:1146-1168:excluded_directoriesandexcluded_filesare concatenated unconditionally. Keeping two parameters on the#[pyfunction]signature buys nothing (see #6). Oneexcluded=parameter.heliopause/src/export/source_identity.rs:73-75:source_identity(roots)is now a one-line wrapper oversource_identity_excluding(roots, &[])whose only caller isbinding.rs:1160'sif excluded.is_empty()branch — a branch that also only exists to preserve the wrapper. Delete both, always callsource_identity_excluding.ignition/preparation/compile_pool.py:180:extra_roots = tuple((label, str(root)) for label, root in _EXTRA_ROOTS.get())— thestr()round-trip exists only becausesource_roots()(source_identity.py:23) doesPath(path)on the way back in. Pickle thePaths (they pickle fine) and drop both conversions.ignition/preparation/aot.py:925-928: theCompiledKernelcheck is placed after animportinside the hotreducer_override(from triton.compiler import CompiledKernelon every reduce) whileJITFunctionabove it is a module-level import used the same way. Hoist the import; theisinstancecheck then costs nothing.
What is genuinely lean (no action)
forward_metadata.py:40-44andrebuild_manifest.py:369: the two('ignition.', 'b12x.')tuples are deleted and replaced by one predicate. This is the PR's best subtraction — net −2 hardcoded package-name lists, and it lets_BASE_PREPARED_MODULE_ROOTS(source_identity.py:17) be the single source of truth.aot.py:284-287,:876-879,:1184-1187: three copies of theNamedTemporaryFile/os.replace/unlinkidiom collapsed into_atomic_write_file, andsave_compiled_functioncallers (:1318, :1461, :1470) onto_save_compiled_function. Genuine dedup (though, per the tooling caveat, that helper came from #668, not this PR).core_storage.py:309-318warmup_pool(): 10 lines, mirrors the existingtorch.cuda.MemPool(...)+_preparation_pools.add(...)pattern at:286-291and:305-306exactly. Correctly placed; no wrapper is needed beyond it.
Bottom line
Highest-value deletions, in order: (1) fold the duplicated cuBLAS seed body into one helper; (2) delete the hasattr/None/else triple and the pool=None compatibility default in _seed_warmup_workspaces (the test doubles it protects would raise TypeError anyway); (4) drop the source-root basename rule and re-derivation in prepared_module_roots(); (5) collapse _prune_static_compile_results' four exits and inline _sanitize_static_bundle; (6) replace the split excluded_directories/excluded_files partition with one flat list end-to-end; (7) replace unresolved_report's bitmap+sort+HashSet selection with an order-keyed Vec/BTreeMap. Together these remove roughly 120–160 lines and, more importantly, remove four places where the same fact (which files count as sources; which ops seed the workspace) is now stated twice and must be kept in sync by hand.