Skip to content

perf(dynamicemb): remove the host syncs of DynamicEmb (lookup, growth, determinism mode, explicit APIs) - #542

Closed
shijieliu wants to merge 83 commits into
NVIDIA:mainfrom
shijieliu:enh-dynamicemb-no-host-sync
Closed

shijieliu wants to merge 83 commits into
NVIDIA:mainfrom
shijieliu:enh-dynamicemb-no-host-sync

Conversation

@shijieliu

@shijieliu shijieliu commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Description

No DynamicEmb code path makes the CPU wait for the GPU any more, except two kinds of call: one whose result is host data (a checkpoint file, a pop, a metrics read, an erase count), which has to wait once for it, and a call into a class the user wrote against the host-sized contract, which takes a count by definition. The first 15 commits of this PR removed the host syncs of the lookup of a training or eval step (flagged_compact, boolean-mask indexing, .any() in an if, a pinned copy plus a stream synchronize, a scalar assigned through a CUDA index, ...). They listed what still waited: table growth, DEMB_DETERMINISM_MODE, an external parameter server and user classes, the memory guard that sent a big batch down the reading path, DYNAMICEMB_SYNC_FREE=0, and the checkpoint / pop / flush APIs at several waits per table or batch. The commits after them remove all of it. Nothing is left behind an environment variable: no variable selects a path that reads.

Blocking host syncs, measured on origin/main and on this branch by the probe added here (profiler CUDA runtime events + sync debug mode + interposition; 8 measured steps after 3 warm-up steps; H100): 66 configurations x scenarios x plain/prefetch = 556 cases, 540 read zero blocking syncs. The 16 that do not are the old-contract external storage (below). Per lookup group per step, before -> after:

layout all keys hit new keys new keys, evictions eval eval, missing keys
cache + storage (LRU) 4 → 0 8 → 0 10 → 0 1 → 0 2 → 0
cache + storage, Adam 4 → 0 8 → 0 10 → 0 1 → 0 2 → 0
cache + storage, LFU 4 → 0 8 → 0 10 → 0 1 → 0 2 → 0
cache + storage, frequency admission 4 → 0 12 → 0 14 → 0 1 → 0 2 → 0
cache + storage, RETAIN_KEY 4 → 0 9 → 0 12 → 0 1 → 0 2 → 0
cache + storage, SUM pooling 4 → 0 8 → 0 10 → 0 2 → 0 3 → 0
HBM only 4 → 0 6 → 0 6 → 0 1 → 0 1 → 0
HBM only, frequency admission 4 → 0 14 → 0 14 → 0 1 → 0 1 → 0
host only 2 → 0 4 → 0 4 → 0 1 → 0 1 → 0
host only, frequency admission 2 → 0 7 → 0 7 → 0 1 → 0 1 → 0
hybrid (HBM tier + host tier) 7 → 0 16 → 0 16 → 0 1 → 0 7 → 0
hybrid, frequency admission 7 → 0 19 → 0 19 → 0 1 → 0 7 → 0

and the cases the first 15 commits had to leave:

case origin/main this branch
a growth event of a table (HBM only, cache + storage, host only, hybrid host tier, NO_EVICTION; per step of a window with 3 growths) 8.8 to 12.8 0 (1 to 3 allocator-class events: pages mapped or registered)
DEMB_DETERMINISM_MODE, cache + storage (all hit / new keys / new keys with evictions / tier 2 hit) 4 / 236 / 790 / 760 0 / 0 / 0 / 0
DEMB_DETERMINISM_MODE, HBM only (all hit / new keys / evictions) 4 / 25 / 65 0 / 0 / 0
external storage that declares the padded contract (device-resident parameter server) 4 to 28 0
a batch whose miss path exceeds the buffer budget (was: the reading path) many 0 (the miss path runs in row chunks)
external storage written against the host-sized contract (PyDictStorage: all hit / miss / miss + evictions / tier 2 hit) 4 / 24 / 28 / 25 1 / 13 / 15 / 12, of which 1 / 3 / 3 / 3 are DynamicEmb's own audited read (the number of live rows, once per call into the class, which its contract takes) and the rest is the stand-in's own host code
the new probe configurations: AdaGrad, row-wise AdaGrad (fp16/bf16), FTRL, uint64 keys, MEAN pooling and weights, mixed dims, probabilistic admission, a non-admitted initializer, STEP / CUSTOMIZED / LRU_LFU / PRECISE_CUSTOMIZED scores, row chunks not measured 0

HSTU end-to-end (examples/hstu/training/benchmark, exp4 caching + hash_roundrobin and exp5 + prefetch pipeline, 1 node x 8 H100, nsys window = iterations 150-170, steps 151-168 averaged, the log step left out), origin/main against this branch:

exp4_caching_hr exp5_prefetch
host syncs per step, training thread (nsys) 24.76 -> 19.18 27.35 -> 22.06
... of them inside DynamicEmb's op:* ranges 4 -> 0 4 -> 0
... in the forward / the prefetch phase forward 13 -> 8 prefetch 5 -> 1 (input_dist 8 -> 7)
pageable device-to-host copies per step 11 -> 8 14 -> 11
DynamicEmb ops' CPU time per step, segmented_unique + storage_find + flagged_compact 0.39 -> 0.11 ms 3.85 -> 0.11 ms
kernel launches per step 594 -> 630 (+5.9%) 593 -> 629 (+6.1%)
plain throughput, same node, TFLOPS/GPU (iterations 199-999) 345.4 -> 345.8 (+0.1%) 349.9 -> 349.8 (-0.0%)

Throughput is a wash, as the design predicts for this benchmark: every key hits the cache, so the miss path that now runs on every step does nothing, and what is left is not DynamicEmb's. The 19 (exp4) and 22 (exp5) syncs that remain per step are all outside DynamicEmb's op ranges: TorchRec's input distribution (the split sizes of the key all-to-all), the balanced shuffler, the optimizer step and HSTU's own global_tokens. One run each. The plain runs of origin/main and of this branch ran back to back on the same node (its run-to-run spread was 0.4-0.6% in the earlier runs, and about 0.9% between two nodes), so they are the throughput comparison. The nsys baseline of origin/main is from the other node of that earlier measurement, so only the sync counts, the copies and the DynamicEmb CPU times are comparable between the two nsys sets: its GPU step window is 1.5% (exp4) and 0.8% (exp5) shorter than this branch's on the other node, while the plain runs on one node show no difference.

What changed

The unique keys of a batch stay as long as the input with their count left on the device; a row past the count is inert (the reserved all-ones key, table id and slot -1) and every kernel skips it. That is the first 15 commits. The rest, by area (every area is a few staged commits, each valid on its own):

  1. Growth (growth_order.py, scored_hashtable.py, key_value_table.py, extendable_tensor.py, src/vmm_tensor.cu, src/table_operation/table_rows.cu). A growth event is queued on the stream that decided it and reads nothing back: the key map is rebuilt from its own padded key column (two new kernels, table_carry_slot_state and table_carry_reclaimed_rows, carry the rows, the reference counters and the reclaimed rows with the count kept on the device and the "no key may be rejected" check as a device assert); the small uploads go through pinned memory; a host value buffer grows in place (it reserves its address range when it is made and registers only the new tail, never unregisters or moves what exists); and the device-wide torch.cuda.synchronize() of ExtendableBuffer.extend is gone, replaced by an explicit order: the growth stream waits on the device for the streams that use the table, those wait for its end before their next use, and every reader of the key map (forward, backward, eval, flush, dump, export, replay, pops) orders itself after a growth. The rehash is not slower than the one it replaces at any size, and 4.5 to 9 times faster from 220 slots (it no longer reads a count per batch of the export). On an H100 node with nothing else running, three runs within 3% of each other: 0.85 ms against 0.9 at 216 slots, 0.68 against 1.3 at 218, 0.74 against 3.3 at 220, 1.4 against 10.7 at 222, 4.4 against 40.5 at 224. A first measurement, made while other suites shared the node, had shown the small tables a few milliseconds slower: the count-free rehash is a string of small launches, so at that size its time is the host's, and the gate keeps a 6 ms allowance for a busy node.
  2. DEMB_DETERMINISM_MODE (src/table_operation/{bucketize,insert_sorted,kernels}.cu*, scored_hashtable.py). Every insert sorts its keys by bucket and key on the device and one thread inserts the keys of a bucket one after the other in a single kernel, instead of a host loop over "waves" whose count was read back. Same table as the ordinary insert gives for that order of keys; the keys a call took stay locked until the call is done, as in the ordinary kernel, so the cache and HybridStorage write-back stays correct. 3 to 9 times faster than the waves on uniform and evicting batches (65,536 keys over 8,192 buckets: 0.58 ms against 1.7 ms; over 256 buckets: 9 against 80 ms); a batch whose keys all fall into one bucket is serialized in that bucket (about 31 us per key) and an all-inert insert costs 0.5 ms where the waves cost 0.1.
  3. Extension contract (types.py, batched_dynamicemb_function.py, key_value_table.py, sync_free.py). Storage gains an optional padded contract (find_masked / insert_masked, rows whose key is the reserved key are no-ops, no count anywhere) with a device-resident reference implementation (DynamicEmbStorage) and a base-class adapter for a class that only implements find / insert (one read of the number of live rows per call into it; a step that missed nothing does not call it). The memory guard is gone: a miss path whose buffers would exceed DYNAMICEMB_MISS_PATH_BUFFER_BYTES (4 GiB, was DYNAMICEMB_SYNC_FREE_MAX_BYTES) runs in consecutive row chunks. The four host-sized lookup bodies are deleted (a verbatim copy lives on as the test oracle); DYNAMICEMB_SYNC_FREE, the read miss gate and DYNAMICEMB_EXACT_GROWTH are removed.
  4. Per-step audit fixes. The negative-score check never waits (a cumulative device counter, ordered across streams); the embedding collection reads no dedup count for DynamicEmb's row-wise sharding and the scored input dist exchanges the splits once; dead code with blocking primitives is deleted; the first-step state is built with the module; the probe covers optimizers, dtypes, key types, poolings and score kinds (66 configurations, 556 cases).
  5. Explicit APIs wait once per call or batch, not per table, chunk, column or pending entry: dump once per batch and only the live rows are copied, load stages its uploads and filters on the host, replay_increment checks the placement of a delta once and raises before it writes a row, pop_* twice per module, flush reads no count (an external storage below the cache excepted), EraseHandle.result() once.
  6. Found on hardware, fixed in this PR (nothing in the lane designs could have found these without a GPU): a prefetch's tensors are now recorded on the forward stream (dynamicemb_prefetch had a forward_stream parameter that nothing used, so the caching allocator could hand a block to the next prefetch while a late backward still read it: illegal memory accesses in a stress that models TorchRec's prefetch pipeline, also on a table that cannot grow); _drain_chunks of the pop path indexed per-table arrays with a table id past num_tables (a device assert that killed the process); the rehash's bucket-size sum made a table-sized int64 copy; the lanes' tests and the probe (acceptance counted allocator events as syncs; tier2_hit and hybrid_growth measured something else than their names).

What it costs

  • A step launches the same kernels whether its keys hit or miss: about 35 more launches per step when everything hits, fewer when keys miss (and no waits). It shows only when a step is CPU-bound. DYNAMICEMB_MISS_PATH_GATE=poll skips the miss path when a non-blocking poll shows nothing missed.
  • The miss path's buffers (values, evicted_values) are sized by the input length, not by the number of misses; above the budget the path is chunked and its number of launches grows with the number of chunks, not its number of reads.
  • A growth that is rare costs host time while pages are pinned (a host value buffer: about 45 ms per 64 MiB, the calling thread, nothing waits for the device) and a few allocator-class events (page mapping and registration).
  • A host value buffer reserves address space when it is created (VmSize, not memory): exactly max_capacity for a table that evicts, DYNAMICEMB_HOST_RESERVE_FACTOR (8) times it, at least 64 GiB, for one that never evicts; growing past it raises an error that names the variable.

What still waits for the GPU

