Repository navigation
Conversation
[Medium impact] The PR appears safe to merge, with the interface break and performance trade-offs documented. SummaryThe PR keeps lookup arrays at the input length and carries their live counts on the GPU.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Input keys] --> B[Deduplicate on GPU]
B --> C[Input-length arrays and device count]
C --> D[Lookup live keys]
D --> E[Compact misses with device count]
E --> F[Admit, initialize, insert, and write back]
D --> G[Gather output]
F --> G
G --> H[Reduce gradients]
H --> I[Update live rows and release pins]
Reviews (11) · Last reviewed commit: "perf(dynamicemb): settle the keys that a..." · Reviewed by Greptile |
bf23afe to
8ea493e
Compare
|
Reworked: the sync-free step is now the only step. The existing |
8ea493e to
8fb16d4
Compare
|
Pushed 077f185: the benchmark of this PR is rewritten, no library code changed. What it timed before: a training step (K lookups, a small dense net, the loss and its backward) on one of 16 pre-built batches. The data were built before the timed region, but the dense part was timed, 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. What it times now: the lookup alone. The K collections' forward and their backward with the fused sparse update (the backward is part of the lookup: in the caching and HBM-only layouts the forward pins every key it reads with a reference count that only the backward releases), driven by gradients built beforehand; no dense part, no loss, no data creation. Two inputs that share no key are used in turn, and a caching layout is given the smallest cache that holds the unique keys of an input, so the cache is refreshed at every step. The script prints what the cache did at each step (unique keys found, inserted, evicted) and the table has a cache hit column. The table in the description is re-measured (3 rounds, idle H100, main and this PR alternating) and replaces the old one. What changed in the picture: HBM-only is 1.28x to 1.40x (it was 1.11x to 1.32x with the dense part in the step); a cache that misses is bound by the GPU (1.02x at 45% hits, 1.17x at 93%); and a caching layout whose step hits everywhere is slower than on main (0.73x; hybrid 0.87x), which the old benchmark did not show. That is the zero-key miss path (59 GPU activities per collection and step against 37 on main), described in the section "Where it does not pay". |
077f185 to
1c2456f
Compare
|
Rebased onto main 476cdc0 (it had moved by #539, #540, #544 and #547, and this PR conflicted with it) and force-pushed:
🤖 Generated with Claude Code |
09aa60a to
b4c15bc
Compare
|
Pushed What changed since
Two behaviours to look at.
Validation of the tree that is pushed (the extension rebuilt from it, H100):
Not re-run on this revision: the HSTU end-to-end measurement of the description (it was taken before the review rounds), the full Benchmark (
The all-hit caching row is still the cost side of this design (0.83x; it was 0.71x before this round): a step with no miss launches the miss path for zero keys. It is the next piece of work and it is not in this PR. Found by the audit and left alone, each one a decision rather than a deletion: the three 1-D kernels of #546 is stacked on this PR and is still on the previous head; it is restacked on this one after this round is settled. 🤖 Generated with Claude Code |
|
Pushed
Validation of this tree on H100 is in the new section "Delayed counts" of the description: the new tests and four mutants of the commit, the v2 table suite (419 passed, 4 skipped), #546 is restacked on this head. 🤖 Generated with Claude Code |
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]>
…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]>
…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]>
bccf650 to
7141add
Compare
|
Rebased onto main d53b9c8 (#528) and force-pushed: #546 sits on the old commits of this PR and is not restacked yet. The "Results" benchmark of 🤖 Generated with Claude Code |
Replaces the design of #542. The lookup step of training and eval no longer reads anything back from the device, and there is one code path for it: the existing interfaces are migrated in place and the host-sized implementations are deleted.
Rebased on main (476cdc0: #539, #540, #544 and #547). #547's two helpers,
release_slot_pinsandrefresh_slots_after_rehash, now take the device count (num_valid), so a no-grad training forward, which releases the slot pins itself, makes no blocking sync either (test_step_does_not_blockhas a check for it). The measurements below were made on the previous main (08051a3), except where the section "Rebased on main" at the end says otherwise.No padding. The arrays of a step keep the length of the input,
N(assegmented_unique_cudaalready did), and the number of unique keys stays on the device asnum_valid, a one-element int64 tensor. Every op of the step is launched overN, readsnum_valid, and works for the firstnum_validentries only; what lies past them is undefined and never read. So the dedup does what it is for: the work after it is proportional to the unique keys, not to the keys of the batch, and nothing is filled with sentinel values.The interfaces
Storage.find/insert,Cache.lookup/insert_and_evict,Counter.add/eraseandMultiTableAdmitter.admittake a keywordnum_valid(None: every entry is live, an exact-length call, which is what the explicit APIs and the tests make) and always return the same form: per-key arrays at the capacity of the input and counts as one-element device tensors (findreturnsnum_missingas a tensor, not an int).dynamicemb/types.pystates the contract,DynamicEmb_APIs.md("Host syncs in a step", "Writing a Storage, Cache, Counter or MultiTableAdmitter") says how to write a class against it, and the in-treePyDictStorageis migrated.Deleted: the host-sized flows (
_prefetch_cache_path,_prefetch_hbm_direct_path,_generic_forward_path,_apply_admissionand the eval lookup keep their names and have the sync-free bodies), the*_countedduplicates this PR used to add next to them, and the dispatch between the two (supports_num_valid,is_counted,_counted_supported). The external storage tier (a parameter server below the cache) works on the same arrays.Breaking: a
Storage,CounterorMultiTableAdmitterthat a user wrote has to follow the new contract (keywordnum_valid, capacity-sized results with device counts). A class written against the old one fails with aTypeErrorat its first step; there is no fallback path.What is covered
The per-step lookup and update of the built-in
DynamicEmbCache,DynamicEmbStorage(HBM-only, host-only and the backing storage of a cache) andHybridStorage, with an external storage tier, in training and in eval, with the built-in admitters, LFU/LRU/step scores, every optimizer, pooled and sequence output, with and without the prefetch pipeline:segmented_unique, the cache and storage lookups, the miss path (storage lookup, admission, initialization, insert, eviction, write-back), the backward reduce, the fused optimizers and the ref counters.What still waits for the device (as on main)
max_capacity; aNO_EVICTIONtable never does);evicted_item_mode=RETAIN_KEY),DEMB_DETERMINISM_MODE, the per-key score check whensafe_check_modeasks for it, the cache metrics while recording is switched on (set_record_cache_metrics, off by default);Storagethat reads the count on the host (a Python dict, say) waits where it reads it.How
flagged_compact,counted_gather,counted_scatter,counted_scatter_fill(src/counted_ops.cuandsrc/index_calculation.cu; the Python modules call them directly): compaction that returns capacity-sized arrays and a device count; gather, scatter and fill over the firstnum_validentries.num_valid(table_lookup,table_insert*,table_erase, the ref-counter and row-resolve kernels, load/store of value rows, the nine initializers and the ten optimizer updates). The grid of a launch with a count is capped, so a short or empty batch costs one cheap launch. Without the argument a kernel is what it was.if num_miss == 0: return) now runs for zero keys.Results
H100 80GB, PyTorch 2.13, CUDA 13.3,
sm_90build.Blocking host syncs per lookup group and step, measured with the same probe on origin/main and on this branch (
cudaStreamSynchronize,cudaDeviceSynchronize,cudaEventSynchronize, synchronous and pageable copies), in the two modes of the probe (the forward runs its own prefetch / an explicitprefetchbefore the forward; the cells are the same in both):Not zero (as on main, see above): retained evicted keys (1 to 2), tables that can still grow (1.5 to 2.75),
NO_EVICTIONtables (3),DEMB_DETERMINISM_MODE(hundreds). An external parameter-server storage (cache_ps, the Python-dict storage of the tests) goes from 24 to 10 syncs on a step with new keys: it reads the count itself.Many embedding collections, lookup only (
benchmark/benchmark_many_collections.py, new, runs unchanged on both trees; one H100, K collections of 2 tables of dim 64, 1024 samples x 4 keys per table, SGD unless noted). The timed step is the lookup of K DynamicEmb collections and nothing else: each collection's forward and its backward with the fused sparse update, driven by gradients built before the timed loop. The backward is part of 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. There is no dense part, no loss and no data creation; the inputs are built on the GPU before the warmup. Two inputs that share no key (2,134 unique keys per table each) are used in turn, so a cache too small for both is refreshed at every step: a caching layout is given the smallest cache that holds the unique keys of an input unless--hbm-ratiosays otherwise, and the script prints what the cache did at each step (unique keys found, inserted, evicted). Wall time of a step: the steps of a window are launched back to back and the device is waited for once at its end. Milliseconds per step, medians over 3 rounds with main and this PR alternating, on an otherwise idle node:Reading it. Removing the syncs pays where the step is launch-bound and has syncs to lose: 1.28x to 1.40x for HBM-only tables (more with more collections), 1.30x with Adam and 1.30x with many duplicate keys, and a hybrid layout with half of its keys in host memory goes from 29.0 to 16.0 ms (1.82x, 302 syncs per step to none). Host-only tables are on par: their step waits for host memory, not for syncs. A cache that misses is bound by the GPU, which this PR does not make faster: 1.17x at 93% hits, 1.02x at 45% hits, where a step takes 271 ms and the GPU is busy 99% of it.
Where it does not pay: a step that hits everywhere. A cache that holds both inputs is slower, 7.42 to 10.13 ms (0.73x), and so is a hybrid layout whose keys all sit in the HBM tier, 8.59 to 9.88 ms (0.87x). On a step that hits, main reads the miss count and skips the miss path (and the host-tier lookup of a hybrid layout); this step has no count on the host to decide that and runs them for zero keys. The profiler counts GPU activities per collection and step, main against this PR: caching 37 against 59 when every key hits (79 against 59 at 45% hits), hybrid 56 against 68 when the keys fit and 118 against 68 when half do not, HBM-only 41 against 35. This benchmark is launch-bound (the GPU is busy 14% of the time in the all-hit caching row), so every launch counts; a step that is bound by the GPU does not see it (HSTU below). The launches of the miss path for zero keys are the cost side of this design, and the place to look next.
HSTU end to end (
examples/hstuexperimentsexp4_caching_hr: caching, hash round-robin, Zipf 1.05, andexp5_prefetch: the same with the prefetch pipeline; 8 x H100, one node; 1000 iterations for the throughput, nsys over iterations 151-168 for the syncs; one run each):op:segmented_unique,op:storage_find,op:flagged_compact)The 20 to 24 that remain are not in DynamicEmb (the TorchRec input distribution,
global_tokens, the optimizer step). The HSTU step is GPU-bound (the GPU is busy 97 to 98% of it), so with 4 syncs fewer the step time does not move within the noise of one run: the gain is on a step that is launch-bound, as in the benchmark above. The step launches 27 more kernels, the lookup's empty-miss launches.Tests. About 240 new test cases (1.5k lines), in the test files of what they test (
test_unique_op.py,test_table_operation.py,test_padded_buffer_optimizer.py, the v2 table suite andtest_no_grad_slot_lifetime.py), and a migratedPyDictStorage: each new op against the same op on the exact slice with garbage past the count (garbage keys, out-of-range indices, sentinel-filled outputs that must stay untouched; all optimizers; batches large enough for the capped grids to stride); the whole step against a plain-torch oracle (with the DEBUG initializer the row of a new key is a function of the key, SGD and Adam move rows by a known amount) for HBM-only, cache, hybrid and host-only layouts, NONE/SUM/MEAN pooling, with and without admission, with evictions and spills, an empty and a one-key batch, and at 1.5M keys per batch; a training and an eval step make no blocking sync (profiler, with a guard against a vacuous pass). A one-off comparison that is not part of the PR runs the same workload on origin/main and on this branch (every layout, SGD and Adam, pooled and sequence output, 24 steps and an eval pass) and agrees to a relative 1e-4. The existing suites pass on H100: the single-GPU files, the v2 table suite (417 passed, 4 skipped), the multi-GPU torchrun suites (sequence, pooled, table-row-wise, alignment, twin module, per-key score, erase-async, incremental dump, hash round-robin) and the LFU and admission scripts, all on the final revision. compute-sanitizer (racecheck, synccheck and memcheck) is clean on the row, optimizer and insert/evict/erase kernels run with a capped grid.Behaviour changes
HybridStoragealways asks its host tier about the keys the HBM tier lacks; a user-writtenStorageis called every step, also withnum_validof zero.Nrows instead of the number of misses: up toN x value_dimbytes per buffer, a few buffers.dynamicemb_extensions.flagged_compactis the compaction that keeps its count on the device and takesnum_valid; the version that returned a host count is gone.reset_optimizer_stateshas the counted form (num_valid,table_ids,table_emb_dims) that the step uses. Its host-indexing form is gone:indiceswithoutnum_validraises aValueError(it used to index on the host), andemb_dimsis an int that all rows share. Withoutindicesit resets every row, as before.Outstanding prefetched keys ... exceed cache capacity) counts the batches in flight by the host's bound (their input keys), replaces a bound by the real count where that has already reached the host (see "Delayed counts"), and reads the counts from the device, once, only when the bounds, so replaced, still exceed the cache; it runs before the cache is touched.insert_and_evictno longer takes its atomic for a tile that evicts nothing (a tile of 1 in every launch that has a count: one atomic per evicting key, none for the others). The order of the evicted keys in the output was never specified.Changes after review
A review of the first version found code that was not needed. It is gone:
dynamicemb/counted.py(one-line wrappers of the extension ops: the modules call the ops directly);counted_count_true(the cache metrics read the device while they are recorded, as on main); theoutargument ofcounted_gather; the 2-D and other-dtype forms ofcounted_scatter_fill; thenum_validofreduce_grads, ofexpand_table_ids_cuda(unique_op.cu/.hare main's again) and of the contiguous flat load and store; the host-countflagged_compact(the counted one has its name). The live count, the check of thenum_validtensor and the capped grid exist once instead of once per translation unit.segmented_uniquenever reads the device and never cuts its arrays; the read of the per-table unique counts that a table that can still grow needs is made where it is needed. The over-subscription accounting has no flag for "exact" counts.keys_exact, theemb_dtypeof the cache path,preserve_existingof_insert_and_evict_keys, theevict_strategyofDynamicEmbeddingFunction.forward, the writes of-1that the lookup had already made, the host-indexing forms ofreset_optimizer_states.counted/directory is gone): about 240 cases instead of 1,283. The batches of 4M entries that a capped grid has to stride over and the clamp of the count to[0, capacity]stay covered.Validation of the final revision (H100, PyTorch 2.13, CUDA 13.3, the extension rebuilt from this tree):
test_unique_op.py,test_table_operation.py,test_padded_buffer_optimizer.py,test_ftrl_optimizer.py,test_rowwise_adagrad_state_precision.py,test_no_grad_slot_lifetime.py): 975 passed;test_no_grad_slot_lifetime.py(47 passed): all pass;set_record_cache_metrics(True)), which read the device again, as on main: 4 blocking syncs per step and 1 per eval, where main has 5 to 11 and 2 to 3;embedding_dump_loadmatrix (Adam and row-wise Adagrad, with and without optimizer states, on 1 and 8 GPUs, timestamp scores, plus the hash round-robin, table-scope and int32 cases): 14 dumps, 22 loads. One load failed the score-order assertion described under "Rebased on main" (an 8-GPU dump, a 1-GPU load, TIMESTAMP scores; four 8-GPU dumps shared the node). The checkpoint itself is out of order: new main's loader and this branch's fail on it the same way, by the same 23.75 ms. Dumped and loaded again on the idle node, three times: pass;test_table_dump_load.pyon 1 and on 8 processes: 204 passed each.Delayed counts
The over-subscription check was the last place where a cache waited for a count that the device had already made: with the prefetch queued a batch or two ahead of the forward, the bounds of the batches in flight (their input keys) add up to more than the cache wherever the real counts do not, and the check read the real counts from the device, waiting for them, at every such step.
DelayedCopy(key_value_table.py): a device tensor copied to pinned host memory without waiting, and the event that ends the copy, whichlanded()asks without waiting. A copy of a module (copy.deepcopy, pickle) starts without a copy on its way, as it does without the gate of an erase.PrefetchState.unique_count)._settle_outstanding_keysfirst replaces the bounds of the batches whose count has landed by those counts, and goes to the device only if the sum, so corrected, still passes the cache. A batch leaves the sum at the end of its forward by what it was counted as, so the sum stays exact; for that reason a count has to be corrected before the forward ends, not at the backward.A review of this change found a real gap in its first version (a batch that was settled without waiting asked for no count of its own, so the next prefetch waited again, one in three): it is fixed, and the test runs on to the third prefetch.
Validation (H100, PyTorch 2.13, CUDA 13.3; no C++ changed, the extension of the previous revision):
test_no_grad_slot_lifetime.py(47 passed) and the single-GPU test files: all pass;Not run
sm_80,sm_100,sm_120builds; multi-node; compute-sanitizer over the whole test suite (racecheck, synccheck and memcheck were run over the kernels with a capped grid, on an earlier revision). On the final revision: the HSTU end-to-end runs (the numbers above are from an earlier revision) and the full matrix (a reduced one ran, above).Rebased on main
Latest: rebased onto d53b9c8 (#528, the hierarchical dist; 2026-11-12). #528 changes the same ops and entry points as this PR, so the conflicts were where both add to a signature or a code path, and two things needed a change that no conflict marker showed:
dynamic_emb_op.cu: [FEA] DynamicEmb: hierarchical dist for row-wise sequence sharding #528'sout_row,grad_rowsandentry_of_rowand this PR'snum_validare all optional arguments now (reduce_gradsends withgrad_rows;load_from_flat_table_embtakesentry_of_row,out_rowandnum_valid; the kernels take their row count fromnum_validand the entry of an output row fromentry_of_row). The includes ofmodule_bind.cuandunique_op.cu, andbenchmark/README.md(main's section 3, this PR's is now section 4).batched_dynamicemb_function.py: [FEA] DynamicEmb: hierarchical dist for row-wise sequence sharding #528'sdirectpath (a sequence lookup loads each key's row into the output),output_allocandout_rows, together with this PR's arrays at the input's length andnum_valid.PrefetchState.record_stream(new in [FEA] DynamicEmb: hierarchical dist for row-wise sequence sharding #528) also coversnum_uniqueandnon_admitted_count, which this PR adds.DynamicEmbeddingFunction.backwardreturns 12 gradients, one more since [FEA] DynamicEmb: hierarchical dist for row-wise sequence sharding #528'soutput_allocinput (the first GPU test run after the rebase found it: autograd "returned an incorrect number of gradients"; no conflict marker showed it).Run on the rebased tree (
7141addb; H100, the CI image of the earlier runs; the extension built for sm_90, and for sm_103 on GB300):test_unique_op.pyandtest_no_grad_slot_lifetime.py: 125 passed), the v2 table suite (419 passed, 4 skipped), the single-GPU files (rc 0, excepttest_lfu_scores.pyandtest_embedding_admission.py, which collect no pytest cases: rc 5 as before);test_hier_dist.sh,test_hier_overflow.shandtest_hier_pipeline.sh: all passed; and the sharded suites run again on the hierarchical dist (sequence embedding, twin module, erase-async, per-key score, LFU scores): all pass;--check(the hierarchical dist against TorchRec's, bit for bit) passes on the 8 GPUs of an Eos node and on the 16 GPUs of GB300 trays, for this branch and for main.Not run on this revision: the LFU-score and admission scripts on TorchRec's dists (the LFU script ran on the hierarchical dist only),
embedding_dump_load, the host-sync census and the comparison with main's outputs (both ran on the previous revision), the HSTU end-to-end runs, compute-sanitizer.Before that, the branch was rebased from 08051a3 onto 476cdc0 (#539, #540, #544, #547). One conflict, in
batched_dynamicemb_function.py, in the two helpers of #547 (above); the other six commits of this PR apply unchanged, apart from the benchmark's check that a caching run has a cache smaller than the table (it refuses--num-embeddings 1024with a message, where it used to build an HBM-only table and fail later). The extension was rebuilt (#544 changed a.cufile). Run again on the rebased tree, H100, same container:the tests of the new ops (a directory of their own then, since folded into the existing test files),
test_no_grad_slot_lifetime.pyof FIX](DynamicEmb) Release slot pins after no-grad training forwards #547, the v2 table suite, the single-GPU files, the multi-GPU suites (sequence and pooled embedding, table-row-wise, alignment, twin module, per-key score, erase, incremental dump, hash round-robin) and the LFU-score and admission scripts: all pass;the host-sync census: the same 268 cases as before the rebase, with the same count of syncs in every one;
the one-off comparison of new main and this branch (every layout, SGD and Adam, pooled and sequence output, 24 steps and an eval pass): 16 cases, no difference;
embedding_dump_load.sh, the suite main got with its recent commits (a matrix of 228torchrunruns): all 228 pass on this branch, one of them only on the second try (below);One load failed in the first run: a dump on 8 GPUs, a load on 1 (Adam with optimizer state, TIMESTAMP scores). The test asserts that the loaded scores keep the order of the batches, and the scores of one table were out of order by 7 ms. It is not the load: new main's code fails the same way on that checkpoint. The dump turns each rank's timestamps into ages against that rank's own
device_timestamp()(the 8 GPUs of a node have clocks that differ by seconds; I measured offsets between 1.9 and 4.9 s), read after a barrier, so a rank that is scheduled late after the barrier shifts all of its scores, and the batches are only 12 to 17 ms apart. In that checkpoint the newest scores of one table were 31 ms apart between ranks, those of the other 23 tables 0.1 to 0.8 ms; the node was running other tests. Dump and load repeated on the same loaded node: new main 8 of 8 pass (one came within 1.6 ms of failing), this branch 7 of 8, the failure being the same assertion. On an idle node: 4 of 4 and 4 of 4, with 11.1 to 12.7 ms to spare (the ranks' scores are 0.5 ms apart). A step of this branch is a little shorter than main's (11.7 against 13.1 ms between batches on the idle node), so there is a little less to spare. After dumping that checkpoint again, the 105 remaining loads and the int32 cases pass.Re-measured on the final revision against main 476cdc0 (
benchmark_many_collections.py, the same script and flags as the table above, one round per row, otherwise idle node; the four rows that carry the argument):The all-hit caching row was 0.71x before this round of review.
🤖 Generated with Claude Code