Skip to content

perf(dynamicemb): a table that can still grow reads the device only when it may have to expand - #546

Open
shijieliu wants to merge 14 commits into
NVIDIA:mainfrom
shijieliu:enh-dynamicemb-sync-free-prefetch-vmm
Open

shijieliu wants to merge 14 commits into
NVIDIA:mainfrom
shijieliu:enh-dynamicemb-sync-free-prefetch-vmm

Conversation

@shijieliu

@shijieliu shijieliu commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Second of two PRs, stacked on #545 (the lookup step with the number of unique keys on the device). Until #545 merges, GitHub lists its commits here too: the change of this PR is the last 4 commits (the growth decision, a benchmark flag, the tensors of a prefetch, the correction of the size estimate). Based on main 476cdc0 (#539, #540, #544, #547) and on #545 at bccf650b.

This replaces the first version of #546 (device-side growth with VMM pages, pinned rings, growth ordering). In my benchmark that design made the tables that can grow slower, and tables reach the size of the data and stop growing, so it is not here. What is left is the small part that is worth doing.

The problem

After #545 a table of fixed capacity makes no blocking host sync in a step. A table that can still grow (init_capacity below max_capacity, or NO_EVICTION) still read the number of unique keys of the batch back from the device at every step, to decide whether to expand: one blocking sync per lookup group and step, however far the table was from its limit.

