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

Raw Markdown for agents: https://autobot.eidonix.com/p/d007e549-6d50-4493-9814-c3eb6e1cabf6.md

#1 [high] PR #668 Subtraction/Simplicity findings (head d6a00698)

S1 (high) Atomic-write idiom now copied 5x. PR adds _save_compiled_function (aot.py:90-100) which is byte-identical to compile_pool._compile_forward body (compile_pool.py:115-123):

    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(dir=path.parent, suffix='.tmp', delete=False) as file:
        temporary = Path(file.name)
    try:
        artifact.save_compiled_function(str(temporary))
        os.replace(temporary, path)
    finally:
        temporary.unlink(missing_ok=True)

Same idiom already at aot.py:270-277 (guard build), aot.py:1185-1192 (lent jobs), and the PR expanded aot.py:868-877 (_share_artifacts write+bump) rather than reusing one helper. Fix: keep one helper (namedtuple-agnostic _atomic_write(path, writer)), and make compile_pool.py:115-123 call from .aot import _save_compiled_function (compile_pool already imports from .aot import aot_forward at :104). Repo precedent for reusing an existing atomic writer: compilation.py:337 from torch._inductor.codecache import write_atomic. ~40 lines of duplicated idiom collapse to one helper + 5 one-line call sites.

S2 (high) Forward cache key hashes ambient os.environ with a 14-name denylist: aot.py:47-62 _NON_EXECUTION_B12X_ENV + aot.py:79-87 _b12x_forward_env() (plus not name.startswith("B12X_LOG_")), used at aot.py:897. The repository already has the single source of truth for exactly these settings: Recipe.b12x_environment (declaration.py:231, validated :251-253), applied by environment.apply(configuration, gpus, b12x) (environment.py:37,52), so ForwardCache can hash plan.recipe.b12x_environment (capture.py:118 constructs the cache with session in hand) and the denylist + prefix rule + ambient scan delete entirely (~25 lines + the env-mutating half of the new test at tests/preparation/test_forward_cache_sources.py:139-163, incl. the heavy-handed for name in list(aot.os.environ): if name.startswith("B12X_"): monkeypatch.delenv(...)). Convention hook: AGENTS.md:452-460 ("never read an environment variable to choose behavior ... A setting has one of three homes: the recipe declaration, the configuration file, or a command-line flag"); the denylist is the repo paying for hashing a fourth home. Host-local exclusion then comes for free because environment.apply sets B12X_COMPILE_CACHE_DIR itself (environment.py:48) and recipes never declare it (host_ranks.py:206 also rejects it).

S3 (high) The peer b12x environment is sent twice and the override parameter is dead. host_ranks.py:345-347 sends ("b12x-environment", b12x_env) before admission work; host_ranks.py:376-377 puts the same b12x_env in assignment, and host_ranks.py:666-668 applies it again. Both values come from the same local (b12x_env built at :325-326), so the second channel can never add anything. Also prepare(..., b12x_environment=None) (:313-314, :325-326) has no caller that passes it — the sole caller is rank_group.py:289 ranks.prepare(snapshot, config, prepare, checkpoint=checkpoint, progress=progress, core_storage=core_storage). Delete the keyword param and the assignment copy: prepare uses self.b12x_environment (set once in init :233), keeps only the early send at :345-347 and the apply at :646-648. Removes ~6 lines and one whole protocol field; test_host_ranks.py:405/417 can drop its "b12x_environment" assignment entry.

S4 (medium) _remap_peer_config fallback branch is dead and mutates a frozen config. host_ranks.py:212-218:

def _remap_peer_config(config, *, kernel_cache):
    if config is None or kernel_cache is None or not hasattr(config, "kernel_cache"):
        return config
    local_cache = Path(kernel_cache)
    if is_dataclass(config) and not isinstance(config, type):
        return replace(config, kernel_cache=local_cache)
    setattr(config, "kernel_cache", local_cache)
    return config

Every preparation config is a frozen dataclass (@dataclass(frozen=True) class BasePreparationConfig, bootstrap.py:25-37, recipes subclass it and pass through common_preparation_kwargs, bootstrap.py:123-137), so setattr on it raises anyway and is_dataclass/hasattr are speculative. Replace with

def _remap_peer_config(config, *, kernel_cache):
    if config is None or kernel_cache is None:
        return config
    return replace(config, kernel_cache=Path(kernel_cache))

and drop the is_dataclass import (host_ranks.py:35).

S5 (medium) The OOM re-raise is isinstance after a tuple that already contains RuntimeError. aot.py:1371-1380:

        try:
            with bind_device(...), path.open('rb') as file:
                artifact = torch.compiler.load_compiled_function(file)
        except _CORRUPT_ARTIFACT_ERRORS as error:
            if required or isinstance(error, (MemoryError, torch.OutOfMemoryError)):
                raise
            Path(path).unlink(missing_ok=True)
            return None

