Repository navigation
Feat/support incremental dump for LFU - #432
Conversation
…olicy
Add a `need_incremental_dump` table option. For LFU tables it stores a
per-key last-access timestamp alongside the frequency using a new compound
`LruLfu` ScorePolicy that occupies two AoS score words per key:
- word 0: last-access timestamp (device global timer) — used only to select
keys for time-based incremental dump
- word 1: access frequency — drives eviction (unchanged LFU semantics)
incremental_dump for such tables reuses the TIMESTAMP flow, thresholding on
the timestamp word and returning device_timestamp().
CUDA: Bucket/Table carry num_scores; AoS score accessor scores(iter,k);
ScorePolicy<LruLfu>::update writes both words; reduce() gets a 2-score path
that ranks by the frequency word; insert() clears the whole block on evict;
export/count take a score_index. Bindings thread num_scores/score_index.
Default num_scores=1 keeps the single-score path byte-identical.
Python: scored_hashtable decouples score-word count from spec count
(score_policy_num_scores); key_value_table builds a single LruLfu spec for
LFU+need_incremental_dump; batched returns device_timestamp() for such tables.
Known follow-ups: rehash/dump/load move scores with single-column semantics
(loses the LruLfu frequency); NO_EVICTION+need_incremental_dump is rejected;
overflow-table timestamps not stamped on lookup-found.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Table growth (_expand_tables_impl) re-inserted keys with a single-value ASSIGN, which only restores the leading score word. For the LruLfu (timestamp, frequency) layout this reset every key's frequency to 0 on each rehash, breaking LFU eviction. Add a copy_score_blocks CUDA kernel that copies all score words for aligned (src_slot, dst_slot) key pairs between two tables, reusing the AoS Bucket::scores(iter,k) accessor (no duplicated layout math). Rehash now calls it after re-insert when num_scores > 1, restoring both the timestamp and the frequency exactly. Single-score tables are unaffected (guarded on num_scores). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Dump the full [N, num_scores] score block and restore it on load, so the LFU frequency (word 1) survives save/load, not just the timestamp (word 0). Adds gather_score_blocks/scatter_score_blocks kernels; DynamicEmbStorage dump/load handle multi-word; HybridStorage multi-word dump/load guarded as a follow-up. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The overflow buffer never wrote scores on insert or training lookup (only a CONST read existed); eviction there is counter-based. So overflow entries had unmaintained scores for all modes, and LruLfu's timestamp/frequency were wrong for keys living in overflow. Now: - lookup found-in-overflow (non-CONST): lock the slot and apply the score policy (stamp timestamp / accumulate frequency; both words for LruLfu). - insert_and_evict overflow Insert/Evict: clear the score block (fresh) then write via the policy; Assign updates under lock. Eviction stays counter-based; single-score modes now also get correct overflow scores (previously garbage). Co-Authored-By: Claude Opus 4.8 <[email protected]>
The CONST lookup path returned *scores(iter) == word0, which for LruLfu is the timestamp, not the LFU score. Read the reduction score instead (scores(iter, num_scores-1) == frequency for LruLfu, word0 otherwise), for both the main-table and overflow CONST paths. The non-CONST path already returns the frequency via update(). Single-score modes are unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…r/copy, incremental re-touch) Add table-level test_lru_lfu.py (registered in the runner): - frequency accumulation on insert/lookup; CONST lookup returns frequency (word1), not the timestamp (word0) - eviction ranks by frequency (2-score reduce): hot keys survive - gather->scatter and copy_score_blocks round-trips preserve both words Add batched-level test_lfu_incremental_dump_retouch: re-accessed keys are re-dumped, untouched keys are not, and an idle window dumps nothing (caching on/off). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rage tests _validate_load_meta compared the score-file word count against num_keys, but a multi-word layout (LruLfu = timestamp+frequency) stores num_scores words per key; compare against num_keys * num_scores instead. Caught by the new DynamicEmbStorage dump/load round-trip test. Tests (test_lru_lfu.py): add storage-level dump/load round-trip and rehash (_expand_tables_impl) integration tests asserting both score words are preserved; make the eviction test robust (hot set well below capacity) and avoid unsupported uint64 arange. Verified on EOS H100: 7 passed (table-level) + 18 passed (incremental incl. TIMESTAMP/STEP/CUSTOMIZED regression). Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
/build |
|
❌ Pipeline #56931977 -- failed
Result: 12/17 jobs passed |
Greptile SummaryThis PR introduces a compound
Confidence Score: 5/5The change is logically consistent end-to-end: bucket strides, score permutations, rehash copying, and incremental-dump thresholding are all wired up correctly for the two-word LruLfu layout. No correctness bugs were found in paths exercised by production workloads. The new assert guards in determinism-mode paths are debug-only and do not affect inference or training correctness. Previously flagged issues have been addressed. scored_hashtable.py: the three DEMB_DETERMINISM_MODE assert guards should use raise NotImplementedError to survive python -O, matching the convention in key_value_table.py. Important Files Changed
Sequence Diagram%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant User
participant BatchedTables
participant Storage
participant KeyIndexMap
participant CUDAKernel
Note over User,CUDAKernel: LruLfu insert
User->>BatchedTables: forward(indices)
BatchedTables->>Storage: find(keys, LRU_LFU)
Storage->>KeyIndexMap: "insert(num_scores=2)"
KeyIndexMap->>CUDAKernel: table_insert_kernel
CUDAKernel-->>CUDAKernel: "update scores[0]=timestamp scores[1]+=freq"
CUDAKernel-->>KeyIndexMap: indices
Note over User,CUDAKernel: Incremental dump
User->>BatchedTables: get_score()
User->>BatchedTables: incremental_dump(ts_ref)
BatchedTables->>Storage: incremental_dump
Storage->>KeyIndexMap: "incremental_dump(score_index=0)"
KeyIndexMap->>CUDAKernel: "count_matched + export_batch(score_index=0)"
CUDAKernel-->>Storage: keys, timestamps
Storage-->>User: keys_cat, values_cat
Note over User,CUDAKernel: Full dump
User->>Storage: dump
Storage->>KeyIndexMap: "gather_score_blocks -> [N,2]"
KeyIndexMap->>CUDAKernel: gather_score_blocks_kernel
CUDAKernel-->>Storage: [N,2] uint64
Storage->>Storage: apply dump_permutation
Storage-->>User: score file in logical order
Note over User,CUDAKernel: Rehash
Storage->>KeyIndexMap: "insert(CONST, num_scores=2)"
KeyIndexMap->>KeyIndexMap: copy_score_blocks_from
KeyIndexMap->>CUDAKernel: copy_score_blocks_kernel
CUDAKernel-->>KeyIndexMap: both words preserved
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant User
participant BatchedTables
participant Storage
participant KeyIndexMap
participant CUDAKernel
Note over User,CUDAKernel: LruLfu insert
User->>BatchedTables: forward(indices)
BatchedTables->>Storage: find(keys, LRU_LFU)
Storage->>KeyIndexMap: "insert(num_scores=2)"
KeyIndexMap->>CUDAKernel: table_insert_kernel
CUDAKernel-->>CUDAKernel: "update scores[0]=timestamp scores[1]+=freq"
CUDAKernel-->>KeyIndexMap: indices
Note over User,CUDAKernel: Incremental dump
User->>BatchedTables: get_score()
User->>BatchedTables: incremental_dump(ts_ref)
BatchedTables->>Storage: incremental_dump
Storage->>KeyIndexMap: "incremental_dump(score_index=0)"
KeyIndexMap->>CUDAKernel: "count_matched + export_batch(score_index=0)"
CUDAKernel-->>Storage: keys, timestamps
Storage-->>User: keys_cat, values_cat
Note over User,CUDAKernel: Full dump
User->>Storage: dump
Storage->>KeyIndexMap: "gather_score_blocks -> [N,2]"
KeyIndexMap->>CUDAKernel: gather_score_blocks_kernel
CUDAKernel-->>Storage: [N,2] uint64
Storage->>Storage: apply dump_permutation
Storage-->>User: score file in logical order
Note over User,CUDAKernel: Rehash
Storage->>KeyIndexMap: "insert(CONST, num_scores=2)"
KeyIndexMap->>KeyIndexMap: copy_score_blocks_from
KeyIndexMap->>CUDAKernel: copy_score_blocks_kernel
CUDAKernel-->>KeyIndexMap: both words preserved
Reviews (9): Last reviewed commit: "fix(dynamicemb): allow score_strategy=No..." | Re-trigger Greptile |
Remove the redundant score_specs list/dataclass field (the single score spec always comes from the policy; multi-word LruLfu layout is derived via score_policy_num_scores). Move need_incremental_dump policy selection into get_score_policy(), which returns the LRU_LFU spec directly for LFU and keeps the unsupported-strategy guard. create_table_state collapses to one call plus incremental_score_name = score_policy.name. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ting The compound LruLfu ScoreSpec name maps to word 0 (score_index 0) -- the timestamp column incremental_dump thresholds on -- not the frequency word, so "lru_lfu" reads truer than "frequency". Also apply black to the touched files. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…re test Thread need_incremental_dump through create_model/apply_dmp and add a --need-incremental-dump flag to test_lfu_scores.py. In LruLfu mode the exported score is a 2-word block [timestamp, frequency]; take the reduction (last) word so the existing frequency-vs-true-count validation proves the extra timestamp word does not corrupt LFU semantics through the full torchrec/storage stack. Guard against caching/HybridStorage (multi-word checkpoints are a follow-up) and run the new variant storage-only in test_lfu_scores.sh. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The docstring claimed STEP/CUSTOMIZED/NO_EVICTION add a timestamp column, but get_score_policy rejects them with NotImplementedError -- need_incremental_dump is supported only for TIMESTAMP (no-op, already a timestamp) and LFU (the compound LruLfu two-word policy). Align the docstring with the code. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…t assert The multi-word load path is the only shape guard before scatter_score_blocks forwards the tensor to the CUDA kernel (which does no validation). An assert is stripped by `python -O`, so a malformed checkpoint (e.g. a 1-D score tensor) could silently cause wrong/out-of-bounds device writes. Raise ValueError instead, and also check the row count (size(0) == num keys), matching the _validate_load_meta style. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The comment described the multi-score region as SoA ([col0 block][col1 block]), but the scores(iter, k) accessor computes iter * num_scores_ + k -- an AoS layout where each key's score words are contiguous. Correct the comment so a developer deriving pointer arithmetic for a new multi-score op gets the right formula. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
/build |
|
❌ Pipeline #56941091 -- failed
Result: 12/17 jobs passed |
erase() called table_erase without num_scores, so it fell back to the pybind default of 1. For a LruLfu table (num_scores=2) that mis-sizes the per-slot stride (total_size = key + digest + num_scores*score), giving wrong bucket_bytes / num_buckets and corrupting bucket-stride arithmetic -- erase then probes the wrong slots. Forward self.num_scores_. (Incidental: black collapses one adjacent signature line.) Co-Authored-By: Claude Opus 4.8 <[email protected]>
…al_dump Replace the `need_incremental_dump` flag with a compound `score_strategy` tuple. `score_strategy` now accepts either a single DynamicEmbScoreStrategy or a tuple; only (TIMESTAMP, LFU) is supported for now (in either order), mapping to the existing LruLfu two-word score policy. The tuple order is the logical order checkpoints are written in; the on-device physical layout stays fixed, and dump/load reorder score columns via a logical<->physical permutation, so both orders behave identically at runtime and differ only in checkpoint column order. A one-element tuple (X,) is normalized to the single strategy X. - config: normalize_score_strategy + helpers (eviction / timestamp-column / physical-order / dump+load permutation); validate in __post_init__; drop the need_incremental_dump field and its grouped_key entry - key_value_table: get_score_policy handles the tuple; dump reorders physical-> logical in export_keys_values_iter, load reorders logical->physical - incremental_dump: time-based only when the strategy carries a TIMESTAMP column (single TIMESTAMP or a compound including it); otherwise thresholds on the absolute score value (documented in code + DynamicEmb_APIs.md) - shard/batched: eviction/LFU checks route through the new helpers - tests/docs: convert need_incremental_dump usage to the tuple; add (LFU, TIMESTAMP) reversed-order dump/load round-trip with checkpoint column check; update score_strategy type annotations; --need-incremental-dump test flag now selects the compound (TIMESTAMP, LFU) strategy Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
/build |
|
❌ Pipeline #57495645 -- failed
Result: 10/17 jobs passed |
The (TIMESTAMP,LFU)/(LFU,TIMESTAMP) dump/load round-trip test paired the dumped score file with keys from a *separate* export_keys_values scan, which is a distinct iteration and need not reproduce the dump's row order -> misaligned key->frequency mapping (even the identity ts_first case failed). Read the keys from the dumped `keys` file instead, which is written in lockstep with the `score` file, so rows are aligned. Verified on H100: 8 passed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…mental-dump -> --lru-lfu - Export the ScoreStrategy type alias from the top-level dynamicemb package (import + __all__) so users can annotate the now-Union-typed score_strategy as `from dynamicemb import ScoreStrategy`. - Rename the test_lfu_scores CLI flag --need-incremental-dump to --lru-lfu (and its var/messages) to match the underlying LruLfu compound policy; the removed need_incremental_dump name no longer appears anywhere. Update test_lfu_scores.sh. Verified on H100: `from dynamicemb import ScoreStrategy` imports; lfu_scores smoke passes with --lru-lfu. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
/build |
|
❌ Pipeline #57508429 -- failed
Result: 11/17 jobs passed |
None is a pre-existing sentinel used by the planner / sharding path for non-DynamicEmb (plain TorchRec) tables (shard/embedding.py guards on `score_strategy is not None`). The new __post_init__ validation rejected None with TypeError, breaking test_distributed_dynamicemb.py's get_planner which passes score_strategy=None for use_dynamicembs=False tables. Pass None through unchanged and annotate the field Optional[ScoreStrategy] to match. Missed earlier because test_distributed_dynamicemb.py (torchrun) was not in the first GPU run. Now verified on H100: test_distributed_dynamicemb 15/15, test_lru_lfu 8/8, incremental_dump 18/18, hybrid_storage_export all pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
/build |
|
❌ Pipeline #57749978 -- failed
Result: 14/17 jobs passed |
Description
Checklist