The change

  • The host keeps, per table, an estimate of its size that can only overcount (it exists already, for the growth decision). A step now adds to it the number of input keys N of the batch, a bound the host knows (it does not know how they split over the tables), in place of the number of unique keys U, which it does not.
  • Storage.may_expand(bound) says, from the estimates alone and without touching the device, whether the batch might make a table grow. If not, accumulate_bound(bound) counts the batch and the step makes no blocking sync. If so, the step reads the per-table unique counts from the device as before, expand_if_need(unique) (unchanged) decides exactly, and the estimate becomes the real size again. The read is made before the table gate, not inside it.
  • The estimate is brought back to the real sizes without waiting (the last commit; the "delayed" correction of perf(dynamicemb): a lookup step without host syncs (arrays at the input length, the count on the device) #545 again, with DelayedCopy). The estimate grows by N where a table grows by U, so left alone it would come close to a limit long before the table does, and the step would then wait at every step. When the estimate is within four batches (4N) of a limit, a batch that is done (after its backward, or after its no-grad forward) has the sizes of the tables copied to pinned host memory, without waiting; once the copy has landed, the next check lowers the estimate by what it had counted beyond those sizes. Farther than 4N from a limit nothing is copied, and at most one copy is on its way at a time. What keeps the estimate above the real size:
    • A batch is open from the moment it is counted until it is done (open_batch / close_batch): its keys may not all be in the table yet. The correction lowers the estimate by max(held - sizes, 0), where held is the estimate at the time of the request less the bounds of the batches that were open; those bounds stay, and so do those of the batches counted since. This holds whatever the order in which the backwards run. A simpler token, the estimate at the prefetch, does not: a model of the protocol (it is not part of the PR) found 570 runs in 6000 where the estimate fell below the real size with it, and none in 12000 with the open bounds, erases, rebases and out-of-order backwards included.
    • The correction is void if the estimate was set from the device in between (a confirmation, a checkpoint load: estimate_generation).
    • A table that was expanded since the batch was counted asks for no sizes (key_map_generation): the key map that a later prefetch made, on its own stream, is not ordered after the stream of the batch that is done. The tensors the size kernel reads are also recorded on the stream of the copy (record_stream). A review of the commit found that race.
  • A copy of the sizes that the device may still be writing into the estimate (queued at the start of a prefetch when a checkpoint load or a confirmation left the estimate stale) is never raced with: while it may be in flight, may_expand says yes, and the read of the unique counts is the wait. A review of the first version of this change found that race (the estimate could fall below the real size and a table grow late); there is a regression test, and it fails when the fix is taken out.
  • A storage that has expand_if_need but not may_expand (a class a user wrote) is asked at every step, as on main.
  • A copy of a module (copy.deepcopy, pickle) starts without a copy of the sizes on its way, as it does without the gate of an erase.
  • --init-capacity-ratio in benchmark_many_collections.py, to benchmark tables that can still grow.
  • A prefetch records its tensors on the forward stream (record_prefetch_state_on). It makes them on the prefetch stream, the forward and the backward read them on another one, and once the host lets go of them the caching allocator may give a block to the next prefetch while a late backward still needs it. This exists on main too and has nothing to do with growth; it is in this PR because the prefetch is what it touches. The test shows the reuse without the recording and none with it.

A table now waits when its real size is within a few batches of its limit (N keys each, more of them in flight), and when it expands (DynamicEmb_APIs.md, "Table expansion": "When the host looks at the device"). The capacities a table reaches are those of the old protocol.

Results

H100 80GB (8 per node), PyTorch 2.13, CUDA 13.3.

Blocking host syncs per lookup group and step, origin/main → #545 → this PR, counted by a probe over the steps of a module (it is not part of the PR) in both modes (the forward prefetches itself / an explicit prefetch before the forward), for tables that can grow and have room to spare (init capacity 16384 rows of 65536, batches adding about 350 keys):

layout all keys hit, forward prefetches new keys, forward prefetches all keys hit, explicit prefetch new keys, explicit prefetch
HBM only, grows 4 → 1 → 0 6 → 1 → 0 4 → 1 → 0 6 → 1 → 0
host only, grows 2 → 1 → 0 4 → 1 → 0 2 → 1 → 0 4 → 1 → 0
cache + storage, grows 4 → 1 → 0 8 → 1 → 0 4 → 1 → 0 8 → 1 → 0
HBM only, no eviction 4 → 1 → 0 6 → 1 → 0 4 → 1 → 0 6 → 1 → 0
cache + storage, no eviction 4 → 1 → 0 8 → 1 → 0 4 → 1 → 0 8 → 1 → 0

The tables that are near their limit (census with init capacity 1024 and batches of 384 keys: the bound is as large as the room) wait there, less than on #545, per step, #545 → this PR, plain and prefetch mode alike: all keys hit 1.50 → 1.00 (a table that never evicts: 3.00 → 0.00), new keys 2.75 → 2.38 (3.12 → 2.75), a step that grows the table 5.75 → 5.50 (4.75 → 4.25). The whole census (268 cases, both modes) against main: 264 improved, 4 unchanged, 0 regressed; 78 cases still sync outside what is inherent to the step: the 16 near-limit cases above, and the cases that #545 lists as not zero (retained evicted keys 28, DEMB_DETERMINISM_MODE 14, the cache metrics 10, the external parameter-server storage of the tests 10).

Many collections, lookup only (benchmark_many_collections.py --init-capacity-ratio 0.5 --collections 16: tables that can hold 250K keys and hold 4K; milliseconds per step, mean of 2 rounds on one idle H100):

layout (16 collections) origin/main (ms/step) #545 (ms/step) this PR (ms/step) this PR vs #545 blocking syncs per step over 90 steps, main -> #545 -> this PR
HBM only 7.07 6.26 5.91 1.06x 64.2 -> 16.2 -> 0.0
host only 6.38 7.23 7.04 1.03x 32.2 -> 16.2 -> 0.0

The rounds of a row differ by 0.4% to 3.3% (the two rounds of #545's host row, 7.11 and 7.35 ms, are the 3.3%), so the 1.03x of the host row is inside the noise. The HBM row is 1.20x faster than main. The host row is the exception: it stays above main (7.04 against 6.38 ms) with no blocking sync left in the step, and I have not looked for what is left. Here N is the 8192 keys of a batch, counted every step, and a table may hold 250K keys: the estimate alone would reach the limit in about 30 steps. With the correction a copy of the sizes brings it back each time it comes within 4N of the limit, and no step of the 90 waits.

Not timed on this revision: the hybrid and the cache layouts with tables that can grow (their syncs are in the census rows above, 1 → 0), and the tables that cannot grow, which do not reach this code (can_expand() is False: no estimate, no open batch). On an earlier revision of this PR those ran at 5.30 ms on #545 and 5.28 ms here (HBM only), and 270.55 and 270.50 ms (a cache of 3072 rows).

Tests: the growth section at the end of test_batched_dynamic_embedding_tables_v2.py and one case in test_no_eviction_row_indexing.py (44 cases over the layouts HBM only, cache, hybrid, host only and no eviction): a table far from its limit makes no blocking sync in any layout; one that has to grow does, and its keys never pass the load limit; batches of repeats do not make a table grow; may_expand / accumulate_bound / expand_if_need; a storage with only expand_if_need is asked at every step; the estimates never fall below the real sizes while a copy is in flight; a growing module gives the outputs of one that starts at full size and loses no key; the estimates follow the sizes of a table whose batches repeat their keys; they stay above the sizes while batches overlap; a correction asked for before the estimates were set again is void; the batches that are still open are not corrected away; a table that was expanded since the batch was counted asks for no sizes; the tensors of a prefetch are not reused. I broke the code in fourteen ways to see them fail: the flag ignored, never reading, always reading, no size bound, no stream recording, no fallback, the bound not added to the rows of a table that never evicts, the rows not checked against the limit, no correction, the open batches corrected away, no generation check, no generation bump, the open bounds never released, a refresh asked for after an expansion. Each is caught by the tests of that behaviour (the one that never reads fails 39 tests and then ends in a segmentation fault).

Battery on this branch (H100, the container above; no C++ changed since the extension of the previous revision of #545):

  • the growth tests (44), the v2 table suite (462 passed, 4 skipped), test_no_grad_slot_lifetime.py (47 passed), the single-GPU test files (test_lfu_scores.py and test_embedding_admission.py collect no pytest cases and run as the LFU-score and admission scripts below);
  • the multi-GPU torchrun suites: sequence and pooled embedding, table-row-wise, alignment (1440 passed), twin module (81 passed, 64 skipped), per-key score (76 passed), erase-async, incremental dump (17 passed), hash round-robin (127 passed); the LFU-score and the admission scripts;
  • the host-sync census (268 cases, above), and the one-off comparison of new main with this branch that is not part of the PR (16 cases, as in perf(dynamicemb): a lookup step without host syncs (arrays at the input length, the count on the device) #545): no difference.

Not covered (as on main)

The step of a table that is within a few batches of its limit, or that expands, waits for the device (see the census above); checkpoint load, dump / incremental dump, flush, pop, erase and replay wait as before; DEMB_DETERMINISM_MODE, retained evicted keys and the classes a user wrote are as in #545.

Two things about the correction that a reader should know:

  • The estimates and the open batches belong to the thread that trains: the prefetch, the forward and the backward of a step are not run at the same time.
  • A confirmation (the estimate set to the size on the device plus the unique keys of the batch) leaves out the keys of an earlier batch whose rows are inserted later, in the forward: the host and the hybrid layouts, between the prefetch and the forward of that batch. That is so on main and is not changed here; a correction asked for before the confirmation is void, so the correction does not add to it.

Not run on the final revision: the HSTU end-to-end runs, the checkpoint dump / load matrix (this PR changes no dump or load code), compute-sanitizer, and the sm_80 / sm_100 / sm_120 builds.

🤖 Generated with Claude Code

@greptile-apps

greptile-apps Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] No blocking issue was found in the reviewed changes.

Summary

This PR reduces device waits when embedding tables still have room to grow.

  • DynamicEmb lookup data keeps its live count on the device.
  • Growable tables check their size only when a batch might need expansion.
  • The many-collections benchmark can start tables below their maximum size.

Review conclusions are based on source inspection; no GPU tests were run.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Prefetch batch] --> B{Host bound leaves room?}
  B -->|Yes| C[Accumulate bound without waiting]
  B -->|No| D[Read unique counts]
  D --> E[Confirm sizes and expand if needed]
  C --> F[Run lookup]
  E --> F
  F --> G[Forward and backward finish]
  G --> H{Estimate near limit?}
  H -->|Yes| I[Copy sizes without waiting]
  I --> J[Correct estimate after copy finishes]
Loading

Reviews (6) · Last reviewed commit: "perf(dynamicemb): correct the host's est..." · Reviewed by Greptile

@shijieliu
shijieliu force-pushed the enh-dynamicemb-sync-free-prefetch-vmm branch from 54072f8 to 8710171 Compare November 11, 2026 06:15
@shijieliu shijieliu changed the title perf(dynamicemb): grow a table and prefetch a batch without waiting for the device perf(dynamicemb): a table that can still grow reads the device only when it may have to expand Nov 11, 2026
@shijieliu

Copy link
Copy Markdown
Collaborator Author

This PR is rewritten (force-push, 54072f8 -> 8710171) and its description replaced.

The first version (device-side growth with VMM pages, pinned rings and growth ordering: 9 commits) made the tables that can still grow slower in my benchmark, and a table reaches the size of the data and stops growing, so that design is dropped. What is here is the part that was worth keeping, three commits on top of #545: the host decides from a bound whether a table that can still grow may have to expand, and reads the device only then; a flag for the benchmark; and the prefetch tensors recorded on the forward stream (a hazard that exists on main).

Validated on an H100: 29 new tests (and the code broken in six ways to see them fail), the whole battery, a census (blocking syncs per step of a growable table with room: 2 to 8 on main, 1 on #545, 0 here) and a benchmark (growable tables 1.09x to 1.13x faster than on #545 where the step is launch-bound, tables that cannot grow unchanged). Details are in the description.

The old head, if anyone wants to look at it, is commit 54072f8.

shijieliu and others added 4 commits November 11, 2026 00:05
The lookup, insert, insert-and-evict, erase, ref-counter and row-resolve ops
take an optional device count, num_valid: a one-element int64 tensor with the
number of live leading entries of their per-key arrays. Their kernels stop at
the count, never read or write an entry past it, and cap their grid, so a
short or empty batch costs one cheap launch. The JIT evict kernels get the
pointer through EvictParams. Without it everything is what it was.

LinearBucketTable forwards it. With it, insert_and_evict* return the number of
evicted keys as a device tensor and the evicted arrays at the capacity of the
keys, instead of reading the count back and slicing. DEMB_DETERMINISM_MODE,
which walks the buckets from the host anyway, reads the count once and runs
on exact slices.

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

The load and store of value rows, select_insert_failed_values, the nine
initializers, the ten optimizer updates and reduce_grads take an optional
num_valid (see the table ops): rows past the count are neither read nor
written, and the grid is capped. An initializer may get no row index at all, in
which case it initializes rows 0..n-1; one that gets a negative index skips it.
Without num_valid the kernels are unchanged.

fill_rows and reset_ftrl_states reset the optimizer state of the rows that
were just created, so a counted caller needs no torch indexing, which would
read what lies past the count. The optimizers' reset_optimizer_states uses
them when it is given num_valid.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
segmented_unique_cuda already allocates its outputs for the number of keys and
leaves the number of unique ones on the device. The host-side read of that
count is what the rest of the step has to avoid, so it needs ops that take the
count instead of a sliced array:

* flagged_compact_counted: the compaction of flagged_compact, but the arrays
  keep their capacity and the number of selected entries comes back as a
  device tensor. Only the first num_valid entries are candidates.
* counted_gather, counted_scatter, counted_scatter_fill, counted_count_true:
  index and reduce over the first num_valid entries; a negative index skips.
* expand_table_ids_cuda takes num_valid and writes only that many table ids.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
Every step runs K independent BatchedDynamicEmbeddingTablesV2 modules, each its
own lookup group, and feeds their pooled outputs to a tiny MLP. The GPU work
per step is small, so CPU launch latency and the blocking host syncs inside
DynamicEmb are what the step time is made of. The script uses public APIs only,
so the same file runs on a tree before and after a change; it reports wall and
host time per step, the GPU-busy fraction, and the blocking syncs per step
(torch.profiler), writes JSON, and compares two result files.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
@shijieliu
shijieliu force-pushed the enh-dynamicemb-sync-free-prefetch-vmm branch from 8710171 to b655323 Compare November 11, 2026 10:59
@shijieliu

Copy link
Copy Markdown
Collaborator Author

Rebased with #545 onto main 476cdc0 and force-pushed: 87101715 -> b6553237. The three commits of this PR apply unchanged (no conflicts, no C++/CUDA change).

Run again on the rebased tree (H100): the counted tests, test_growable_tables.py (29), test_no_grad_slot_lifetime.py (46), the v2 table suite (391 passed, 4 skipped), the single-GPU files, the multi-GPU suites, and the LFU-score and admission scripts all pass; the host-sync census (268 cases and the 20 headroom cases) is identical, case by case, to the one before the rebase (headroom: 1 -> 0 syncs). embedding_dump_load of main was not run on this branch: it changes no dump or load code and #545 ran it.

🤖 Generated with Claude Code

@shijieliu
shijieliu force-pushed the enh-dynamicemb-sync-free-prefetch-vmm branch 2 times, most recently from 5776ee5 to c4beed1 Compare November 11, 2026 13:07
shijieliu and others added 5 commits November 11, 2026 05:32
…on the device

The step of a batch -- segmented_unique, the cache and storage lookups, the miss
path (admission, initialization, insert, eviction, write-back) and the backward
-- no longer reads anything back from the device. Its per-key arrays keep the
length of the input, and the number of live leading entries travels beside them
as num_valid, a one-element int64 tensor on the device. Every op is launched over
the capacity and works on the first num_valid entries; the glue between them is the
counted ops of dynamicemb_extensions (flagged_compact, counted_gather,
counted_scatter, counted_scatter_fill, counted_count_true), called directly.
flagged_compact is the compaction that keeps its count on the device and takes
num_valid; the version that read its count back to the host, which nothing calls
any more, is gone.

The existing interfaces are changed in place and the host-sized implementations
are gone, so there is one code path: Storage.find/insert, Cache.lookup and
insert_and_evict, Counter.add and erase, MultiTableAdmitter.admit take a keyword
num_valid (None: every entry is live, an exact-length call) and return
capacity-sized arrays with their counts as device tensors (types.py states the
contract); dynamicemb_prefetch, dynamicemb_eval_forward and
DynamicEmbeddingFunction have one flow each; the external storage tier works on
the same arrays. A Storage, Counter or MultiTableAdmitter that a user wrote has to
follow the new contract (DynamicEmb_APIs.md). The key map's insert_and_evict answers
in the same form for every call (arrays at the capacity of the keys, the number
of evicted keys a device tensor), with or without a count.

A table that can still grow reads the unique count per table to decide whether to
expand (segmented_unique reads and cuts nothing; unique_size_per_table is the
reader); retained evicted keys, DEMB_DETERMINISM_MODE and the explicit APIs (dump,
load, flush, replay, erase) still wait for the device. The cache metrics are kept
on the device and copied to the host when read.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
The exact-slice comparisons of the counted update kernels covered SGD and Adam
only. AdaGrad, row-wise AdaGrad and FTRL (plain and with group lasso) now run
the same flat-table and padded-buffer cases with garbage past the count, and the
two that reduce a row's norm in shared memory (row-wise AdaGrad, FTRL with
group lasso) also run with more rows than the capped grid has blocks, for the
flat table as well as the padded buffer.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…one, on two inputs in turn

The timed step was a training step: the K lookups, a small dense net, the loss and
its backward, on one of 16 pre-built batches. The batches were built before the
timed region, but the step held more than the lookup, and a cache that held the
keys of the 16 batches stopped missing after the warmup, so its insert and evict
paths were not timed.

A step is now the lookup of one input and nothing else: the K collections' forward
and their backward with the fused sparse update, driven by gradients built
beforehand. The backward belongs to the lookup: in the caching and HBM-only
layouts a training forward pins every key it reads with a reference count that
only the backward releases, and in every layout the backward makes the update of
the rows. There is no dense part and no loss. The batches are replaced by --inputs
inputs (default 2) used in turn, each drawing its keys from the same distribution
over its own slice of the rows, so no two share a key.

A cache that cannot hold the keys of all inputs misses at every step. A caching
layout is given the smallest cache that holds the unique keys of an input (a
cache holds a multiple of 1024 rows): at the defaults 3072 rows, one input and 45%
of the other, so about half of the keys miss, are inserted and evict as many. The
library raises when the unique keys of a step do not fit its cache, so a size taken
from the inputs works at any batch size; --hbm-ratio overrides it. For a caching
layout the run prints what the cache did at the step of each input (unique keys
found, inserted, evicted), read from the library's cache metrics outside the
timed region, and the table has a cache hit column that --compare prints for both
sides; for a hybrid layout the run says whether the keys fit the HBM tier.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
A review of the sync-free step found code that nothing calls, parameters that
only a test passes, and copies of helpers, all of it added by this PR or made
dead by it.

C++:
* counted_count_true is gone: the cache metrics read the device when they are
  recorded, as on main, and nothing else counted flags.
* counted_gather has no out argument; counted_scatter_fill is a 1-D op for bool
  and int64 arrays (what the step fills), not a general scatter-fill.
* reduce_grads, expand_table_ids_cuda (unique_op.cu/.h are main's again) and the
  contiguous flat load and store take no num_valid: the step never needed it
  there.
* The live count, the check of the num_valid tensor and the capped grid (4 waves
  of resident blocks, at most 32 per SM) exist once (counted_limit.cuh,
  counted_ops.h) instead of once per translation unit. The evict fatbin still
  includes no torch header.
* flagged_compact checks its input count once.

Python:
* DynamicEmbCache keeps main's host tensor for the cache metrics; there is no
  device mirror, event or publish step.
* Parameters, fields and branches nothing uses: preserve_existing of
  _insert_and_evict_keys, evict_strategy of DynamicEmbeddingFunction.forward,
  table_num and emb_dtype of PrefetchState, num_valid of slots_of, the
  outstanding_settle=None branch, the writes of -1 that the lookup has already
  made for the keys an admitter refuses, defaults no caller relies on, and the
  host-indexing forms of reset_optimizer_states that the counted form replaces:
  indices without num_valid is a ValueError now, not a silent reset of every row.
* unique_size_per_table is inlined into its one caller.
  refresh_slots_after_rehash looks the keys up without the compaction it
  threw away.
* Comments that told what the code did before, and sentences that repeated the
  contract, are gone.

Docs and benchmark: a broken anchor, the wait of the cache metrics in the list
of what a step waits for, dead lines of the benchmark and paragraphs that said
the same thing twice.

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

The tests of the ops that work on the first num_valid entries had a directory
of their own. They move into the test files of what they test, and their
parametrizations shrink to the cases that tell them apart (about 240 cases
instead of 1,283):

* compaction, gather, scatter, scatter-fill and the table ids: test_unique_op.py
* lookup, insert, insert_and_evict, collecting the evicted keys, the overflow
  buffer, the counter, erase, determinism mode: test_table_operation.py
* load and store of flat tables, select_insert_failed_values, the
  initializers, the optimizer updates, reduce_grads, resetting optimizer states:
  test_padded_buffer_optimizer.py
* a whole step against a plain-torch oracle, a step that must not block, a
  batch large enough for capped grids: test_batched_dynamic_embedding_tables_v2.py;
  the keys a cache is over-subscribed by: test_no_grad_slot_lifetime.py

Every op family keeps one test that runs on arrays with garbage past the count
and compares with the call on the exact slice. The glue ops and the table
lookup and insert also run a batch of 4M entries that a capped grid has to
stride over, and the count is checked to be clamped to [0, capacity]. The five
entries of the old directory are gone from unit_test.sh: the new homes are
registered already.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
shijieliu and others added 5 commits November 11, 2026 17:48
…have landed

The check that the prefetches in flight do not pin more keys than the cache holds counts
each batch by the number of keys it looked up, an upper bound, and reads the real number
of unique keys from the device, waiting for it, when the bounds add up to more than the
cache. With the prefetch queued a batch or two ahead of the forward, that is a wait at
every step wherever the bounds pass the cache and the real counts do not.

A batch that is counted by its bound while the sum is past half of the cache now has its
real count copied to pinned host memory without waiting (DelayedCopy: the copy, and the
event that ends it, asked without waiting). A check that finds the sum past the cache
replaces the bounds of the batches whose counts have landed by those counts, and waits for
the device only if the sum still passes the cache; a count that has not landed is a bound,
as before. A batch leaves the sum at the end of its forward by what it was counted as, so
the sum stays exact. A copy of a module (copy.deepcopy, pickle) with a count on its way
starts without it, as it does without the gate of an erase.

The test prefetches batches whose bounds pass the cache and whose real counts do not:
the second and the third prefetch make no blocking sync once the count of the batch before
has landed, and with the count queued behind a long wait (the control) the prefetch asks the
device.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…hen it may have to expand

A table that can still grow (init_capacity below max_capacity, or NO_EVICTION) read
the number of unique keys per table back at every step to decide whether to expand:
a blocking host sync per lookup group and step, the one the lookup step still made.

The host now decides from a bound it knows. Its estimate of the table sizes (the
numbers last read from the device plus, for every batch since, the keys of the batch,
which can only overcount) plus the number of input keys of this batch is compared
with the load limit. While that fits nothing can grow, nothing is read, and the bound
is counted in place of the unique keys. When it does not, the real counts are read,
before the table gate as they always were, and expand_if_need decides from them as it
did, confirming the sizes on the device when its estimate says a table might grow. The
decisions are the old ones; only the reads that could not change them are gone.

* Storage.may_expand(bound) and Storage.accumulate_bound(bound) are the two halves of
  the step for a batch whose unique count the host does not have; expand_if_need keeps
  its contract (a NO_EVICTION table now also clears the flag, below).
* While collect_table_sizes_flag is set, may_expand is True. The prefetch has then
  queued an asynchronous copy of the sizes into the estimates, which must not be read
  or added to before the host has waited for it: the read of the unique counts was that
  wait, made at every step. A NO_EVICTION table now clears the flag once it has decided
  (a checkpoint load left it set for good).
* A storage that has expand_if_need but not may_expand (a class of the user's) is given
  the real counts at every step, as it always was.

The estimate grows by N, the input keys of a batch, where a table grows by its unique
keys U, so it reaches the limit before the table does: a table with room left waits in
a burst of up to about N / U + 2 reads, once in about (limit - size) / N steps; one
within N keys of its limit still waits at every step.

The tests are at the end of test_batched_dynamic_embedding_tables_v2.py, and one in
test_no_eviction_row_indexing.py: a table far from its limit makes no blocking sync in
any storage layout; one that has to grow does, and its keys never pass the load limit;
batches of repeats do not make it grow; the estimates (of the keys, and of the rows of
a table that never evicts) never fall below the real sizes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
--init-capacity-ratio sets init_capacity below max_capacity, so that the tables can
still grow and the host keeps track of their size at every step: the many-collections
benchmark can now show what that costs. The host tier of a hybrid layout, the one that
grows, holds 1 - --hbm-ratio of the rows, so for it a ratio from there up leaves
nothing to grow to. A result file written before the flag existed is compared as a run
with the default (1.0).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…tream until it has used them

A prefetch makes the unique keys, their count, the slots and the other tensors of its
PrefetchState on the prefetch stream, and the forward and the backward of the batch
read them on the forward stream. The host lets go of them once the backward has been
queued, and that is the moment the caching allocator hands their blocks back to the
prefetch stream: the next prefetch can write into them while a late backward still
waits behind other work of the forward stream, and the backward then reads the keys,
slots or rows of another batch (a fault, or a wrong row). This also happens on
origin/main.

dynamicemb_prefetch now records every device tensor of the state on the forward
stream. The test has a control: with the recording taken out the allocator does give a
block back.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
…the device, without waiting

The host counts every batch in its estimate of the size of a table that can still grow by
a bound, the number of its input keys, while the table grows by its unique keys, which a
step does not wait for. The estimate drifts away from the size and comes close to the limit
of the table long before the table does, and from there on the step reads the number of
unique keys from the device, a few waits, until the sizes have been confirmed.

Once a batch is done (after its backward, or after a forward without one) and the last
check found the estimate within four batches of a limit, the sizes of the tables are copied
to pinned host memory without waiting (DelayedCopy). When the copy has landed, the next
check lowers the estimates by what they had counted beyond the sizes, less the batches that
were not done when the copy was asked for: the host keeps what each batch was counted by
from its prefetch to its release (open_batch, close_batch), in whatever order the batches
are done, and the batches counted since are kept too, so the estimates stay an upper bound
of what the tables will hold. Whatever else sets the estimates from the device (a
confirmation, a checkpoint load) makes a copy that is on its way void.

The copy runs on the stream of the backward, and a later prefetch makes a new key map
(an expansion) on its own stream: the sizes are not asked for when the table has been
expanded since the batch was counted, and the key map the copy reads is held for the
allocator until it has run. A copy of a module (copy.deepcopy, pickle) starts without a
copy on its way.

A table now waits only when it really is within a few batches of keys of its limit, and
when it expands.

The tests are in the table suite: the estimate follows the size of a table whose batches
repeat their keys (and falls, on every layout); it stays above the sizes, and above the rows
of a table that never evicts, while batches overlap; the batches still open are not
corrected away; a copy asked for before the estimates were set again is void; no sizes are
asked for after an expansion.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: aleliu <[email protected]>
@shijieliu
shijieliu force-pushed the enh-dynamicemb-sync-free-prefetch-vmm branch from c4beed1 to 2681a2b Compare November 12, 2026 02:41
@shijieliu

Copy link
Copy Markdown
Collaborator Author

Restacked on the new head of #545 (bccf650b, with the delayed counts) and force-pushed: c4beed13 -> 2681a2b5. The branch is #545's 10 commits and 4 of its own; the description is rewritten for this head.

  • The first three commits are those of before, on perf(dynamicemb): a lookup step without host syncs (arrays at the input length, the count on the device) #545's restructured history. perf(dynamicemb): a lookup step without host syncs (arrays at the input length, the count on the device) #545 folded its counted/ tests into the test files of the ops, so the growth tests moved from test/unit_tests/counted/test_growable_tables.py to the end of test_batched_dynamic_embedding_tables_v2.py (and one case to test_no_eviction_row_indexing.py). Small changes with it: the doc says a table waits "near its limit, by the host's estimate"; --init-capacity-ratio notes the hybrid layout (its growing tier holds 1 - --hbm-ratio of the rows) and never gives init_capacity 0; the hazard test patches record_prefetch_state_on by its module path.
  • New, 2681a2b5: the "delayed" correction of the host's size estimate. A step counts a batch by its input keys N where a table gets U <= N keys, so the estimate drifted up to the limit and the table then waited at every step. Now, within 4N of a limit, a batch that is done has the sizes of the tables copied to pinned memory without waiting (DelayedCopy, from perf(dynamicemb): a lookup step without host syncs (arrays at the input length, the count on the device) #545), and once the copy has landed the next check lowers the estimate by what it had counted beyond them, keeping the bounds of the batches that were still open (open_batch / close_batch) and of those counted since. Voided if the estimate was set from the device in between; not asked for after an expansion.
  • Review. An independent read of the commit found one real race: a later prefetch expands the table on its own stream and lets go of the key map that the size copy of the earlier batch was still reading. Fixed twice over: no copy is asked for after an expansion (key_map_generation), and the tensors the size kernel reads are recorded on the stream of the copy. Four smaller points, also fixed: the batch is opened last in the prefetch (nothing that can fail comes after it, so a prefetch that raises leaves no open batch), it is closed once (the no-grad forward and the backward do not both release it), a size copy is not landed while the flag says another copy is on its way into the estimates, and a copy of a module starts without a size copy on its way.

Validation, H100, the same container: the growth tests 44 passed; the v2 table suite 462 passed, 4 skipped; test_no_grad_slot_lifetime.py 47; the single-GPU files; the nine multi-GPU suites (sequence, pooled, table-row-wise, alignment, twin module, per-key score, erase-async, incremental dump, hash round-robin), the LFU-score and the admission scripts, all on this tree; the census (268 cases: 264 improved, 4 unchanged, 0 regressed against main; the headroom cases 4/6, 2/4, 4/8, 4/6, 4/8 -> 1 -> 0 on main -> #545 -> this PR); the one-off comparison with new main (16 cases) with no difference; fourteen mutants of the code, each caught by the tests of its behaviour.

Timing (K=16, tables that can hold 250K keys and hold 4K, one idle H100, mean of 2 rounds, ms per step, main -> #545 -> this PR): HBM only 7.07 -> 6.26 -> 5.91, with 64.2 -> 16.2 -> 0.0 blocking syncs per step over 90 steps; host only 6.38 -> 7.23 -> 7.04 (inside the 3% the rounds of #545 differ by; still above main, with no blocking sync left, and I have not looked for the rest), 32.2 -> 16.2 -> 0.0.

Not re-run on this revision (listed in the description): the hybrid and cache rows of that benchmark, the HSTU end-to-end runs, the checkpoint dump / load matrix, compute-sanitizer. Two limits the correction does not remove, also in the description: the estimates are for the thread that trains (the prefetch, the forward and the backward of a step do not run at the same time), and a confirmation leaves out the keys of an earlier batch of a host or hybrid layout that are inserted later in the forward, as on main.

🤖 Generated with Claude Code

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