Every remaining read is one of these, and the ones that go through sync_free.read_now, pull_to_host, .wait( or flagged_compact are listed with their reasons in test/unit_tests/no_host_sync/test_audited_reads.py, which fails for an unlisted one:

  • a call whose result is host data: dump / load / export / incremental_dump / replay_increment, pop_evicted_keys / pop_erased_keys, erase_keys, EraseHandle.result(), cache_metrics(), flush() (one wait per call, or per batch of a call that moves data in batches; counted per API in DynamicEmb_APIs.md, "What the explicit calls wait for");
  • a class written against the host-sized contract (an external Storage, a user MultiTableAdmitter / Counter / non-admitted-row initializer that has not declared the padded contract): one read of how many rows are live per call into it, which its contract takes. Implement the padded contract (accepts_empty_keys = True, see "External storage") and DynamicEmb reads nothing on its behalf;
  • setup and teardown (a table that is dropped waits for queued work before it frees memory), and the first launch of a kernel in a process under CUDA's lazy module loading;
  • TorchRec's input distribution: the split sizes of the all-to-all of keys (one length_per_key and one exchanged-splits read per sharding), and, with use_index_dedup, a sharding that is not DynamicEmb's row-wise one still needs its unique-key count, one read per step.

Behaviour changes

  • Environment: DYNAMICEMB_SYNC_FREE, the read value of DYNAMICEMB_MISS_PATH_GATE and DYNAMICEMB_EXACT_GROWTH are removed (setting one prints a warning and changes nothing); DYNAMICEMB_SYNC_FREE_MAX_BYTES is now DYNAMICEMB_MISS_PATH_BUFFER_BYTES and splits a batch into chunks instead of choosing another path; DYNAMICEMB_HOST_RESERVE_FACTOR is new.
  • The extension must be rebuilt (python setup.py build_ext --inplace): the sorted inserts and the rehash kernels are new, and an older build raises an error that says so (there is no fallback that waits).
  • Only DynamicEmbCache and DynamicEmbStorage (or a subclass that re-declares accepts_empty_keys = True in its own body) are accepted as the cache and the storage of a cache's lookup; any other class is a TypeError that names the fix.
  • A rehash that cannot place a key (a bucket of the new key map overfilled: only a growth to a size that is not a whole multiple of the old one can, such as the last growth, clamped by max_capacity) is a device-side assert, not a Python AssertionError.
  • A table may grow by up to a few batches' keys earlier than an exact check would, never later; a checkpoint load decides from the exact sizes with one read. The outstanding-keys over-subscription error and the negative-score check are raised one or two calls late (several negative batches between two polls give one report); flush() drains them.
  • A host value buffer that has grown is registered in pieces (one per growth): a copy-engine operation over a range that crosses two pieces (copy_, clone, .cpu() of the whole buffer) is refused by the CUDA driver with "invalid argument"; kernels and memsets work across any number of pieces, and the library only touches value buffers with kernels.
  • In DEMB_DETERMINISM_MODE a bucket that gets more new keys than it has free or evictable slots admits the smallest keys and refuses the rest, the guarantee per score strategy is written down in DynamicEmb_APIs.md ("Deterministic mode"), and insert() now fills insert_results and score_out in that mode (it used to leave them uninitialised, which the admission counter read).
  • From the first 15 commits: the in-tree probabilistic admitter draws one random number per row of the batch; a cache insert that was refused is no longer written back over the key's storage row; cache_metrics is read from a device buffer when the getter is called; RETAIN_KEY keeps pending chunks until their count lands, pop_evicted_keys waits for them.

Tests

Everything below ran on an H100 node of Eos (ci-image-2607: PyTorch 2.13, CUDA 13.3, DEMB_ARCHS=90); the multi-GPU suites ran one at a time (they share one rendezvous port). The 68 commits after the first 15 were written on a machine without a GPU and first compiled and run at the end: the extension compiled on the first build, and what the hardware found is item 6 of "What changed". The numbers are from this tree: the commits after the main runs change tests, a test helper, comments and one import order only, and what they touch was run again (E4 and the nine tests that failed alone, on the node; the unit tests of the budget helper, on a CPU node).

  • New suites, all passing (pytest cases, parametrized): sorted insert, segmented bucketize and the determinism mode 635 (test_sorted_insert 270, test_bucketize_segmented 246, test_sorted_insert_hw 93, test_determinism_mode 26); growth 243 (padded rehash 101, value-move model 93, host value buffer 14, growth order and hooks 35); the padded contract and the chunked miss path 294 (padded_contract 110, miss_path_chunks 56, masked hybrid 56, eval 22, lazy retain 20, ...); the explicit APIs and the per-step fixes 295 (pop_one_pass 98, load_staged 25, dump_pipelined 24, expand_async 24, dedup_padded_dist 23, ...); the static checks and helpers 1065 (tail_invariants 397, env_surface 253, sync_free 235, sync_free_helpers 139, host_sync_probe_unit 32, audited_reads 9). The probe census (556 cases) and the strict ratchet, acceptance and lint run (HSP_ASSERT_ZERO=1 HSP_RATCHET_STRICT=1 SYNC_LINT_STRICT=1): 486 passed, 1 skipped, 3 expected failures.
  • Existing suites, all passing: the single-GPU suites, 63 files and 4,925 cases in all (some files are in two groups), none failed: the v2 tables suite (399 passed, 4 skipped), test_table_operation 663, test_lru_lfu, test_multitable_ref_counter, test_async_count, test_vmm_tensor, test_ftrl_optimizer, test_erase_api, ... test_lfu_scores.py and test_embedding_admission.py collect no tests (as on main; their .sh wrappers are the tests, and pass). The multi-GPU suites: per_key_score (76), sequence_embedding, pooled_embedding, table_row_wise, twin_module (57 passed, 40 skipped), erase_async, hybrid_export (17), table_operation_sh (204), retain_evicted, weighted_pooled_v2, hash_rr_kuairand, rowwise_adagrad, table_rows, int64_weights, freq_*, planner_*, ckpt_file_discovery, admission_sh, lfu_scores_sh; the alignment suite (1,440 cases) at 1, 4 and 8 ranks and incremental_dump (17) at 1 and 8 ranks.
  • Hardware gates for growth (test/unit_tests/growth/gates/, set DEMB_GROWTH_GATES=1): E1 a device value buffer's extend against a kernel of 1.8 s in flight: blocked in 0.00% of the iterations in 12 variants (the controls with a synchronize are blocked in all of them, so the gate can tell); E2 the same for a host value buffer registered in place, plus the address staying put over 1,000 growths, 20 pieces as fast as one (within 5%) and 128 tables reserving 64 GiB each: pass; E3 table growth against the streams of TorchRec's prefetch pipeline (a table that grows at every step, random sleeps in front of the forward, the backward and the prefetch, 5,000 steps on each of 4 layouts, the output of every step and the reference counters checked): pass, and the same gate fails with the order removed (the negative control); this is the gate that found the missing record_stream of a prefetch's tensors. The conclusion it carries: the device-wide torch.cuda.synchronize() of ExtendableBuffer.extend is safe to remove. E4 the rehash, three runs on an idle node, in the numbers of "What changed" item 1: pass.
  • The HSTU pipeline test (TorchRec's prefetch pipeline, a private patched copy) with the item table starting at init_capacity=128: the table grew twice (key map generation 2, capacity 24,576) and the pipelined loss and logits match the unpipelined model.
  • Sanitizers: compute-sanitizer memcheck, racecheck, initcheck and synccheck over the sorted-insert kernels, each with a positive control that shows the tool sees an injected error: no finding. memcheck over the growth gates and the explicit-API copies: no finding.
  • Each test alone: a test that passes in its file can fail alone when it times something right after the first launch of a kernel (CUDA's lazy module loading makes that launch wait for the device). Every test of the 13 files that hold a stream busy with a sleep kernel was run in a process of its own (464 tests); nine failed that way (three in test_sync_free_helpers.py, six in test_check_scores_late.py) and each now launches its kernel once before the window opens. After the change all 162 tests of those two files pass alone and both files pass whole (139 and 23).

Not run: sm_80 / sm_100 / sm_120 builds (the new kernel code is architecture-independent but only DEMB_ARCHS=90 was built), more than one node, compute-sanitizer over the whole suites (it was run, with all four tools and no finding, over the new sorted-insert kernels, and with memcheck over the growth gates and the explicit-API copies).

How to look for a remaining sync: python test/unit_tests/no_host_sync/host_sync_probe.py --configs cache_storage,hbm_only_growth --scenarios all_hit,miss (needs a GPU; --compare diffs two censuses), or run test_sync_ratchet.py / test_no_host_syncs.py, which fail if a step blocks more often than budgets.json allows (HSP_ASSERT_ZERO=1, HSP_RATCHET_STRICT=1).

Checklist

  • I am familiar with the Contributing Guidelines.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes (DynamicEmb_APIs.md: "Host syncs", "Chunked miss path", "External storage", "Table expansion", "What the explicit calls wait for", "Deterministic mode", the environment variables).

🤖 Generated with Claude Code

shijieliu and others added 15 commits November 9, 2026 08:42
…in insert_body

For a table with a compound score (LRU + LFU) the insert cubin fixes
OutputScore=true and receives score_output == nullptr whenever the caller gives
no score_out (LinearBucketTable.insert does not by default). insert_body writes
score_output[i] without a check in its table_cap == 0 block, the block a
reserved key (EmptyKey, LockedKey, ReclaimKey and the key below them) or a table
without buckets takes, while the write at the end of the function is checked. A
reserved key in such an insert therefore stored through a null pointer and
failed with an illegal memory access.

Callers do not send reserved keys today, but the sync-free lookup paths that
follow replace compaction by masking, so a key that takes no part in a step is
replaced by the reserved key and reaches this block on every step. Check the
pointer like the write at the end of the body does. The LruLfu fatbins are
rebuilt from this header by the normal build.

test_lru_lfu_insert_reserved_keys_without_score_out inserts reserved and real keys
into an LRU+LFU table with no score_out. On the unfixed build it faults with an
illegal memory access at the next synchronize; with the check it passes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
… unique, evict, initializer and optimizer kernels

An array that is sized at its upper bound (the unique keys at the input length,
the evicted arrays at the batch length) and holds data only in a prefix has to
be read back to the host to learn the prefix length. These edits define what the
rest of such an array holds, so that later changes can use the arrays at their
upper bound and leave the length on the device. They change nothing for the
code that exists today, which still slices by the length.

* segmented_unique_cuda: rows past the unique count get EmptyKey (all ones, the
  reserved key every table kernel skips without reading its table id) and
  frequency 0.
* expand_table_ids_cuda: rows past offsets[num_tables] get table id -1 instead
  of num_tables, which names no table.
* DYNAMICEMB_DEBUG's check of segmented_range is a device assert instead of a
  host read.
* initialize_with_index_addressor_kernel skips an index below 0 before it forms
  the destination row or draws a number.
* table_insert_and_evict and table_insert_collect_evicted fill their evicted
  arrays with -1 (keys all ones, indices, scores and table ids -1): one fill of
  one int64 block, viewed as the arrays.
* the padded-buffer optimizer kernels skip a row whose table id is below 0, never
  read table_ids when there is no table_emb_dims, and the gradient pointer of
  the flat kernels is formed with a 64-bit product.

Each edit is announced to Python by a bool attribute of dynamicemb_extensions
(segmented_unique_tail_inert, evicted_tail_inert,
initializer_skips_negative_index, padded_optimizer_skips_negative_table_id) so
that the Python side can fall back on a build that lacks it.

New tests cover every edit and fail on the previous sources: padded unique and
table ids for int64 and uint64 keys with and without frequencies, the
initializers with -1 indices, the evicted arrays of both insert entry points,
the padded-buffer optimizers with tail rows (including batches beyond 2^32
elements), and the lookup, erase, counter and row-resolution kernels fed a padded
batch.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…okup paths

A new module, dynamicemb/sync_free.py, holds everything the sync-free paths
share, so that no other file spells a workaround twice. Nothing calls it yet.

* The padded-array convention: EMPTY_KEY (the reserved all-ones key that every
  table kernel skips without reading its table id), as_i64 / mask_keys for
  uint64 keys that have no where kernel, canonical_unique, inert_evicted,
  inert_collected, initialize_masked and padded_optimizer_table_ids. Each uses
  the inert tails the extension now writes when it announces them
  (segmented_unique_tail_inert, evicted_tail_inert,
  initializer_skips_negative_index, padded_optimizer_skips_negative_table_id)
  and has a bit-identical Python fallback for a build that lacks them.
* DeferredRead: a ring of pinned buffers and events, allocated once, that
  carries a device value to the host without ever blocking. enqueue returns None
  when no slot is free, so a full ring degrades to a later read.
* read_now: the one audited blocking read, for the cases that need a host value
  (an external parameter server, a user-defined class, a public API that returns
  host data). Every other read of the package goes through DeferredRead, so a
  grep for read_now lists exactly the syncs that remain.
* pull_to_host, StagedUpload, compact_by_count, and MissGate with its mode
  (always, poll or read).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…eterministic insert's counts off the host

LinearBucketTable.insert_and_evict, insert_and_evict_with_counter_and_overflow
and insert take an optional keyword-only async_count (default False, so every
caller behaves as before). With it, insert_and_evict returns the evicted arrays
at the batch length with the count left on the device, instead of reading the
count to slice the arrays: the evicted-key count was one blocking read per miss
step of the cache path and of the host tier of HybridStorage. The arrays'
tails are the inert tails of the extension (keys all ones, indices and table
ids -1); a refused insert still shows as an entry with a negative index, as
before, and callers mask it.

For tables with a compound (LRU + LFU) score the insert always passes a
score_out, so a reserved key in the batch does not reach the kernel without one.

DEMB_DETERMINISM_MODE's insert, stage 1: _bucketize_and_pad drops the reserved
keys of the batch before it buckets them (they all hash to one bucket and would
make a wave each), repeat_interleave gets its output_size, the wave loop runs on
padded lanes, and the evictions of the waves are accumulated at device offsets.
The mode keeps the two reads that need new kernels (the wave count and the
bucketize count), down from 6 + 3 or 4 per wave.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…Y, device cache metrics and a masked write-back

* _find_keys takes compact=False and then skips the compaction of the missing
  keys. Four call sites compacted and read a count whose result they discarded
  (the cache path's storage find, the write-back's presence test, the rehash's
  slot lookup, eval); they use the flag.
* load_from_flat can write into a given output, so a caller loads the rows it
  has and initializes the rest in one buffer.
* RETAIN_KEY no longer reads the evicted count on every insert: the evicted
  arrays are kept with their device count in a pending list and folded into the
  retained chunks once a non-blocking read of the count has landed. Arrays that
  are not a prefix (a masked array) go through _append_evicted_masked, which
  compacts by a stable sort and never slices by a count. _pop_chunked_keys drops
  entries whose table id is negative, and popping waits for the pending chunks.
* The cache's hit-rate statistics accumulate on the device and are read when the
  getter is called, not on every lookup.
* _write_back_evicted_masked writes the evicted rows back to the storage by a
  constant lookup of their keys and a store_to_flat by row, without compacting
  the present and absent keys (the old code compacted twice and read two
  counts). An entry the cache refused (a negative slot) is not written back:
  its value row was never loaded, and the old code stored an unloaded row over
  the key's row in the storage.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…ups without host reads

DynamicEmbStorage and HybridStorage get lookup_masked and load_masked: the same
lookup the public find does, over a batch whose masked-out keys are the reserved
key, returning per-row founds and rows instead of compacting the missing keys.
find keeps its contract (one compaction, for the callers that need the missing
keys) and is a wrapper.

* HybridStorage.find looked in the HBM tier, compacted the misses, looked them up
  in the host tier and merged the two with boolean-mask indexing (5 to 9 reads
  per forward, 5 to 10 per backward). The host-tier lookup now runs over the
  full-length batch with the keys the HBM tier found masked out, and the merge
  is a row-wise choice between the two tiers. Both lookups still score as they
  did: LRU timestamps and LFU counts are updated exactly as before, in the
  forward and in the backward refresh.
* HybridStorage.insert and load take the evicted rows of the HBM tier from the
  device-counted arrays and spill them to the host tier with the masked insert.
* The eval lookups (_eval_lookup_storage, _eval_lookup_cached, eval_lookup) take
  a missing key's constant row by a where over the full batch instead of
  compacting the missing keys, so an eval step reads nothing.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…dmitters, one fill for the optimizer reset

* The frequency admitter erases an admitted key from its counter. It compacted
  the admitted keys and read their count first; it can erase the batch with the
  non-admitted keys masked out, since the erase skips the reserved key.
* The in-tree admitters (and only they, by exact type) announce that they accept
  a batch holding the reserved key and a table id of -1. A user subclass that
  overrides admit() never receives them: it keeps getting the compacted,
  host-sized batch it was written for.
* reset_optimizer_states filled the rows of the missing keys with an index
  assignment through a CUDA index tensor, a blocking host-to-device copy of the
  scalar on every miss step. It uses index_fill_, which has none. The dead FTRL
  branch of the reset is removed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…cks from late reads

Three host decisions read a device value on every step, or every few steps, to
decide something that tolerates a delay. They now read it late, through a ring
of pinned buffers and events that never blocks.

* Table growth. expand_if_need compared a host over-estimate of a table's size
  (the last confirmed size plus every batch's unique keys) with the load factor
  and, whenever it crossed, confirmed the true size with a blocking copy, even
  when the key set was stable. The decision now uses the last landed snapshot of
  the table sizes plus the bounds of the batches issued since, so a table grows
  at most a few batches' keys earlier than before and never later. The bound of
  a table is its own key count taken from the cached length_per_key of the
  input KJT when there is one (never read from the device), not the input length
  of the whole group. load() and DYNAMICEMB_EXACT_GROWTH=1 keep the blocking
  exact confirmation. The size copy that was issued before the dedup and landed
  only because the dedup's stream synchronize followed it gets a landing zone of
  its own with an event.
* Outstanding keys. The check that a prefetch pipeline does not hold more keys
  than the cache can pin counted the unique keys of every batch on the host.
  OutstandingKeys keeps the host bound (the input length) and corrects it with
  the exact count when that has landed; an over-subscription is reported one or
  two prefetches late, and only when the bound and the exact count agree.
* _check_scores. The negative-score check of PRECISE_CUSTOMIZED tables reduced
  on the device and read the result in the forward and in the prefetch. It
  enqueues the reduction into a ring and raises (or warns, per safe_check_mode)
  when it has landed, at most two calls late; flush() drains it.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
Every lookup path of a prefetch or forward step compacted the keys it had to act
on (flagged_compact, boolean-mask indexing, .any() in an if) and read the count
of each compaction to size what followed: the cache path 4 to 10 reads, the
HBM-direct path 4 to 16, the DEFAULT path 2 to 5, and a scalar assigned through
a CUDA index tensor is a blocking host-to-device copy as well. This adds, beside
each path, a function that does the same work over the arrays at their current
length with per-row masks: a key that takes no part in a step is replaced by
the reserved key, a row that must not be touched is -1, and the kernels that
already skip those do the rest. The same launches run on a step with misses and
on one without, and no count is read, except that the miss path is still
launched or skipped by one read of the miss count (the gate, "read"; the
following changes make it "always").

* _prefetch_cache_path_masked, _prefetch_hbm_direct_path_masked and
  _generic_forward_path_masked, chosen by one dispatcher from host facts only
  (the storage, cache, admitter and external storage types, and a memory guard
  on the N x value_dim transients). The old bodies stay as the *_legacy
  functions: they serve an external parameter server, a user-defined admitter,
  Storage or Cache, a batch above the memory guard, and DYNAMICEMB_SYNC_FREE=0.
* The forward and backward carry masks instead of position lists for the keys
  an admitter refused and the keys a DEFAULT-mode batch persisted.
* The legacy bodies lose the reads that were never needed: the hit compaction,
  the storage find's compaction whose result was discarded, the scalar index
  assignments, and the rehash's slot lookup.

Behaviour changes: the probabilistic admitter draws one number per row of the
batch rather than per new key (its documented stream already depended on the
batch); a cache insert that was refused is no longer written back over the
key's storage row.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…nd a static lint

The tools that decide whether a change removed host syncs, and that keep them
removed.

* host_sync_probe.py counts the host syncs of a prefetch, forward and backward
  step (or an eval step) of a BatchedDynamicEmbeddingTablesV2 per configuration
  (cache with storage, cache with an external store, HBM-only, hybrid, host-only,
  with admission, RETAIN_KEY, LFU, a growing table, determinism mode, ...) and
  scenario (all keys hit, new keys, new keys with evictions, keys only in the
  second tier, eval, growth). Three instruments, merged: torch.cuda's sync debug
  mode with the Python call site of each sync, the profiler's CUDA runtime and
  driver events (the only one that sees a raw cudaStreamSynchronize inside the
  extension), and interposition of torch.cuda.synchronize, Stream.synchronize
  and Event.synchronize. It has a self test with known syncs and negative
  controls, and compares two censuses.
* budgets.json is the census of origin/main: the mean number of blocking syncs
  per step of every configuration and scenario. test_sync_ratchet fails if a
  step blocks more often than its budget, and also bounds the cudaMalloc and
  cudaFree events of a step. A change that removes syncs lowers the budgets in
  the same diff, so the claim is in front of the reviewer.
* test_no_host_syncs is the acceptance test: it asserts that no step of a
  configuration blocks, per configuration once its budgets reach zero. Syncs
  that stay (an external parameter server, table growth, determinism mode) are
  listed in INHERENT with the reason.
* test_tail_invariants checks the padded outputs of segmented_unique and
  expand_table_ids against a CPU reference, and that the table kernels leave a
  scribbled tail alone.
* test_sync_free_lint is a stdlib-ast lint of the sync-free functions: no
  boolean-mask indexing or assignment, no .item/.cpu/.tolist/.any/.all in a
  condition, no scalar assigned through a CUDA index tensor, no
  repeat_interleave without output_size. sync_lint.py lists every syncing
  pattern of the package and diffs it against lint_baseline.json.
* test_sync_free_helpers and conftest cover the sync_free helpers and give the
  tests a no_sync() context that turns a stray sync into an error.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…s at the input length

segmented_unique read the count of unique keys back to the host (a pinned copy
and a stream synchronize, plus a pinned allocation per call) to slice its
outputs, and everything after it was sized by that slice. It now returns the
arrays at the host-known input length N, with the inert tail the extension
writes (the reserved key, table id -1, frequency 0) and the count as a 0-d
device tensor that the host never reads.

* dynamicemb_prefetch decides once per batch, from host facts and N, whether the
  group takes the mask-form paths, and passes the decision and the validity mask
  to every path. The HBM-direct path used to re-derive the decision from the
  array length, which could disagree with the front end when the memory guard
  (large N) and the exact length (small U) differ.
* A group that needs host-sized arrays (an external parameter server, a
  user-defined admitter, Storage or Cache, a batch above the memory guard,
  DYNAMICEMB_SYNC_FREE=0) reads the unique offsets once, through
  sync_free.read_now, and slices to the exact count as before.
* The growth check and the outstanding-keys check get a per-table bound (the key
  count of the table's features when the input carries it, else N) and the
  device count to read late.
* dynamicemb_eval_forward's pooled branch takes the same padded arrays and masks
  its missing keys instead of slicing.
* reduce_grads and the fused optimizers run over N rows; rows past the count are
  never written and the optimizers skip them.
* The in-tree admitters are recognised by the capability predicate of
  embedding_admission, not by their class, so an admitter built around a user
  counter or initializer still gets the host-sized batch it was written for.
* The pinned-copy helpers of the old front end are removed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
… reads a count

The miss path (the storage lookup, the initialization of new rows, the inserts,
the eviction and the write-back) was gated by a read of the miss count: a step
whose keys all hit returned early. With the arrays at the input length and the
inert tail, a step with no misses runs the same kernels on inert rows and
changes nothing, so the gate default becomes "always" and no in-tree step reads
a count from the device. DYNAMICEMB_MISS_PATH_GATE keeps "read" (one blocking
read of the miss count, the previous behaviour of this path) and "poll" (skip
the path when a non-blocking copy has already landed a zero). A group with an
external storage or an admitter that draws random numbers, and the
deterministic mode, still use "read".

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…at still waits

A "Host syncs" section: the padded arrays with their inert tail, what the
sync-free paths cost (the miss path on every step, N-long buffers), and the
reads that remain (external storage and user-defined classes, table growth,
determinism mode, checkpoints, setup and teardown, TorchRec's split sizes).
The four new environment variables, and how the growth decision is made without
waiting.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
Also drops two assignments of unused variables in test_batched_dynamic_embedding_tables_v2.py,
which the repo's autoflake hook removes from any file that a change touches.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…llow-list the reads that remain

budgets.json held the census of origin/main. It now holds the census of this
branch: zero blocking syncs per step for every in-tree configuration and scenario
(cache with storage, HBM only, host only and hybrid; with admission, RETAIN_KEY,
LFU, Adam, pooling; all keys hit, new keys, evictions, keys only in the second
tier, eval), 218 of 272 budgets. What is left is the external parameter server
(request-sized tensors and host counts by contract), DEMB_DETERMINISM_MODE and
growth events, each excused in INHERENT with its reason.

The static lint's allow-list names the seven patterns of this change that are not
syncs of a step: a host-held score check, an exact-growth docstring, the one
compaction of the public Storage.find, host-side growth estimates,
determinism-mode reads, a multi-line repeat_interleave that passes output_size,
and construction-time pinned buffers.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
@greptile-apps

greptile-apps Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The changes since the previous review appear safe to merge.

Summary

This PR removes CPU waits from DynamicEmb lookups, growth, and deterministic inserts, and reduces waits in explicit APIs.

  • DynamicEmb lookups keep unused rows inert and run without reading their counts back.
  • Table growth rebuilds maps on a stream while preserving rows and values.
  • Deterministic inserts sort keys on the GPU and process each bucket in order.
  • Storage and admitter classes can declare whether they accept padded rows.
  • Explicit APIs group device-to-host waits around the call or batch that needs the data.

Reviews (4) · Last reviewed commit: "test(dynamicemb): a partial census keeps..." · Reviewed by Greptile

shijieliu and others added 14 commits November 9, 2026 14:44
EraseHandle.result() waited twice: for the event the worker recorded, and
again for a pageable device-to-host copy of the counts on the caller's
stream. The worker now copies the counts into pinned memory on the erase
stream before it records the event, so the event covers the copy and the
result is one wait; EraseHandleGroup.result() is one wait per handle.

wait_stream() is classified in its docstring and in DynamicEmb_APIs.md as
what it is: a wait paced by the device (the worker launches a chunk only
while fewer than max_in_flight are unfinished), not a free ordering call.
The cache metrics getter was already at its floor of one wait per read; the
docstring and the CACHE_DEBUG example hook say that it is a per-read wait
and not for a timed run.

test_explicit_api_syncs.py counts the blocking events of both calls with the
probe's census and holds them to the floor.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…n the host

Delete what has no caller anywhere in the repository (grep over *.cu, *.cuh,
*.h, *.cpp, *.py, docs) and contains a blocking primitive:

* offsets_to_table_features_offsets and its compact_offsets kernel in
  src/dynamic_emb_op.cu: a cudaStreamSynchronize and a pinned .item<int64_t>();
  it is not bound, not declared in a header and not referenced.
* the DeviceCounter class in src/utils.h: a cudaMalloc / cudaFree pair and a
  D2H copy followed by cudaStreamSynchronize; it is never instantiated.
* EmbeddingLayout.col_begin and col_width in lookup_layout.py: int() of a CUDA
  tensor (D_offsets) per call, called by nothing (no test either). The
  docstring that named them now states the rule and points to the kernels'
  col_begin / col_width in src/pooled_layout.cuh, which are a different, live
  thing and stay.

The export of a cache read int(self.overflow_output_offsets_[table_id].item())
once per overflow batch, a device read of a value the host holds:
overflow_output_offsets_ is built from per_table_capacity_ (the same list), so
the export takes the host value. One D2H and stream sync fewer per overflow
batch of flush / dump / incremental_dump of a cache.

test_sync_free_lint.py claims the twelve baseline lines of lint_baseline.json
that this removes (EXPECTED_GONE). sync_free.compact_by_count and the ps
argument of miss_gate_mode are not touched: they belong to the extension-contract
lane.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
bucketize_keys_segmented is the sort of bucketize_keys without its compaction:
the same compose and the same radix sort of (segment, key), so the keys of one
bucket come out in the same order, but it returns the home bucket of every sorted
position instead of the offsets of the active buckets. Nothing is selected and
nothing is read back (bucketize_keys reads the number of active buckets), so no
shape depends on the data. A key that takes no part in an insert (a reserved key,
whose table id is not read, a key of a table that does not exist or has no
buckets) gets the segment num_buckets and sorts after all the others.

The deterministic insert of DEMB_DETERMINISM_MODE will insert the keys of a
bucket one after another from this order. Nothing calls it yet.

bucketize_keys no longer writes buckets_end / mask one past their end for a key of
a last table that has no buckets (the functor sends it to segment num_buckets).

Tests: the op against a host reference of the home-bucket arithmetic and of the
(segment, key) order, for int64 and uint64 keys, zero-capacity tables first, in
the middle and last, reserved padding with garbage table ids, duplicate keys; the
keys that take part against the compact bucketize_keys; the sync census (zero
reads, with the compact op as the positive control).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
A growth (a key-map rehash, with or without an extension of the value
buffers) only queues kernels on the stream that decided to grow, but the table
is used from other streams: forward, backward and evaluation of the module, and
every dump, export, erase, flush or replay a caller issues on its own stream.
Until now the blocking reads inside the growth hid the missing edges; a
table that never evicts and only grows its key map had no device-wide wait at
all, so a backward still queued on another stream decremented the reference
counters of the key map the rehash had already copied, and the new map kept
the key pinned for good.

GrowthOrder (new, dynamicemb/growth_order.py, one per state that can grow)
keeps the streams that use the table and the end of the last growth:

* the growth stream waits, on the device, for what every registered stream has
  queued before the growth starts (H1);
* when it ends, the end of the growth is recorded and every registered stream
  waits for it (H2); a stream that registers later waits at its first use
  (DynamicEmbTableState.wait_for_growth), which every public method of
  DynamicEmbStorage / HybridStorage, flush_cache, the key_index_map property
  and the forward, backward, prefetch and evaluation of the module call first;
* the key map a growth replaces is marked as used by the growth stream
  (LinearBucketTable.record_stream), so that the caching allocator does not
  hand its blocks out again while the rehash may still read them (H3).

A key map and the value buffers of one decision are one growth (nested sections
count once). Nothing here waits on the host; ExtendableBuffer.extend and the
reads of the rehash are unchanged by this commit. The logic is tested with
stand-in streams (no GPU), the ordering with sleeps on the stream whose work
the growth has to wait for or that is late.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
pop_evicted_keys / pop_erased_keys waited per table (a boolean-mask index,
torch.unique, bool(keep.any()) and two more mask indexes, then a .cpu()) and
once per evicted entry that was still pending (a ring wait, or a read_now for
an entry that never got a ring slot); a model-level pop with a process group
read one size per rank per table before gathering.

A pop is now one pass over the chunks of every table: stable sorts by (table,
key) (uint64 keys through the int64 view with the top bit flipped, so they sort
as unsigned; [n, 2] slot-index chunks column by column), the first row of each
run, per-table counts by scatter_add, the wanted rows and the rows that stay
moved to the front by stable sorts of their masks. The pending entries of the
lazy append are given to the pass whole (their lanes that are not evictions
carry table id -1 and are dropped), so no count is waited for; the pop only
orders the current stream after the stream that made each entry and gives the
ring slots back. The one read returns the per-table counts and the number of
rows that stay; for a pop that returns host data a single copy then moves
exactly the popped rows, not the rows that stay. A module pop is two waits
however many tables it has: Storage.pop_many (DynamicEmbStorage, HybridStorage)
is what BatchedDynamicEmbeddingTablesV2._pop_retained and _drain_retained call.

The group gather of a model-level pop stacks the sizes of the module's tables
into one all_gather and one read, and the keys into one padded int64 gather and
one copy, with the host-side union of every rank's keys: two waits instead of
world_size + 4 per table. Uploads go through pinned memory with non_blocking.

The results are the ones the per-table code returned (sorted distinct keys in
the key type's order, the other tables' rows kept in the order they came,
sentinels dropped); test_pop_one_pass.py checks the pass against a plain
Python reference, pop_many against the per-table pops, and the waits (two,
for 2 and for 8 tables) and the bytes copied.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
The check for a negative score of a table that takes a score per key
(PRECISE_CUSTOMIZED, safe_check_mode != IGNORE) copied one answer per call into a
4-slot pinned ring, and a call that found every slot in flight blocked on the
oldest answer (Event.synchronize) to free one: a back-pressure wait on the
training thread that nothing depends on, as soon as the host is a ring ahead of
the device. A module whose check mode was switched on after construction had no
ring at all and read the scores at once (bool((scores < 0).any())).

* The device keeps one cumulative count of the calls that carried a negative
  score, and a call copies a snapshot of it. A call that finds no free slot
  takes none and waits for nothing: its check is in the count, and the next
  snapshot (or flush) carries it. The host reports when a landed snapshot is
  above the last count it reported, so a negative batch that got a snapshot is
  reported as before, and the ones that found the ring full are reported
  together by the next snapshot.
* The add to the count is a read-modify-write, so a check on another stream than
  the last one is ordered after it on the device (_wait_for_stream, the helper the
  cache metrics use); the adds form one chain, and a snapshot taken after one has
  all of them. flush takes the snapshot that the last check could not, after the
  stream that made it, so a flush on the default stream reports a negative score
  that a side stream's prefetch counted last.
* A module that has no ring when its first CUDA check comes makes one then (a
  one-time pinned allocation), so _check_scores_now only ever sees host scores.
* The count is made before the pending reports, so a call whose own report
  raises (ERROR) has counted its check; flush reports it.

test_check_scores_late.py: the two tests that pinned the ring-full wait now pin
the opposite (nothing waits, flush reports), and new tests cover the late mode,
a flush from another stream behind a lagging side stream, two alternating
streams and merged reports. no_host_sync/test_score_check_ring.py counts the
blocking events of eight checks behind a busy device and of a late mode (zero).
The lint enforces the four functions of the check; DynamicEmb_APIs.md says when
the report comes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
Building a key map for a growth made five blocking host operations: the
bucket-offset table (a pageable H2D copy that waits, then a D2H copy of the same
list), the row limits, the value-buffer pointer table and, after the rehash,
set_row_limits. All of them are a few int64 built on the host, so:

* sync_free.upload_i64 / copy_i64_into stage the list in a ring of pinned
  buffers (allocated with the first key map of the device, reused once the
  copy of the previous use has run) and queue the copy: no wait, no pinned
  allocation in a step; a list too long for a buffer, or a ring that is all in
  flight, takes a pinned tensor of its own, still without waiting;
* LinearBucketTable keeps the first bucket of every table as a Python list
  (bucket_offsets_host_) and builds the CPU tensor from the list instead of
  reading the device tensor back; copy_table_from and copy_score_blocks_from
  slice by the list; set_row_limits is a queued copy;
* publish_table_ptrs compares the buffers' base addresses with the host copy
  of the pointer table (DynamicEmbTableState.table_ptrs_host) and uploads only
  when one has moved: never for a device buffer, whose new pages are mapped
  after the old ones, so the table the kernels read is no longer rewritten;
* read_table_sizes_now reads the table sizes and the rows handed out as one
  sync_free.read_now (one pinned transfer for both vectors) instead of two
  blocking copies; collect_table_sizes_for_state(non_blocking=False) and the
  exact decision of a table that never evicts use it.

DYNAMICEMB_EXACT_GROWTH is removed: it made every training step wait for the
device sizes, which no environment variable may do. An explicit exact=True of
expand_if_need (what a checkpoint load passes) keeps its one audited read;
the tests that compared the estimate with the exact rule pass it instead.

Per growth event the blocking reads drop from 9 to 4 (11 to 4 for a table that
never evicts): the export count, the assertion on the rehash, the reclaimed-row
count and the device synchronize of ExtendableBuffer.extend; budgets.json
takes the predicted 1.5 per step for the five growth configurations (not
measured: this tree was built without a GPU).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
flush_cache exported the cache a batch at a time and read the count of every
batch (d_counter.item(), plus the overflow region's) before it could cut the
arrays: one wait per batch of every table, 10 or more for a small cache.

Without an external storage the batches now come at full length from
LinearBucketTable._export_batches_masked, a sibling of the exact export with
the same scan of the main and overflow regions: the slots past the count are
-1, the keys past it are masked with the reserved key and the table ids are
-1, which load_from_flat, _find_keys and the masked write-back already skip, so
nothing reads a count. A storage that retains evicted keys keeps the arrays of
every batch pending until their counts land; every retain_ring (8) batches the
flush now waits for the newest count (an explicit call may) so that 16 * N
bytes per batch do not pile up behind a host that runs ahead. The values a
batch loads are bounded by FLUSH_BATCH_BYTES (256 MiB of [batch, value_dim]):
a wide row shortens the batch instead of growing the buffer. An external
storage keeps the exact-length path, since its contract takes host-sized
tensors.

The overflow export of the exact path no longer reads the device for
overflow_output_offsets_[t], which is per_table_capacity_[t] on the host.

test_flush_masked.py compares the storage (values, retained keys, the keys that
reach a tier below) with the exact flush kept in the test, with the cache's
overflow occupied, and holds the flush to zero waits (one per ring of batches
with RETAIN_KEY) and the transients to the byte budget.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
ShardedDynamicEmbeddingCollection._dedup_indices read the number of unique keys
(num_uniques.item(): a D2H and a stream sync that also drains the data-dist
stream) once per sharding per step, only to cut the unique keys, the frequency
counters and the scores to exact length, because c10d wants the split sizes of
an all2all to add up to the tensor. Those split sizes come from
bucketized.length_per_key(), which TorchRec's KJTAllToAll reads a few lines
later and caches on the KJT: the same information, read twice.

* For a sharding whose distributor takes padded arrays
  (RwSparseFeaturesDist.accepts_padded_dedup, a class attribute of the
  distributor, not a flag on a KJT), the dedup keeps its arrays at the length of
  the input, the real keys first: the unique keys, the counters and the scores
  (largest_score_per_unique_key already allows a longer result), whose tails
  segmented_unique leaves inert.
* RwSparseFeaturesDist.forward always reads bucketized.length_per_key() -- the read
  the all2all makes next, now cached for it -- and cuts to its sum whatever is
  longer (cut_to_length_per_key): the keys and weights of the bucketized KJT, the
  unbucketize_permute that the output distribution gathers with, and the scores
  before permute_scores_like_keys. The bucketize allocates its outputs at the
  length of its input and writes a prefix, so the tails hold whatever the memory
  held; nothing else sees them (construct_jagged_tensors takes the original
  features and the reverse indices in the dedup flow). Nothing is cut when the
  arrays are exact, and nothing marks a padded KJT: one that was rebuilt on the
  way is cut the same.
* A distributor of TorchRec's (a table of another sharding type next to the
  DynamicEmb ones, for instance a data-parallel one) takes exact arrays and keeps
  the read; it is the one count left in the sharded step, marked sync-ok and
  allow-listed, and the docs say so.

Tests: no_host_sync/test_dedup_padded_dist.py (one GPU, a process group of one
rank) checks that _dedup_indices waits for nothing for the padded case and still
reads for a TorchRec distributor, the cut itself, and that padded input -- with
junk in the tails, the way the bucketize leaves them -- distributes like exact
input, with and without scores and weights. per_key_score/test_per_key_score_dist.py
(two GPUs) compares a poisoned and a rebuilt run with the clean one (up to the
order of the unique keys, which the dedup kernel does not fix), checks the permute
where the bucketize makes it, and measures what the distributor is handed by its
lengths instead of the array length. The lint enforces _dedup_indices,
cut_to_length_per_key and RwSparseFeaturesDist.forward and claims the removed line.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
A sharding whose tables take a score per key sent the scores through a second
KJTAllToAll (RwSparseFeaturesDist._score_dist) on a KJT built from the keys'
lengths, without their length_per_key. For the same lengths and the same splits
as the keys' all2all it did the whole host side again, per step per sharding:
length_per_key from the device (a D2H), the splits to the device (pageable H2D
copies), a splits all2all, the exchanged splits back to the host (.tolist()),
and the recat tensor. That is DynamicEmb's design, not TorchRec's floor, which is
one length_per_key and one exchanged-splits read per all2all.

The scores are the values of a KJT with the keys' lengths, so they leave and
arrive in exactly the keys' splits. _ScoredSplitsAwaitable now waits for the keys'
splits all2all (the only one) and builds the scores' tensors all2all from it with
TorchRec's own KJTAllToAllTensorsAwaitable: the splits by label from the keys'
awaitable (the access _set_sharding_context_intra_a2a makes, the same constructor
in TorchRec 1.2 to 1.7), the keys' pg, keys, stagger and stride per rank. The scores'
KJT carries the keys' length_per_key, which forward has read already, so the scores'
awaitable reads nothing of its own. The keys' tensors are still issued before the
scores', in the same order on every rank, and TorchRec's recat and permute still do
the data movement. The second KJTAllToAll module is gone.

What is left of the scores' all2all is TorchRec's: the tensors awaitable's recat
upload and dist_init's sync of the received KJT, the same cost as the keys' own. The
smaller change, over carrying the scores as one more tensor of the keys' all2all (a
KJT subclass with its own dist_* hooks and dist_init, which would also fuse into a
train pipeline): it adds no new data path, and the data movement stays TorchRec's.

Tests: one splits all2all per scored sharding on one rank (test_dedup_padded_dist.py)
and on two (test_per_key_score_dist.py, which also keeps checking that every score
ends up beside its key and in the tables); the lint enforces the awaitable's
_wait_impl.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
_dump_table waited for the count of every 65,536-slot batch (.item()), then
for its keys, its values, its scores and its optimizer state: four to five
waits per batch, 321 for a table of 64 batches with optimizer states, and
each of them a pageable device-to-host copy.

The batches now come from LinearBucketTable._export_batches_masked at full
length with their count on the device, and pull_live_prefixes brings the
live rows to pinned host memory: the first count is read on its own, then each
batch is one copy of the first n rows of every column, which also carries the
count of the next batch (queued behind that batch's launch), and one more
batch is launched before the rows in hand are yielded, so the device works
while the files are written. One wait per batch however many columns, and the
bytes follow the keys the table holds, not the slots it scans: a table of 2**28
slots with a million keys no longer moves 4096 full-length batches. The value
rows are copied as they are (the optimizer state is split off on the host, a
strided view of the embedding columns when it is not wanted), the score columns
are put in the user's order on the host, and the age conversion of a recency
score stays where it was. The admission counter's dump uses the same pipeline.

The device clock of a checkpoint is read once per call, not once per table,
and not at all when no table evicts by recency (the storages ignore it
then); the counter's dump reads it only for a timer score.

test_dump_pipelined.py compares the files with the exact dump kept in the test
(as records sorted by key, for SGD and Adam, with and without the optimizer
state, timestamp / customized / compound scores), holds a dump to nb + 1 waits
for 1 and 8 batches, counts the elements copied (the live rows, not the slots),
and checks the order of launches and yields of the pipeline.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
Whether a table has to grow is decided without reading the device: from the newest
landed snapshot of its size plus the bounds of the batches issued after the
inserts that snapshot saw (SizeSnapshots.estimate). The estimate is documented as
"earlier than an exact check would, and never later", and the device assert on a
table's row limit relies on it never being low.

replay_increment writes keys through scatter_keys_at_slots, outside that
bookkeeping: no expand_if_need announced them, so the estimate stayed below what
the table held until the next snapshot landed (one or two prefetches), and a step
that came right after a replay could decide a growth one batch late.

_replay_state_increment, the one place both storages and every tier replay through,
adds the number of keys it wrote to snapshots.issued[table_id] (a host int on a CPU
tensor, nothing read from the device). A snapshot enqueued after the writes has the
keys and a mark with this bound, so nothing is counted twice when it lands; one
enqueued before them leaves the bound to cover them. A state that can never grow
has no snapshots and nothing to do. The replay itself still never grows a table (a
rehash would invalidate the source slots), and it may over-count keys the table
already held, which only makes the next growth earlier.

The test replays a delta into a table that can still grow and checks the bound and
that the estimate covers the replayed keys before any snapshot lands. This changes
when a table grows after a replay, which is why it is not part of the cleanup. The
growth paragraph of DynamicEmb_APIs.md names the replayed keys.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
DynamicEmbStorage.load copied every column of every 65,536-key batch to the
device from pageable memory (three to four waits per batch), filtered a
sharded checkpoint with four boolean-mask indexes per batch (four more), and
sized the table with a first pass that copied every key batch to the device
and read the count of its owned keys back (two waits per batch).

The ownership rule (key_ownership.owned_key_mask) is plain tensor arithmetic
that a CPU tensor runs as a CUDA one does, so the keys a rank does not own are
dropped on the host before anything is copied, and the owned keys are counted
on the host from the key file. Each column of a batch then crosses through a
ring of two pinned staging buffers (sync_free.StagedUpload, one per column)
with a non-blocking copy: the host reads and filters the next batch while the
device takes this one, and waits only for a buffer, when the device is still
busy with the transfer of the batch two before it. That is zero waits per
batch while the host is the slower side and at most one per ring turn when the
device is. The admission counter's load does the same, and reads the device
clock only for a timer score; the module's load reads it once per call, and
not at all when no table evicts by recency.

test_load_staged.py checks the host rule against the device rule and the
textbook rule (negative keys included), the host count, the batches against the
owned rows of the files (scores of one and two words, optimizer states), a
sharded round trip (every key lands in exactly the shard that owns it, with
its value, score and optimizer state), the counter's round trip, and that the
waits of a load of 4 batches exceed those of 1 by at most the ring's two.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
A rehash exported the old table in batches of 65,536 slots (a read of the
count per batch), asserted on the host that the insert had rejected no key (a
read per batch) and read the number of reclaimed rows before placing them: a
blocking read per batch and per table, and a table of 2**28 slots made 4,096
of each.

The key column of a table is already a padded array: an empty, a reclaimed or
a locked slot holds a reserved key (-1, -2, -3) that every table kernel skips.
So LinearBucketTable.rehash_table_from copies a chunk of the old key column as
it is (one strided copy; 2**20 slots by default), inserts it into the new
table (the reserved lanes insert nothing and report slot -1), and two kernels
move what is keyed by the slot:

* table_carry_slot_state: the value row and the reference counter of an old
  slot go to the slot its key got (reserved lanes carry nothing). It also holds
  the old assertion: a real key without a slot is a device assert, the style of
  the row limit;
* table_carry_reclaimed_rows replaces table_collect_reclaimed_rows and
  table_place_reclaimed_rows (removed) by one scan of the old slots that places
  each reclaimed row, by CAS, into a free slot spread evenly over the new range,
  as the pair did. How many rows there are is the row counter minus the live
  keys, computed on the device and never read; a second one-thread kernel
  asserts that exactly that many were found. A count of zero or below carries
  nothing, as before.

The scores come from the leading word of every old slot through
table_gather_score_blocks (the AoS accessor; a LruLfu table's other words are
copied with table_copy_score_blocks), and the rehash ends with one device
assert that the two tables hold as many live keys: an insert into a full
bucket that evicts a resident reports a slot, so only the counts see the key it
lost. A table that stores no row moves its values by slot as before: every chunk
loads the values of its live keys, the stores come after the last load.

An extension built before this change has no rehash_device_count flag and the
growth raises an error that says to rebuild; there is no blocking fallback.
Under DEMB_DETERMINISM_MODE the reserved keys other than all-ones are made that
key before the deterministic insert, which drops only that one.

Tests: test_rehash_padded.py compares every live key of a grown table with the
old table (row, every score word, reference count) for int64 and uint64 keys,
one and two score words, tables with and without rows, 0, 30 and 100% erased,
chunks of 1, 3 buckets and the whole column; a growth under no_sync of every
kind of table (HBM, host, never evicting, LruLfu, the non-rows tier of a hybrid
storage); the device asserts in subprocesses. The kernels were also run on the
CPU against the pair they replace (identical key, digest and row arrays) and
compiled with g++ and clang++ with stand-ins for CUDA and ATen.

Per growth event the blocking reads are down to the device synchronize of
ExtendableBuffer.extend: budgets.json takes the predicted 0.375 per step (3
events in the 8-step window) for the five growth configurations; not measured,
this tree was built without a GPU.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
shijieliu and others added 23 commits November 9, 2026 18:30
Two checks of test_hw_explicit_api_copies.py failed on the H100: the
strided D2H copy "blocked behind the spin kernel" (1.090 s) and
pull_to_host "did not wait" (0.000 s). Neither was the code's doing.
The first launch of a kernel in a process waits for the device under
CUDA_MODULE_LOADING=LAZY (the image's default): the strided copy needs
the kernel that makes the view contiguous, and x.add_(5) ahead of
pull_to_host was the first launch of the int64 add. The host blocked in
that launch, before the call being timed.

Probe on the H100 (CUDA 13.3, torch 2.13), a 0.5 s spin kernel then the
op, four trials in one process:
  int64 add_          0.505 s, then 0.000 s x3   (EAGER: 0.000 s x4)
  strided D2H copy    1.127 s, then 0.000 s x3   (EAGER: 0.000 s x4)
  fill_ + pull_to_host  0.506 s x4, the stream's work was waited for.
So a strided source does not block the host once its kernel is loaded,
and pull_to_host waits for the stream. sync_free and the dump code are
unchanged.

The checks now launch what they use once before the spin kernel, and
the instrument checks itself: an event behind the spin kernel must be
pending when the call starts (else the call is timed against an idle
device), and its state when the call returns is the evidence of whether
it waited. The cold variant of both checks fails at that precondition.
A control copy into pageable memory shows that the instrument sees a
wait (1.010 s). New data-integrity checks: pull_to_host returns what a
kernel wrote after a long spin (a keys tensor and a strided column
view, one call), on the default and on a side stream, and does not
wait for a stream that is not current.

GPU (H100, GPU 7): 8 passed twice; 8 passed under compute-sanitizer
memcheck with 0 errors.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
_drain_chunks sizes its per-table arrays (wanted, counts) by the number
of tables of the state and indexes them with the table id of every row
(wanted[tids.clamp(min=0)], scatter_add_ over the ids). A row whose id
is not below num_tables is a device-side assert ("index out of bounds",
IndexKernel.cu), which poisons the CUDA context and aborts the process:
on the H100, test_pop_dedup_and_table_id_filter appends (key 6, table 1)
to a one-table storage and the first pop died at
key_value_table.py:2808 (CUDA_LAUNCH_BLOCKING=1 names the gather).

The old pop compared tids == table_id, so any id was a table, and the
plain-Python reference of test_pop_one_pass.py is written for any id;
its generator only drew ids below num_tables, so the pass was never
tried with one outside. The pass now covers the tables asked for as
well as num_tables, clamps an id into the arrays wherever it indexes and
counts a row as wanted only when its id is one of them: a row of a table
past the state stays, like the row of any table not asked for, and a
table past the state can be popped. A negative table id (wanted[-1] is
the last table) is refused with a ValueError. _pop_chunked_keys_to_host
walks the counts rather than state.num_tables.

New tests in test_pop_one_pass.py: the pass against the reference with
ids 2, 5, 7 in a two-table state and tables asked for past it (int64 and
uint64, CPU and GPU), the negative id, and pop_many of a table the
storage has no table for. On the pre-fix code they fail (14 CPU variants,
and an IndexError at the storage level); the CUDA variants would abort.

GPU (H100): test_insert_collect_evicted.py now 100% green including the
test that aborted; test_pop_one_pass, test_lazy_retain, test_pop_evicted_keys,
no_host_sync lint/audited-read/explicit-API tests: 625 passed, 1 skipped,
3 xfailed; incremental_dump 57 passed (one process), the one-rank
torchrun runs of test_distributed_dynamicemb (16 passed, 1 skipped) and
test_distributed_pop_evicted_keys (1 passed).

Also isort's order of one import of key_value_table.py.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
The wait counts of "What the explicit calls wait for" are per call or per
batch. They leave out one wait that is not the API's: with
CUDA_MODULE_LOADING=LAZY (the default) the first launch of a kernel the
process has never launched can wait for the device while its module is
loaded. On the H100 (CUDA 13.3, torch 2.13) a kernel launched for the
first time behind a 0.5 s kernel returned after 0.505 s, the next
launches at once, and with CUDA_MODULE_LOADING=EAGER the first returned
at once too. It is at most once per kernel and process, so the first call
of an explicit API may pay it. It is what made two hardware checks of
test_hw_explicit_api_copies.py look like waits of the code.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
The module docstring tells the reader to run the hardware checks under
compute-sanitizer; in the CI image the tool is
/usr/local/cuda/bin/compute-sanitizer and is not on the PATH, so the
command as written fails with "command not found". On the H100 (GPU 7)
the checks pass under it: 8 passed, ERROR SUMMARY: 0 errors.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
The cold-launch artifact behind the two hardware checks (the first launch
of a kernel waits for the device under CUDA_MODULE_LOADING=LAZY) is also in
the tests that queue a long kernel (torch.cuda._sleep) and count on the work
behind it staying in flight. Run alone, each in a fresh process on the
H100, three tests of test_lazy_retain.py failed:

  test_a_full_ring_loses_no_entry                  1 pending entry, not 4
  test_entries_without_a_ticket_are_retried_...    [False], not [False, True]
  test_a_pop_on_a_side_stream_takes_the_arrays_... [False], not [False, True, True]

The first launch of the append (its count: (tids >= 0).sum()) waited for the
spin kernel (0.282 s behind one of 0.25 s in a probe), so the first count had
landed before the next entries were made. They pass in the file only because
tests before them have loaded the kernels: an order dependency that -k, a
sharding or a reorder breaks. Two more passed alone without testing anything
(the pop on another stream had nothing in flight to order itself after:
test_a_pop_on_another_stream_than_the_appends and
test_pending_entries_of_another_stream_are_popped_in_order), and so would the
erase-count test (the worker's cold launch waited for the long kernel, so the
copy of the counts was ordered behind work that was done).

test_lazy_retain.py and test_pop_one_pass.py load what an append and a pop
launch once per module (autouse fixture, int64 and uint64 keys), the erase test
launches its update once first, and the tests that need work in flight check
an event behind it is still pending when the pop starts; the assertions about
the pending entries say what a failure means. Production code is unchanged.

GPU (H100): each of the 7 tests (9 cases) passes alone in a fresh process; with
the warm-up taken out the same checks fail (the preconditions catch the two
vacuous ones); the lane A/B single-GPU files together: 341 passed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
check_zero summed per_iter_total, which holds the allocator events (kind
'al': cudaHostRegister of a host-buffer growth, cuMemCreate / cuMemMap /
cuMemSetAccess of a wide device buffer, a cudaMalloc in a step) next to
the syncs. The growth lane classifies those as 'al' on purpose and the
ratchet bounds them apart (ALLOC_EVENTS_MAX + ALLOC_EVENTS_PER_GROWTH per
growth), so the first strict run of the merged tree on an H100 failed
nine configs that read zero blocking syncs: cache_ps, cache_ps_sum,
cache_storage_growth, host_only_growth, cache_storage_noevict,
host_only_noevict, hbm_only_growth_wide, host_only_growth_wide and
hbm_only_noevict_wide (32 cases, 0.12 to 0.88 allocator events a step,
"top site extendable_tensor.py:227:extend").

The probe now records a per_iter_blocking series (ss, ds, es, ms and pd,
merged with the python-visible syncs the way the total is) and
mean["blocking"], the metric of the budgets, is its mean. check_zero, the
--compare count of cases that "still make a blocking sync outside
INHERENT", the pivot, the report table and the --assert-zero summary read
it; the table gains a blk column beside tot, and al stays the ratchet's.

The excuse of a call site follows: it counts the blocking events of the
site only, so an allocation at the stand-in's site is not an excused sync,
and check_zero subtracts it per iteration and never below zero, so that
neither an allocator event nor the excuse of one iteration can pay for a
sync of another. The top site of a violation is a site that blocks, not
the allocator site that has more events, and the ranking of call sites in
the report lists the sites that block first and marks the ones that only
allocate "(alloc)". A report saved before this series existed (--diff,
--render) is read from its per-kind series.

Evidence: the old check_zero on the census of the merged tree
(556 cases, H100) names 32 cases of those 9 configs; the new one names
none. On a fresh census of the tree with the hybrid_growth fix (556
cases) the old one names 34 cases in 10 configs and the new one none, and
--assert-zero exits 0. The eight new CPU tests in
test_host_sync_probe_unit.py (an iteration that only allocates, each
blocking kind beside allocations, the top site, an excused site that
allocates, the per-iteration excuse, the old report format, the
comparison, the table and pivot) all fail on the old probe.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
test_a_growing_step_returns_while_a_running_kernel_has_not_finished
failed for hybrid_growth on the first hardware run: "no table grew in the
window: capacity before={hbm: [4096, 4096], host: [2048, 2048]}
after=same". The plan said the host tier grows because the estimate of a
batch counts all of its keys. Since the growth lane the estimate is the
host tier's own size, read back at the last forward (SizeSnapshots), plus
the bound of the batches in flight, which a step that ends in a barrier
leaves empty. The host tier holds what the HBM tier spills and nothing
else, and an HBM tier of 4096 rows a table took every key of the window,
so the host buffer's growth was never exercised, in the census or in the
test. (The miss case of hybrid_growth ran with that HBM tier at a load of
0.93, which the regime check flags too: a miss is to go into a tier that
is not full.)

The growth scenario now gives the HBM tier one bucket a table (1,024
rows) and fills it with whole warm-up batches (growth_warmup_scale), so
every new key of the window moves one into the host tier, whatever the
growth of the warm-up (the batches in flight) has made of its capacity.
all_hit and miss keep a roomy HBM tier (8192 rows): a miss there is a miss
into a tier that is not full. test_no_host_syncs builds the same warm-up.

Evidence (H100, GPU 4 of eos0449, 8 iterations): the growth case of
hybrid_growth had capacity hbm [4096, 4096] -> same and host [2048, 2048]
-> same. Now hbm [1024, 1024] -> same and host [2048, 2048] -> [8192,
4096] (host sizes [11, 0] -> [2771, 868]): three growth events, 3
allocator events (iterations 2, 5 and 6), 0 blocking syncs in all eight
iterations, in plain and in prefetch mode; the miss case reads zero at an
HBM load of 0.46. The capacity the host tier has when the window starts
depends on how many batches of the warm-up were still in flight (2048
here, 4096 in another run of the same tree): the window grows it from
either, by one doubling at least (4096 -> 8192 in that run). Both
test_a_growing_step_returns_while_a_running_kernel_has_not_finished[
hybrid_growth-plain|prefetch] pass: the growth of the host tier returns
before a 0.3 s sleep queued ahead of it has ended.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
Only queue_ahead was held to its regime: check_zero turned a failed
regime into a violation there and kept it as a flag in the report for
every other scenario. A zero is a statement about a scenario (a table
grew, a tier evicted, a miss was a miss), so a case in which the scenario
did not happen says nothing, whatever its count. The first census of the
merged tree had four such cases, all of hybrid_growth (the growth case,
in which no table grew, and the miss case, at an HBM load of 0.93): they
read zero and test_no_host_syncs[hybrid_growth] passed; only the separate
hardware test of the growing step noticed the growth case, and nothing
noticed the miss case.

check_zero now reports a failed regime of any case, INHERENT ones and
cases that also sync included (both are listed), with a hint at what to
fix; --assert-zero exits 1 on it.

Evidence: on the 556-case census of the merged tree this check_zero
names exactly those four cases and nothing else; on the census of the
tree with the previous commit it names none: every one of its 556 cases
happened as named. A new CPU test covers every scenario, an INHERENT
case, and a case that fails its regime and syncs.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
The regime checks judged from the size of the tiers before and after the
window. For tier2_hit that says that no key was added below the top
tier, not that the keys of the window miss it, and the layouts with a PS
had no check at all ("no backing-tier occupancy check for layout
cache_ps"); all_hit and eval said that nothing was added, not that the
batch was resident; miss_evict looked at the first table only.

run_case now asks every tier, before the window, which of the unique keys
of the measured batches it holds (tier_residency: a lookup with the CONST
policy of an eval, which scores nothing, on the key map of the cache, the
storage, both tiers of a hybrid and a device PS; a membership test on a
dict PS). all_hit and eval need the top tier to hold at least 95% of them,
tier2_hit at most 5% of them while a lower tier holds 95% (the PS for one
table and the storage for the other in cache_ps). Where nothing can be
asked (an older tree) the size checks stand. miss_evict checks both
tables.

It found a case that did not measure what its name says. Under LFU
eviction every key had been counted once, so the pool kept its place in
the top tier among ties: hybrid_lfu's tier2_hit window found 22% (table 0)
and 74% (table 1) of its keys in the HBM tier, top-tier hits that read
zero as tier-2 hits. The keys that push the pool out now count four
(frequency * 4).

Evidence (H100, GPU 4 of eos0449): before the window, the share of the
measured keys in the top tier / in a lower tier, hybrid_lfu tier2_hit:
0.22, 0.74 / 0.78, 0.26 before the change (a throwaway run of the same
setup), 0.0, 0.0 / 1.0, 1.0 after. In the 556-case census all 241 cases
the check applies to hold it: 132 all_hit and 51 eval cases at 1.0 in the
top tier (admission, uint64, mixed dim, device PS included), 58 tier2_hit
cases at 0.0 in the top tier and 1.0 in a lower one -- except cache_ps and
cache_dps, where table 0's keys are in the PS (1.0) and table 1's in the
storage (0.99) -- and miss_evict passes for both tables in all of its 110
cases. Three new CPU tests cover the regimes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
The strict lint gates failed on the merged tree in three places.

DynamicEmbCache.lookup and expand_if_need_impl are below their
LEGACY_BASELINE ("sync-call 0 < 1"; "blocking-copy 0 < 1, pin-memory
0 < 1"): their violations went with the lanes that rewrote them. They are
clean, so their baseline entries go and they are enforced like the
functions that are new (Target(..., on_main=True, enforce=True)), as the
module documents for a target whose package has landed.

SYNC_LINT_FINAL=1 found 25 lines of lint_baseline.json gone from the tree
and claimed by no change. They are claimed now by the commit that removed
each, found with git log -S over d03198c..HEAD: 685bbfd (11 lines: the
pinned-copy helpers of the dedup count), ba6f90d (2), e76b706 (3),
1088d81 (4), 119d8e5 (2), 99b014e, e88872b and a02eee5 (one each).

Two of those name a line that the baseline had twice and the tree has
once (incremental_dump.py `sizes = [int(s.item()) for s in size_list]`,
key_value_table.py `num_tables, dtype=torch.int64, pin_memory=True`), so
"the claimed line is still in the tree" could not hold for them either
way. claims_still_present takes the baseline now: a claim that names one
line (the same for every copy) stands when the tree has fewer copies than
the baseline had. A claim that is a prefix of several different lines of
the baseline keeps the strict rule. A new CPU test covers both.

Evidence: SYNC_LINT_STRICT=1 SYNC_LINT_FINAL=1 SYNC_LINT_REQUIRE_NEW=1
passes (323 passed, 3 xfailed). What remains under
SYNC_LINT_ENFORCE_ALL=1, which is not one of those gates: the three legacy
targets that keep a baseline because a host count is their contract --
LinearBucketTable.insert_and_evict (scored_hashtable.py:1027) and
insert_and_evict_with_counter_and_overflow (:1544), the async_count=False
branch that hands the public API a host count, and
MultiTableFrequencyAdmitter.admit (embedding_admission.py:323),
flagged_compact for a counter that did not declare the padded contract.
Flipping them takes a `# sync-ok: <why>` on those lines in production
code, which this change does not touch.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
The strict ratchet failed for cache_ps and cache_ps_sum: their cells
still held the numbers of the tree before the removal (18 / 21 / 18 blocking
syncs a step for a miss, a miss with evictions and a hit on the second
tier) and the merged tree measures 13 / 15 / 12 (all of them at the two
call sites that the old-contract PS excuses: sync_free.read_now and the
PyDictStorage stand-in's own file; an all-hit step was at its 1 already).
Lowered with sync_budgets.py --from-report: 12 cells, nothing else
changes. The note in _meta that five growth configs and five new ones were
"claims, not measurements" goes with it: a census has measured every one of
those configs, all cells at zero, and the tool drops the note when it
does.

Evidence: 556 cases (the probe's case_keys, so budgets.json covers
exactly what the probe measures; sync_budgets.validate() reports nothing)
from a census of nhs2-int ab82788 with the changes before this one, on an
H100 (GPU 4 of eos0449; 8 iterations, warm-up 3, seed 1234): 540 cases
read zero blocking syncs, among them every growth, determinism, chunked
and device-PS case and the hybrid growth cases of the previous commits;
the 16 others are the cache_ps cells above. --assert-zero exits 0 (every
regime held). With these budgets the strict set of test_sync_ratchet.py,
test_no_host_syncs.py and test_sync_free_lint.py (HSP_ASSERT_ZERO=1
HSP_RATCHET_STRICT=1 SYNC_LINT_STRICT=1 SYNC_LINT_FINAL=1
SYNC_LINT_REQUIRE_NEW=1) passes on the same GPU: 487 passed, 3 xfailed (the
three legacy lint targets in report mode), nothing failed or skipped.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
test_multi_spill_keeps_the_keys_of_the_call asserted
table.overflow_bucket_sizes == [30, 30] "after the first call", but
spill_sequence(key_type, 2) runs both calls before it returns, so the table was
read after the second. The kernel was right and the test was wrong.

The account of the 41 that H100 reported: after call 1 each overflow bucket
holds 30 spills (an empty 48-slot bucket, every spill takes a free slot). Call 2
brings 30 more per table into a bucket with 30 unpinned residents and 18 free
slots; a spill takes the first slot of its scan that is not held by an earlier
spill of the call, so 11 of the 30 reached a free slot (INSERT) and 19 evicted a
resident of call 1 (EVICT): 30 + 11 = 41, per table, both key types. A CPU
model of overflow_insert_and_evict (fmix64 hash, scan from hash % 48, slots a
spill took skipped) gives the same 11 and 19, and so do the per-call results on
the GPU.

spill_sequence now returns a snapshot of the overflow sizes after every call
and the test asserts [30, 30] on the first and 30 + INSERTs on the second. The
rest of the test (never reached before) passes unchanged.

Evidence (H100, GPU 6): test_sorted_insert.py 270 passed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
test_a_checkpoint_load_is_deterministic dumped a table that had been given keys
1..128 and then required the loaded table to find all 128. The table has 128
slots per logical table in 8 buckets of 16, and the hash puts 17, 18 and 18 of
those keys into three buckets: the source table (inserted without the mode, by
the ordinary kernel, whose evictions race) lost five of them (27, 40, 52, 56,
64) before the dump, so the file held 123 keys and no table of this geometry
can hold 128 of them.

The load in DEMB_DETERMINISM_MODE loses nothing. Same file, GPU 6: without the
mode the loaded table finds 123 of the 123 keys of the file with bucket sizes
[15, 14, 15, 16, 16, 15, 16, 16]; with the mode it finds 123 of 123 with the
same bucket sizes.

The test now gives the source 64 keys (at most 10 per bucket of 16), checks that
the file holds exactly those 64, and looks for the keys of the file in the
loaded table, with the score the file holds. Two loads still build one storage.

Evidence (H100, GPU 6): test_determinism_mode.py 26 passed, 4 skipped (the
insert x async_count combinations that do not exist).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
First run on an H100 (Eos, GPU 5): test_rehash_padded.py, test_growth_order.py and
test_growth_hooks.py had 17 failures. 16 were faults of the tests, none of the code
they exercise; the 17th (the temporaries bound of the rehash) is the next commit's.

* test_rehash_padded.py: lookup() asked every table for the score named "s", which
  is the name of a table made by get_scored_table. A table of create_table_state
  names its score by its strategy, so ValueError "'s' is not in list" ended 12
  tests (test_a_growth_reads_nothing_back x5, test_values_follow_their_keys_across_
  chunks x4, the three staging tests) before they grew anything, among them the
  ones that carry the claim that a growth reads nothing back. It asks the table
  for its own name. The two device-assert tests ran a helper that added to a
  uint64 CUDA tensor, for which this PyTorch has no kernel ("ufunc_add_CUDA" not
  implemented for 'UInt64'): it builds the scores as int64 and converts.
* test_growth_order.py::test_flush_orders_the_storage_below_the_cache_after_its_
  growth: its stand-in for a cache lacked value_dim and emb_dtype, which the batch
  sizing of flush_cache (the contract lane) reads. It has them.
* test_growth_hooks.py: note_replayed and pop_many, added by the api and step
  lanes, are listed as needing no order, each with its reason from what it
  touches: note_replayed adds a host int to the size estimate (host bookkeeping
  and the pinned ring of snapshots), pop_many drains the retained key arrays that
  earlier inserts made and orders the current stream after the streams that made
  them, like pop_evicted_keys and pop_erased_keys. find_masked and insert_masked
  already carry @_after_growth.

Evidence (GPU 5): test_rehash_padded.py 93 of 94 pass (the last, the temporaries
bound, is the next commit's), test_growth_hooks.py 5 of 5, test_growth_order.py
14 of 14. The claim of the first group is real: with a torch.cuda.synchronize()
put back into both extend methods, test_a_growth_reads_nothing_back fails for
hbm_rows, host_rows, lru_lfu_rows and hybrid_host_tier ("host sync outside
sf.read_now: torch.cuda.synchronize"); no_eviction grows its key map only and
extends nothing.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
test_the_temporaries_of_a_rehash_are_those_of_one_chunk_not_of_the_table[chunk_2e14]
failed on the first GPU run: the rehash of a table of 2**22 slots peaked at 4.85 MB
above its two tables, where a chunk of 2**14 slots weighs 0.92 MB.

The code was wrong, not the bound. Tensor.sum() of the int32 bucket_sizes first
copies the whole operand as int64, 8 bytes a bucket (measured on this PyTorch,
2.13: sum() of 2**19 int32 peaks at 4,195,840 bytes, sum(dtype=int32) at 1,536).
A rehash did that twice -- the final comparison of the live counts of the two key
maps (over the new one) and the count carry_rows_from takes (over the old one) --
so its peak above the tables was a chunk's temporaries plus 8 bytes a bucket of
the table: 4 MiB here, 64 MiB for a table of 2**30 slots in buckets of 128, in the
event that runs when device memory is tight, and against the claim of the design
that a rehash holds the temporaries of one chunk and nothing that grows with the
table.

sum_bucket_sizes adds runs of 4096 buckets as int32 (exact: a bucket holds at most
its capacity) and only the sums of the runs as int64: four launches, nothing read
back, temporaries of 12 bytes a run.

Evidence (H100, GPU 5), peak above the tables for a rehash of 2**22 slots, before
and after, by chunk size in slots:
  2**12: 4,359,680 -> 229,376      2**14: 4,851,200 -> 917,504
  2**16: 6,817,280 -> 3,670,016    2**18: 14,681,600 -> 14,680,064
It is now 56 bytes a slot of the chunk with no term in the table (the comment said
about 40; the fixed 4 MiB of the sum hid the real slope), and carry_rows_from
peaks at 2,048 bytes instead of 2,098,688. The bound of the test is unchanged and
the test passes for both chunk sizes. New tests: sum_bucket_sizes is exact against
the int64 sum for 0, 1, 4095, 4096, 4097, 12293 and 2**19 buckets and its peak is a
few KiB.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…o not

test_vmm_tensor.py::test_host_buffer_grows_in_place failed on the first GPU run
with "CUDA error: invalid argument" at a copy_ over a host buffer that had grown
past 20 pieces; gate E2 (b) failed the same way over 1000.

Root cause, from CUDA_LOG_FILE=stderr on an H100 (CUDA 13): the buffer is
registered with cudaHostRegister one piece per growth, and the driver checks the
range of a cudaMemcpy* against the size of the registration its pointer is in:
  [CUDA][E] Copy is larger than memobj size, for destination operand
  [CUDA][E] Returning 1 (CUDA_ERROR_INVALID_VALUE) from cuMemcpyDtoDAsync_v2
(and "for source operand ... from cuMemcpy" for a device to host copy). cudaPointer-
GetAttributes agrees that the pieces are what the design says -- type host, the
device pointer equal to the host pointer, contiguous -- so HostVMMTensor is right and
nothing is wrong with the registration. Measured over 2 and over 21 pieces:
  work across every boundary:  kernels (add_, fill_, index_copy_, a gather, cat, sum),
                               a memset (zero_)
  work inside one piece:       copy_, one copy per piece of the same range
  refused across a boundary:   copy_ into or out of the range, clone, cpu
The refusal is at the call, nothing is written, and the context and the buffer stay
usable.

What was wrong: the test said "one kernel over the whole buffer" and used copy_ and
clone, which are copy engine operations. It now uses kernels, and a new test pins the
rule down (kernels, a memset and a copy inside one piece work across any number of
boundaries; a copy across one fails cleanly with "invalid argument", and skips if a
future driver follows it). The production code is not affected: the library reads
and writes the value rows only with kernels through the pointer table (no cudaMemcpy
over a value buffer in src/, nothing but data_ptr() and shape of tensor() in the
package). But it is a limit the old buffer, registered whole, did not have, and
nothing said so: HostExtendableBuffer, vmm_tensor.cu and DynamicEmb_APIs.md now do,
with what to do instead (a copy per piece, or a kernel).

Evidence (GPU 5): test_vmm_tensor.py 42 passed, 2 skipped (they need two GPUs), with
the new test.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
Gate E3 (the loop of the prefetch pipeline: forward on one stream, prefetch of the
next batch on another, backward, with random sleeps) crashed on the first GPU run in
every layout within one epoch of 48 steps: an illegal memory access, a device assert
in table_resolve_rows_kernel ("slot < main_capacity"), an illegal instruction. The
negative control crashed the same way, so the gate looked blind.

Not a growth bug. The same loop on a table that cannot grow (init_capacity 2**20,
96 steps) crashes in all four layouts, and the lane's order (H1-H3) is not involved.
What decides it is the allocator:
  PYTORCH_NO_CUDA_MEMORY_CACHING=1 (nothing is reused): 4 of 4 layouts pass;
  default: 4 of 4 crash;
  every tensor of the PrefetchState recorded on the forward stream: 4 of 4 pass, with
  and without growth (8-10 rehashes in 96 steps).
GPU core dumps (CUDA_ENABLE_COREDUMP_ON_EXCEPTION, read with cuda-gdb) name the
victims: table_lookup_kernel "Warp Out of range Address" at the digest read of a
bucket, load_from_flat_table_kernel_vec4 "Warp MMU Fault" -- kernels reading a key, a
slot or a row of some other batch. compute-sanitizer reports nothing (it slows the
kernels past the race), CUDA_LAUNCH_BLOCKING=1 passes.

Cause: dynamicemb_prefetch makes the unique keys, reverse indices, slots, rows,
masks and counts on the prefetch stream; the forward and the backward read them on
the forward stream. The host drops them once the backward has been queued, which is
when the caching allocator hands their blocks back to the prefetch stream, whose next
prefetch writes into them while a late backward is still queued behind other work. The
function takes forward_stream and has never used it (on main either), and nothing
recorded the tensors. record_prefetch_state_on records every device tensor of the
state on it: the block is not reused before what is queued on the forward stream at
the free has run. A few record_stream calls per prefetch.

Tests: test_the_tensors_of_a_prefetch_are_not_reused_while_the_forward_stream_may_
read_them lets go of a prefetch while the forward stream sleeps and allocates what the
next prefetch would (no block comes back), and its control, with the recording taken
out, does get a block of the prefetch back, so the test can tell. Gate E3 after the
fix (GPU 5, 5000 steps in balanced epochs): hbm_no_eviction 420 rehashes, hbm_evicting_
with_erase 525, host_only 525, hybrid 420, all pass (peak +2.4/+2.4/+2.3/+1.5 MiB
allocated); with the order switched off (H1, H2) the control fails in all four, which is
what it is for: an illegal memory access, "a reference counter is not back at zero: a
decrement was lost", a device assert on row_limits, a device assert.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
First GPU run: E1 failed 8 of 20 variants on its bound of 10 ms for the 99th
percentile of an extend (40-150 ms when the running kernel is memory bound or 64 MiB
is mapped: the driver's mapping and zeroing compete with it for bandwidth), E2 (a)
failed one iteration of 40 as "returned only after kernel A finished" although the
call took a median of 47 ms (p99 360 ms), so a slow call can span the end of a 100 ms
kernel by coincidence, and E2 (b) died with cudaErrorInvalidValue. Every E1 variant
had blocked=0.00%: nothing had waited for the device.

Waiting and slowness are now measured apart.
* Wait runs: kernel A is 1.8 s, far longer than any extend (kind sleep: one
  torch.cuda._sleep; kind memory: a train of add_ over a 4 GiB buffer, 900 launches
  at most, which a stream can queue), a synchronize after every iteration. A call is
  BLOCKED when it returned after A had finished, or took more than half of what A had
  left when it was called. PASS: at most 1% blocked. Latency (median, p99, max) is
  printed and is not a criterion.
* Data runs: kernels of 50 ms (E1) / 100 ms (E2), many iterations, no synchronize in
  between. PASS: no CUDA error, every old element has had each of A's adds exactly
  once, every tail holds what a kernel on another stream wrote right after the extend
  that made it. How often a call returned after A is printed as information only.
* Controls: GATE_E1_SYNC=before (a synchronize before the timed extend) and inside (in
  it) wait by construction and must show every iteration blocked, or the gate cannot
  see a wait.
* E2 (b) fills and checks with kernels: the old copy_ was a cudaMemcpyAsync, which the
  driver refuses across two registered pieces (see the commit on test_vmm_tensor.py).
  That refusal is printed by (f), a test of its own, because compute-sanitizer reports
  it as an API error and would fail the memcheck run of (b).

Results (H100, GPU 5), kernel A about 1.8 s:
  E1 wait, 12 variants (grow 2, 6, 64 MiB; memory and sleep; alone and with a second
  launching thread), 12 iterations each: blocked 0.00% in all. extend median 0.07-4.8
  ms, p99 0.6-134 ms (a driver call under bandwidth contention, not a wait: 7% of A).
  E1 data, 12 variants, 100 iterations each: pass, no CUDA error, data exact.
  E1 recorded loop of test_vmm_buffer without its synchronize, device and host, four
  initial sizes: 8 of 8 pass (device stops at the reserved VA range, host at its
  reservation).
  E1 under compute-sanitizer memcheck (data runs, grow 6 and 64 MiB, 40 iterations),
  candidate and control with the synchronize: 0 errors in both.
  E2 (a) wait, 64 MiB, 12 iterations: blocked 0.00%, median 45 ms, p99 332 ms (pinning
  the pages: touch, mlock, registration, O(delta), no wait). (a) data, 40 iterations: pass,
  data exact. (b) 1000 growths, 1000 piece boundaries, address stable, kernels exact
  across all of them. (c) random gather of 1 GiB: one registration 204.8 ms, 20 pieces
  165.8 ms, ratio 0.81 (limit 1.05). (d) 128 tables of 64 GiB reserved (8192 GiB
  VmSize). (e) cudaDevAttrCanUseHostPointerForRegisteredMem = 1. (a) data and (b) under
  memcheck: no invalid access; the only reports are the intentional refused memcpy.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…verdict

Two faults of the gate itself, found when it ran for the first time.

* 5000 steps in epochs of 48 left a last epoch of 8. The host tier of the hybrid
  layout sits behind an HBM tier of 2048 rows and does not fill, so does not grow, in
  so few steps, and the gate failed with "no table grew: the epoch did not exercise a
  growth". Epochs are now of nearly one size, none longer than GATE_E3_EPOCH_STEPS.
* A CUDA fault (an illegal access, a device assert) leaves the context unusable and
  its tensors cannot be freed: the destructor throws and the process aborts, before
  the verdict is printed. After a fault the harness frees nothing, prints the verdict
  (E3 FAIL, or E3 CONTROL ... sensitive) and ends the process there, with 1 for a
  failed run and 0 for a control that saw what it is for.

Results (H100, GPU 5), with the prefetch hand-off fixed (the commit before the
gates): the run of 5000 steps in 105 epochs passes in all four layouts,
  hbm_no_eviction          420 rehashes  peak +2.4 MiB allocated, +6.0 MiB reserved
  hbm_evicting_with_erase  525 rehashes  peak +2.4 / +8.0 MiB
  host_only                525 rehashes  peak +2.3 / +6.0 MiB
  hybrid                   420 rehashes  peak +1.5 / +4.0 MiB
in 78 s. The negative control (GATE_E3_DISABLE_ORDER=1, H1 and H2 off, 1000 steps, one
process each) fails in all four, which is what it is for: hbm_no_eviction "illegal
memory access" (printed as sensitive); hbm_evicting_with_erase "a reference counter
is not back at zero: a decrement was lost" (after 15 rehashes); host_only and hybrid
die on device asserts (row < row_limits[tid] in table_resolve_rows_kernel, and the
rehash's count check) in the library, before the harness could print.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
A line broken in the middle of a sentence by the previous edit of the figures.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
On an H100, against the tree before the lanes, the count-free rehash is 1.7 to 5
times faster from 2**20 slots on (2**20: 2.0 against 3.4 ms, 2**22: 3.7 against
10.7 ms, 2**24: 19 against 40 ms) because it no longer reads a count per batch
of the export. For 2**16 and 2**18 slots it is slower by 0.4 to 4.6 ms, a fixed
cost of about a dozen more launches, which a ratio alone called a regression.
The gate now fails a case only if it is slower by more than the ratio AND by
more than 6 ms.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
The temporaries of a rehash are 56 bytes per slot of a chunk and nothing that
grows with the table (measured on an H100; the text said about 40), and the
rehash of a growing table reads nothing in DEMB_DETERMINISM_MODE either.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
shijieliu and others added 2 commits November 9, 2026 21:08
…e node

The first E4 measurement ran while other suites shared the node and showed the small
tables a few milliseconds slower than the rehash they replace. Three runs on an H100
node with nothing else running, within 3% of each other, show the count-free rehash is
not slower at any size: 0.85 ms against 0.9 at 2**16 slots, 0.74 against 3.3 at 2**20,
1.4 against 10.7 at 2**22, 4.4 against 40.5 at 2**24. The docstring and the comment of
MAX_ADDED_MS say so; the 6 ms allowance stays as a guard against a busy node.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
… opens

Nine tests failed when run alone and passed in their files: three in
test_sync_free_helpers.py (an enqueue behind a busy stream, the event of a copy made on a
side stream, the poll gate) and six in test_check_scores_late.py (the negation of the
scores under a sleep). Under CUDA's lazy module loading the first launch of a kernel waits
for the device, so a kernel that the window launched for the first time made the host wait
out the sleep, and every answer the test expected to be in flight had landed. Each test now
launches that kernel once before the stream is made busy. Every test of both files passes
alone (162 of 162 on an H100) and the files pass whole (139 and 23).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
@shijieliu shijieliu changed the title perf(dynamicemb): no host syncs in the lookup of a training or eval step perf(dynamicemb): remove the host syncs of DynamicEmb (lookup, growth, determinism mode, explicit APIs) Nov 10, 2026
…id not run

clear_measured_claims dropped the "unmeasured" note of a config when every result the
report held for it was ok, without asking whether the report held every case of the
config. A census made with --scenarios all_hit --modes plain therefore marked a config as
measured while its miss, eviction, eval and prefetch cells kept budgets that were only
claims, and the later budget check cannot see that. A config now counts as measured when
every case the probe measures for it (case_keys(), or the `expected` argument) is in the
report and ok. Found by the Greptile review of the pull request.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant