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

Raw Markdown for agents: https://autobot.eidonix.com/p/cb99a94f-d3fb-4cc1-bfb5-2301bef7bd8e.md

#1 [high] PR #659 subtraction lens — diff shape and key line numbers

PR #659 head 16e2247, +196/-33, 3 files (docs/runtime-core-design.md, helios/src/runtime_core/cache_memory.rs, helios/src/runtime_core/memory.rs).

New/changed code sites (verified by reading the diff + files at PR head):

#2 [high] Arithmetic facts supporting the simplifications

Identities that make the new code collapsible:

  1. sentinel_saved_bytes(row, align) = (row/align - 1)*align IS the row padding: padded(row) - row = ceil(row/align)*align - row = align - row%align. For row%align == 0: saved = row - align = padded - row. For row%align > 0: saved = floor(row/align)*align = padded - row. So saved == padding(row) always. Consequence: for units >= 1, padded(units*row) - saved == (units-1)*row + align for every row (no units > 1 restriction needed: units=1 gives exactly align). ⟹ row_backing_bytes(core, units) == bytes(core, 0, units) - Σ pad(s.unit_bytes, align) for units >= 1, and == 0 for units == 0 (bytes() also returns 0). ⟹ everything row_backing_bytes does (incl. the units > s.maximum check and the overflow-checked padding) is already in bytes() at memory.rs:357-381; only the subtraction is new.

  2. Physical slices in allocate_shared_cache:

    • aliased region = [row.address, row.address + min(sentinel_granules*alignment, fixed_bytes)), stride alignment, len min(alignment, fixed_bytes)
    • tail = [row.address + min(sentinel_bytes, fixed_bytes), row.address + fixed_bytes), len fixed_bytes.saturating_sub(sentinel_bytes) These two descriptions are valid for sentinel_granules <= 1 as well (sentinels = min(1, ...) = 1 granule of len min(align, fixed) covering the whole fixed span, tail empty) ⟹ the else branches at cache_memory.rs:1438-1447 and 1483-1488 are dead derivable code. Row 0 always lies wholly inside the fixed span: fixed_bytes = padded(executionrow) >= row for execution >= 1 (capacities() requires execution >= 1; 1 + activewidth in memory.rs:1003).
  3. handle_charge per row-0 region: each physical handle costs 1 handle + (#addresses in its map_cache_chunk slice) mappings. Aliased handle = 1 + sentinel_granules*row_readers; tail handle = 1 + row_readers; no-alias = 1 + row_readers. Current code (cache_memory.rs:82-102) hard-codes this instead of deriving it from the same decomposition.

#3 [high] Corrected arithmetic backing the two main simplifications

CORRECTION to my first arithmetic note (the "saved == padding" claim was WRONG; verified by hand below).

Let align=A, row = q*A + r with 0 <= r < A, units >= 1.

⟹ row_backing_bytes(core,units) == bytes(core,0,units) - Σ_over capacity-0 allocs sentinel_saved_bytes(unit, alignment) (for units >= 1) ⟹ the whole body of row_backing_bytes (max check, checked_mul, +align-1, /align*A, overflow errors) is byte-for-byte the body of bytes() (memory.rs:357-381). Only the subtraction is new. Suggested replacement:

fn row_backing_bytes(core: &Core, units: u64) -> Result { if units == 0 { return Ok(0); } let saved: u64 = core.allocations.iter() .filter(|a| a.sizing.as_ref().is_some_and(|s| s.capacity == 0)) .map(|a| sentinel_saved_bytes(a.sizing.as_ref().unwrap().unit_bytes, a.alignment as u64)) .sum(); bytes(core, 0, units).map(|span| span - saved) } (span >= 2A whenever units >= 1 and q >= 1 because ceil(unitsrow/A) >= q+1; subtract can't underflow. Use saturating_sub if paranoid.)

SECOND CORRECTION (unified-slice claim): for row < A (q = 0) the shared page CANNOT be aliased because row 0's only granule also holds row 1's start — so sentinels == 0 must stay "one handle over the whole fixed span". The valid unification is: let page = if sentinels == 0 { fixed_bytes } else { alignment }; // per-mapping length AND address stride let count = sentinels.max(1); map_cache_chunk(page, &(0..count).map(|i| (row.name, row.address + ipage, page)).collect::<Vec<_>>())?; let tail = fixed_bytes - pagecount; // sentinels==0 → 0 if tail > 0 { map_cache_chunk(tail, &[(row.name, row.address + pagecount, tail)])?; } Check: sentinels==0 → page=fixed, count=1, tail=0 → exactly one call over the whole span = old behaviour, same handle count. sentinels=n>=2 → n mappings of len A over [0,nA), tail = fixed - n*A >= 0. Zeroing collapses the same way (zero(page) once, zero(tail) once). This deletes the duplicated if sentinel_granules > 1 {…} else {…} blocks at cache_memory.rs:1417-1447 and 1468-1488 and the >1 vs >0 inconsistency.

#4 [high] Findings: row_backing_bytes dup, triplicated branch, GPU test churn

FINDING 1 (high). row_backing_bytes (memory.rs:383-414, 32 new lines) re-implements bytes (memory.rs:357-381) verbatim — same capacity filter, same units > s.maximum error, same checked_mul + (align-1) / align * align padding, same "cache allocation size overflow" — and differs only by the - saved subtraction. Verbatim current (memory.rs:394-413):

        .try_fold(0u64, |total, (a, s)| {
            if units > s.maximum {
                return Err(invalid("cache capacity exceeds its virtual extent"));
            }
            let align = a.alignment as u64;
            let span = units
                .checked_mul(s.unit_bytes)
                .and_then(|n| n.checked_add(align - 1))
                .ok_or_else(|| invalid("cache allocation size overflow"))?
                / align
                * align;
            let saved = if units > 0 {
                super::cache_memory::sentinel_saved_bytes(s.unit_bytes, align)
            } else {
                0
            };
            total
                .checked_add(span - saved)
                .ok_or_else(|| invalid("cache allocation size overflow"))
        })

vs bytes (memory.rs:367-380) with .filter(|s| s.capacity == capacity) and no saved. Replace whole fn body with:

fn row_backing_bytes(core: &Core, units: u64) -> Result<u64> {
    if units == 0 {
        return Ok(0);
    }
    let saved: u64 = core
        .allocations
        .iter()
        .filter_map(|a| a.sizing.as_ref().filter(|s| s.capacity == 0).map(|s| (a, s)))
        .map(|(a, s)| super::cache_memory::sentinel_saved_bytes(s.unit_bytes, a.alignment as u64))
        .sum();
    bytes(core, 0, units).map(|span| span - saved)
}

Equivalence: identical fp0; span - saved cannot underflow for units>=1 (span >= row + align > saved). All 5 call sites (memory.rs:486, 510, 523, 1003, 1249) unchanged.

FINDING 2 (high). allocate_shared_cache writes the same three-case decomposition three times, and handle_charge a fourth:

let count = layout.sentinel_granules.max(1);                       // shared handle's mapping count
let granule = if count > 1 { layout.alignment } else { layout.fixed_bytes }; // sentinels<=1 => whole span
let tail = layout.fixed_bytes - granule * count;                   // 0 for sentinels<=1

handle_charge equivalence (n = sentinel_granules, tail>0 ⟺ n>=2 && nA < fixed): fixed_charge = 1 + tail? + row_readers * (count + tail?) reproduces today's 1+row_readers (n<=1) and 1+nrow_readers (+1+row_readers when tail) exactly.

FINDING 3 (medium). GPU test churn cache_memory.rs:1212-1225: row 0 special-cased INSIDE the pattern closure (+11 lines, nested if/else). Just:

let mut expected: Vec<Vec<u8>> = (0..7).map(/* original closure untouched */).collect();
expected[0] = vec![0; geometry.row.unit_bytes as usize];   // null sentinel row stays zero

keeps the .skip(1) upload and the single assert!(contents == expected[row]) check, -11/+2 lines, and the pattern stays one expression.

No dead flags/knobs/fallbacks introduced: every new symbol (sentinel_granules, sentinel_saved_bytes, both tests, both doc hunks) is used.

#6 [high] Research summary

Subtraction/Simplicity review of PR #659 done. The diff is honest and mostly lean (+196/−33, two new CPU tests, no flags/knobs/fallback layers, no AGENTS.md structural violation), but three concrete cuts are available, all recorded in the scratchpad with verbatim quotes.

  1. row_backing_bytes (memory.rs:383-414) is a 32-line copy of bytes (memory.rs:357-381) — same capacity filter, same units > s.maximum error, same checked_mul + (align-1) / align * align padding, same overflow messages; only the - saved term is new. Replace the body with bytes(core, 0, units).map(|span| span - saved) plus a saved fold, keeping all five call sites.

  2. The null-row decomposition is written three times in one file — handle_charge (cache_memory.rs:82-102, four identical overflow closures), the mapping block (1416-1447) and the zeroing block (1467-1488) each special-case sentinel_granules > 1 / tail / else. One derived description (count = sentinels.max(1), granule = if count > 1 { alignment } else { fixed_bytes }, tail = fixed - granule*count) reproduces today's handle counts exactly (1 + row_readers for n <= 1; 1 + n*row_readers [+ 1 + row_readers] otherwise) and collapses both else branches, which are determinable code, not real cases.

  3. The GPU test edit adds a branch inside a closure (cache_memory.rs:1212-1225): row 0 is special-cased inside the pattern generator, +11 lines. Assigning expected[0] = vec![0; …] after the unchanged closure is −11/+2 and keeps the single contents == expected[row] assertion.

Lower-value: the sentinel_* names are a second word for the repo's existing "null row" (docs already say "null row zero"), and sentinel_granules is derivable at its only allocation site. Nothing dead was introduced.

#7 [high] Verbatim quotes for finding 2 (triplicated decomposition) — needed to write the report

Finding 2 needs three verbatim quotes. All at PR head 16e2247.

(a) handle_charge, cache_memory.rs:81-102 (21 new lines):

    fn handle_charge(&self, row_readers: u64, plane_readers: &[u64]) -> Result<u64> {
        let fixed_charge = if self.sentinel_granules > 1 {
            let sentinel_bytes = self.sentinel_granules * self.alignment;
            let sentinel = 1u64
                .checked_add(
                    self.sentinel_granules
                        .checked_mul(row_readers)
                        .ok_or_else(|| invalid("mapping handle count overflow"))?,
                )
                .ok_or_else(|| invalid("mapping handle count overflow"))?;
            if self.fixed_bytes > sentinel_bytes {
                sentinel
                    .checked_add(1)
                    .and_then(|n| n.checked_add(row_readers))
                    .ok_or_else(|| invalid("mapping handle count overflow"))?
            } else {
                sentinel
            }
        } else {
            1u64.checked_add(row_readers)
                .ok_or_else(|| invalid("mapping handle count overflow"))?
        };

Replacement (one line, after introducing the two derived quantities below):

        let fixed_charge = 1
            + u64::from(tail > 0)
            + row_readers * (count + u64::from(tail > 0));

(b) mapping, cache_memory.rs:1416-1447:

            let sentinel_bytes = layout.sentinel_granules * layout.alignment;
            if layout.sentinel_granules > 1 {
                let mappings: Vec<_> = (0..layout.sentinel_granules)
                    .map(|i| {
                        (
                            geometry.row.name.as_str(),
                            geometry.row.address + i * layout.alignment,
                            layout.alignment,
                        )
                    })
                    .collect();
                self.map_cache_chunk(layout.alignment, &mappings)?;
                if layout.fixed_bytes > sentinel_bytes {
                    self.map_cache_chunk(
                        layout.fixed_bytes - sentinel_bytes,
                        &[(
                            geometry.row.name.as_str(),
                            geometry.row.address + sentinel_bytes,
                            layout.fixed_bytes - sentinel_bytes,
                        )],
                    )?;
                }
            } else {
                self.map_cache_chunk(
                    layout.fixed_bytes,
                    &[(
                        geometry.row.name.as_str(),
                        geometry.row.address,
                        layout.fixed_bytes,
                    )],
                )?;
            }

Replacement:

            let count = layout.sentinel_granules.max(1);
            let granule = if count > 1 { layout.alignment } else { layout.fixed_bytes };
            let mappings: Vec<_> = (0..count)
                .map(|i| (geometry.row.name.as_str(), geometry.row.address + i * granule, granule))
                .collect();
            self.map_cache_chunk(granule, &mappings)?;
            let tail = layout.fixed_bytes - granule * count;
            if tail > 0 {
                self.map_cache_chunk(tail, &[(geometry.row.name.as_str(), geometry.row.address + granule * count, tail)])?;
            }

(c) zeroing, cache_memory.rs:1467-1488:

            // Zero each physical byte once, before any graph or transfer can read an alias.
            if layout.sentinel_granules > 1 {
                self.driver.check(
                    "cuMemsetD8_v2",
                    (self.driver.zero)(geometry.row.address, 0, layout.alignment as usize),
                )?;
                if layout.fixed_bytes > sentinel_bytes {
                    self.driver.check(
                        "cuMemsetD8_v2",
                        (self.driver.zero)(
                            geometry.row.address + sentinel_bytes,
                            0,
                            (layout.fixed_bytes - sentinel_bytes) as usize,
                        ),
                    )?;
                }
            } else {
                self.driver.check(
                    "cuMemsetD8_v2",
                    (self.driver.zero)(geometry.row.address, 0, layout.fixed_bytes as usize),
                )?;
            }

Replacement: same granule / tail values, two unconditional-if calls:

            self.driver.check("cuMemsetD8_v2", (self.driver.zero)(geometry.row.address, 0, granule as usize))?;
            if tail > 0 {
                self.driver.check("cuMemsetD8_v2", (self.driver.zero)(geometry.row.address + granule * count, 0, tail as usize))?;
            }

NOTE for the report: in (b) and (c) granule/count/tail must be computed before the mapping block and reused by the zeroing block (which is ~20 lines later, same function, no ? in between other than map calls — so hoisting is trivial). In (a) the same count/tail can be computed as let count = self.sentinel_granules.max(1); let tail = self.fixed_bytes - if count > 1 { self.alignment * count } else { self.fixed_bytes };. Careful wording: this is a maintainability proposal (one description of the null-row physical slices used by handle accounting, mapping and zeroing), NOT a correctness bug; do not present the > 1 vs > 0 boundary as a bug — n == 1 is already filtered to 0 at cache_memory.rs:259-262, so both spellings agree today.

#5 [medium] Lower-value notes: derivable field, naming drift, no AGENTS violations

Lower-value observations (mention briefly, not as headline findings):