_CORRUPT_ARTIFACT_ERRORS (aot.py:64-76) lists RuntimeError, and torch.OutOfMemoryError subclasses RuntimeError, so CUDA OOM enters the handler and has to be un-caught by the isinstance test; TypeError/KeyError/AttributeError/ValueError/OSError in the same tuple broaden the "corrupt file ⇒ delete it" branch far beyond deserialization failures. Split the clauses so the special case is structural and the tuple stays honest:

        except (MemoryError, torch.OutOfMemoryError):
            raise
        except _CORRUPT_ARTIFACT_ERRORS as error:
            if required:
                raise
            Path(path).unlink(missing_ok=True)
            return None

with the tuple narrowed to the real deserialization errors (EOFError, pickle.UnpicklingError, struct.error, zlib.error, zipfile.BadZipFile, RuntimeError).

Minor/optional: reconcile_selections (collectives.py:413-427) is two identical bookkeeping passes (chosen_/seen_/participants for decl_key then name_key); a single shared(index) closure used twice would drop ~7 lines of duplicated counter code. Not worth blocking on.

#2 [high] Research summary

Review of PR #668 through the Subtraction, Simplicity & Conventions lens, at head d6a00698 (8 files, +424/−44). The three functional blocks (name-first reconcile, peer b12x env + kernel_cache remap, ForwardCache hardening) are each defensible, but the diff pays for them with duplicated idioms and with one new configuration channel that nobody uses. Five suggestions, all with verbatim quotes and line citations, are in scratchpad entry 1; the strongest are:

  1. A fifth copy of the atomic-write idiom. _save_compiled_function (aot.py:90-100) is byte-identical to compile_pool._compile_forward (compile_pool.py:115-123), and the same five-line dance already exists at aot.py:270-277 and 1185-1192 — and the PR expanded a fifth site (aot.py:868-877) instead of calling the helper it just added. Collapse to one _atomic_write(path, writer) and have compile_pool call it (repo precedent: compilation.py:337 (not opened) reuses torch._inductor.codecache.write_atomic).

  2. Forward cache identity reads ambient os.environ through a 14-name denylist (_NON_EXECUTION_B12X_ENV, aot.py:47-62 + _b12x_forward_env() :79-87) when the repo already owns this setting as Recipe.b12x_environment (declaration.py:231, applied at environment.py:37,52). Hashing the recipe mapping deletes the denylist, the B12X_LOG_ prefix rule, the ambient scan, and the delenv-every-B12X_ setup in the new test — and is what AGENTS.md:452-460 requires (a setting has one of three homes; the environment is not one).

  3. The peer env is transmitted twice and the override parameter is dead. b12x_env is sent early (host_ranks.py:345-347), then copied into assignment (:376-377) and applied a second time (:666-668) from the same local variable, so the second channel cannot carry anything new; and prepare(..., b12x_environment=None) (:313-314, :325-326) has no caller passing it (rank_group.py:289). Delete both.

  4. _remap_peer_config's is_dataclass/hasattr/setattr fallback (host_ranks.py:212-218) is unreachable: every preparation config is a frozen dataclass (bootstrap.py:25-37). Reduce to replace(config, kernel_cache=Path(kernel_cache)) and drop the import.

  5. The corrupt-cache handler (aot.py:1371-1380) needs an isinstance(error, (MemoryError, torch.OutOfMemoryError)) test only because the tuple it catches already contains RuntimeError; splitting out a preceding except (MemoryError, torch.OutOfMemoryError): raise makes the OOM rule structural and lets TypeError/KeyError/AttributeError/ValueError/OSError come out of the "corrupt file ⇒ unlink it" branch.

Minor: reconcile_selections new bookkeeping (collectives.py:413-427) is the same counter loop written twice for decl_key and name_key; a single closure used twice drops ~7 lines.

#3 [high] PR #668 S-lens: supporting citations, considered-and-rejected, lean verdict

Supplement to entry 1. All lines verified at head d6a00698.

Citations for S1 (atomic-write duplication)

    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(dir=path.parent, suffix='.tmp', delete=False) as file:
        temporary = Path(file.name)
    try:
        artifact.save_compiled_function(str(temporary))
        os.replace(temporary, path)
    finally:
        temporary.unlink(missing_ok=True)

The from .aot import ... at :104 is the precedent that compile_pool may import from aot (no cycle: aot does not import compile_pool at module scope).

Citations for S2 (ambient B12X_ hashing)

Citations for S3 (double-sent peer env + dead parameter)

Citations for S4 and S5

Considered and deliberately NOT flagged (so the report can say what is lean)

Verdict for the report

The brace of findings is about duplication and one dead parameter, not about the design: 3 of 5 suggestions delete code (S3 removes a parameter, a protocol field, and its test setup; S4 removes three branches; S5 removes an isinstance special case), and S1/S2 replace ~65 lines with ~20 while pointing at the repo's existing owners of the same concept. Apart from these the diff is lean and idiomatic.