Skip to content

Feat/dynamicemb lru lfu score strategy - #2

Open
jiashuy wants to merge 14 commits into
feat/dynamicemb-lfu-incremental-dumpfrom
feat/dynamicemb-lru-lfu-score-strategy
Open

jiashuy wants to merge 14 commits into
feat/dynamicemb-lfu-incremental-dumpfrom
feat/dynamicemb-lru-lfu-score-strategy

Conversation

@jiashuy

@jiashuy jiashuy commented Jul 8, 2026

Copy link
Copy Markdown
Owner

Description

Checklist

  • I am familiar with the Contributing Guidelines.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes.

jiashuy and others added 2 commits July 14, 2026 14:09
* feat(dynamicemb): support incremental_dump for LFU via LruLfu score policy

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]>

* fix(dynamicemb): preserve LruLfu scores across rehash

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]>

* fix(dynamicemb): preserve LruLfu multi-word scores across dump/load

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]>

* fix(dynamicemb): maintain overflow-table scores (incl. LruLfu)

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]>

* fix(dynamicemb): lookup returns frequency (not timestamp) for LruLfu

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]>

* test(dynamicemb): cover LruLfu logic (policy, eviction, gather/scatter/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]>

* fix(dynamicemb): count LruLfu score words in load validation; add storage 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]>

* refactor(dynamicemb): fold LruLfu policy selection into get_score_policy

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]>

* refactor(dynamicemb): name LruLfu score spec "lru_lfu" + black formatting

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]>

* test(dynamicemb): cover LFU + need_incremental_dump in end-to-end score 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]>

* docs(dynamicemb): correct need_incremental_dump supported-strategy scope

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]>

* fix(dynamicemb): validate LruLfu load score shape with ValueError, not 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]>

* docs(dynamicemb): fix memory_usage() score-layout comment (AoS, not SoA)

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]>

* fix(dynamicemb): forward num_scores from erase() to the C++ kernel

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]>

* feat(dynamicemb): support tuple score_strategy, remove need_incremental_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]>

* test(dynamicemb): fix checkpoint column-order check in LruLfu round-trip

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]>

* feat(dynamicemb): export ScoreStrategy; rename test flag --need-incremental-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]>

* fix(dynamicemb): allow score_strategy=None in normalize_score_strategy

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]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
@jiashuy
jiashuy force-pushed the feat/dynamicemb-lru-lfu-score-strategy branch 3 times, most recently from 3c7e3c0 to a2e67b9 Compare July 20, 2026 07:26
gameofdimension and others added 12 commits July 22, 2026 12:06
…ffer (NVIDIA#439)

* Reduce SID-GR decode CUDA-graph memory with shared pool and shared logits buffer

Capturing the SID-GR decode CUDA graph at beam_width=1024 reserved a
private CUDA-graph memory pool and a [batch, beam, vocab] logits tensor
per captured graph (~30 entries), raising idle GPU memory from ~24 GiB to
~45 GiB and OOM-ing decode at the configured beam width. Both are fixed
without changing any computation, so outputs are numerically unchanged.

1. Shared graph private pool (CudaGraphCacheMixin)
   The prefill piecewise runner already shared one graph_pool_handle()
   across its captures; the decode runner did not and got a fresh private
   pool per capture. Hoist the lazy handle + pool= kwargs + env opt-out
   onto CudaGraphCacheMixin (deduplicating the two runners' identical
   helpers), and have each runner set a _separate_pools_env class
   attribute. Decode captures now reuse one pool instead of ~30.
   Opt-out: GR_INFERENCE_DECODE_CUDA_GRAPH_SEPARATE_POOLS /
            GR_INFERENCE_PREFILL_CUDA_GRAPH_SEPARATE_POOLS.

2. Shared logits output buffer
   lm_head logits ([batch, beam, vocab], ~batch*297 MiB at beam=1024) were
   held once per captured graph. Add an out= path to _linear_project
   (matmul out= into a caller buffer) and a logits_out= arg to
   forward_decode_step; the decode runner allocates one buffer per
   (active_beam_width, bucket) and writes every captured graph's logits
   into it, so the tensor lives once per shape rather than once per graph.
   Opt-out: GR_INFERENCE_DECODE_CUDA_GRAPH_SEPARATE_LOGITS.

New /status fields: decode_cuda_graph_shared_pool,
decode_cuda_graph_shared_output_buffers.

Measured on NVIDIA L20 46GiB (beam=1024, context_len=4000):
- idle after warmup: 45.4 -> 26.9 GiB (graph overhead ~21 -> ~3 GiB).
- beam=1024 decode that previously OOM'd now succeeds.
- graph-ON output_ids match the eager (graph-OFF) baseline token-for-token
  across single / batch2 / batch4 (24/24, 0 mismatch); replays confirm the
  shared path is hit.

Tests: 9 CPU unit tests added (test_cuda_graph_shared_pool.py,
test_decode_shared_logits.py) covering the pool-sharing helper (opt-out,
handle reuse, dedup contract) and the shared-logits buffer (_linear_project
out= correctness, per-(beam,bucket) caching).

Signed-off-by: gameofdimension <[email protected]>
Co-Authored-By: Claude Code
Co-Authored-By: GLM-5.2

* Free shared logits buffer when its decode shape is evicted

The shared logits cache (_shared_logits, keyed by (beam_width, bucket)) is
independent of the graph LRU, so a buffer allocated for a decode shape stayed
resident for the runner lifetime after _store_graph() evicted the last graph
using it. A transient large capture (high beam/bucket) could thus leave its
[bucket, beam, vocab] tensor resident and re-grow idle memory after eviction,
undermining the memory bound this change adds.

Override _store_graph in GRDecodeCudaGraphRunner: after the base store (which
performs LRU eviction), drop shared logits buffers whose (beam_width, bucket)
shape has no live graph entry, tying buffer lifetime to graph lifetime.

Tests: two CPU tests in test_decode_shared_logits.py — eviction frees the
orphaned buffer, and a shape shared by multiple graphs is kept until its last
graph is evicted.

Signed-off-by: gameofdimension <[email protected]>
Co-Authored-By: Claude Code
Co-Authored-By: GLM-5.2

* Keep shared logits buffer for the just-captured entry when caching is off

With GR_INFERENCE_DECODE_CUDA_GRAPH_MAX_ENTRIES <= 0, the base _store_graph()
clears _graphs and returns without retaining the newly captured entry, so the
override's live_shapes set was empty and it deleted the shared logits buffer
that _capture had just wired into entry.output. The buffer itself was not freed
(the caller's immediate replay still reaches it via entry.output, which holds
the same tensor), but the cache entry was dropped on every capture -- defeating
per-shape reuse under max_entries=0 and leaving the override's correctness
dependent on that external reference.

Always add the just-stored entry's (beam_width, bucket) to live_shapes so its
output buffer stays in the cache through the immediate replay regardless of
whether the base store retained the entry. A no-op for max_entries > 0, where
the entry is already live.

Tests: test_shared_logits_buffer_kept_for_just_captured_entry_when_caching_disabled
covers the max_entries=0 path (fails without this change).

Signed-off-by: gameofdimension <[email protected]>
Co-Authored-By: Claude Code
Co-Authored-By: GLM-5.2

---------

Signed-off-by: gameofdimension <[email protected]>
…NVIDIA#400)

* Refactor KV cache backend split

Introduce KVCacheBackend, split the default Python backend from the public KVCacheManager facade, and add the initial export lookup path.

* Add export kvcache design outlines (temp)

* Support AOTI-compatible recsys kvcache ops

* Add end-to-end AOTI support for HSTU+KV-Cache inference

* Support PyTorch export and AOTI compile/package with test coverage.
* Support C++ Torch runtime validation for AOTI-compiled KV-cache graphs.
* Support Triton Inference Server validation using the PyTorch AOTI backend.
* Add required KV-cache/runtime/custom-op plumbing and export fake-op shims.

* Refactor KV-cache export/runtime cleanup and document AOTI flows

* extract and simplify HSTU KV-cache export wrapper
* remove stale debug instrumentation and export bring-up prints
* standardize macro-gated logging in KV-cache runtime/binding/client code
* rename AOTI ordering placeholder tensors consistently
* clean C++ replay demo logging and CUDA check behavior
* document end-to-end HSTU KV-cache AOTI C++ and Triton Server workflows

* Updated the documents for KVcache with aoti support

* Update Dockerfile with full aoti build

* Fix pytorch Dockerfile

* Fix Docker

* Support SM120 for hstu inference

* Setup folder for aoti related impl, and fix rebase conflicts

* Fix hstu kernel build for aarch64.

* Add code cleanup

* Rename `offload_flush` api

* Code cleanup

* Fix CI tests

* Fix review errors

* Fix CI error

* Update to formal fbgemm_hstu branch

* Cleanup kvcache server env var

* Fix CI error

* Fix CI error

* Fix CI error

* Update readme for inference_aoti

* Fix review error

* Fix review error

* Update documents with benchmark results

* Update the readme and doc

* Add tritonserver python backend as baseline

* Apply code and document cleanup

* Fix review errors
Express LRU+LFU eviction through the compound score strategy
(TIMESTAMP, LFU) (either tuple order): word0 = last-access timestamp,
word1 = frequency. By default eviction ranks by frequency with an
older-timestamp tiebreak; it can be fully customized via a user-supplied
score_function.

- score_function(scores, cur_timestamp) -> float64 is numba-compiled to
  LTO-IR and nvJitLink-linked into a prebuilt custom eviction cubin at
  registration time; the driver launches it for all 2-word eviction.
- The default path uses a prebuilt Lex (frequency -> older-timestamp)
  comparator cubin -- no numba required.
- Users index `scores` in logical (tuple) order; subscripts must be
  integer constants and are statically remapped to physical device words
  via score_dump_permutation, so (LFU, TIMESTAMP) works transparently.
- Custom cubins are cached per (device, function, score order).

Two prebuilt fatbins (Lex + custom) are compiled per-arch at build time
and shipped as package_data.

Tests: 18 table-level tests including whole-set eviction oracles for the
default timestamp tiebreak, custom decay, logical!=physical remap, and an
end-to-end BatchedDynamicEmbeddingTablesV2 path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
A full bucket can be evicted by the plain insert path (table_insert), not
just insert_and_evict. That path used DefaultEvictor -> the single-score
reduce(), which cannot read the 2-word AoS LruLfu layout, so a plain insert
that overflowed a bucket would pick a garbage victim (and ignore any custom
score_function). Only insert_and_evict was wired to the eviction cubin.

Route the num_scores==2 plain-insert eviction through the same cubin:

- Factor table_insert_kernel's body into insert_body<Table,KernelTraits,Evictor>
  so both the AoT kernel (DefaultEvictor) and the cubin (RankedEvictor<Comparator>)
  share it.
- Add a third cubin entry dyn_emb_insert_entry (reuses EvictParams; collects no
  evicted output) + demb_get_insert_fn(); resolved/cached like the evict entries.
- launch_table_insert_kernel routes PolicyType==LruLfu to the cubin (default Lex
  when score_fn_key==0, else the custom evictor); thread score_fn_key through
  table_insert and ScoredHashTable.insert().

The plain insert still drops the evicted key (unchanged semantics) but now
selects the correct victim (freq->ts tiebreak by default, or the custom decay).

Test: table.insert() overflowing a full bucket with _evict_high_freq_first must
evict the hot keys (DefaultEvictor would have kept them).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
- compile_evict_fatbins: add --expt-relaxed-constexpr / --expt-extended-lambda
  so the fatbin TU compiles kernels.cuh (<cub/cub.cuh>, cooperative_groups) with
  the same flags as the main extension build, avoiding cross-CUDA-version skew.
- jit_link.cpp load_from_image: cuModuleUnload the just-loaded module if any
  cuModuleGetFunction fails, instead of leaking it.
- jit_link.cpp link_custom: destroy the nvJitLinkHandle on every exit path via
  an RAII guard (jl_check / load_from_image can throw), instead of leaking it
  when linking fails.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
cuda.compile was given only the argument types, so numba inferred the return
type from the body. A score_function returning an integer expression (e.g.
`return -scores[1]` without a float() cast) would compile to an integer-register
return, which the C++ `extern "C" __device__ double user_score_fn(...)` caller
reads as junk double bits -- a silent miscompile that degrades eviction to an
arbitrary order. Pin the signature to float64(CPointer(uint64), uint64) so numba
casts the return value to double instead.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
- evict_lrulfu.cu header: three entry points (evict ovf/noovf + plain insert),
  reuses insert_body too -- not "two entry points, insert_and_evict_body only".
- score_jit.py docstring: register_score_function takes (cc_major, cc_minor).
- lru_lfu_score_strategy_design.md: replace the stale "no code written yet"
  status with an as-built banner (compound tuple instead of an LRU_LFU enum, no
  gamma, three cubin entries, plain insert also routes through the cubin);
  keep the body as the original design rationale, code is the source of truth.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
- DynamicEmb_APIs.md: add a "Customized eviction via score_function" section
  under DynamicEmbScoreStrategy (signature, logical-order indexing, numba-cuda
  requirement, worked example) and a score_function field entry under
  DynamicEmbTableOptions. Make the constraint explicit: score_function is
  supported ONLY for the two-word {TIMESTAMP, LFU} compound (scores length 2);
  any other score_strategy with a score_function raises ValueError.
- example/example.py: add an example lru_lfu_decay_score (time-decayed LFU) and a
  --score_strategy {step,timestamp,lru_lfu} flag that wires the compound
  (TIMESTAMP, LFU) tuple + score_function into DynamicEmbTableOptions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Scrub the remaining proposal-era divergences so the design doc describes the
shipped implementation (code stays the source of truth), keeping the rationale:

- Drop `lfu_decay_gamma` and the `(scores, cur_timestamp, gamma)` signature
  everywhere; the score_function is `(scores, cur_timestamp) -> float64` with any
  decay constant written in the body.
- No `LRU_LFU` enum: the strategy is the compound `(TIMESTAMP, LFU)` tuple;
  update the goal, API, example, and component table accordingly.
- score_function indexes `scores` in logical (tuple) order with a static
  logical→physical remap (not "zero remapping").
- Three cubin entries (`dyn_emb_evict_entry_ovf`/`_noovf` + `dyn_emb_insert_entry`)
  and plain insert also routes through the cubin (two call sites); fix the ABI
  struct (no gamma field), §11 entry/launch text, and the build-check.
- cuda.compile pins the float64 return type; module cache keyed by (device, key).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…e/order

- README.md: add a "Customized Eviction Score" section under Usage Notes (compound
  (TIMESTAMP, LFU) + score_function example, numba-cuda requirement, pointer to the
  API doc).
- DynamicEmb_APIs.md: add a "Compound (multi-score) strategies and score order"
  section that spells out, in user-facing terms, that a compound strategy keeps
  more than one score per key and that the tuple order controls two things that
  always agree — the score column order dumped to file, and how score_function
  indexes scores — while eviction is identical either way. Reword the
  score_function / score_strategy text to drop implementation details.
- lru_lfu_score_strategy_design.md: fold in the remaining LRU_LFU -> compound-tuple
  precision fixes (LruLfu spec/strategy/table naming, device-keyed cache) that the
  prior design-doc rewrite commit missed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
… guards)

Two cheap defensive guards on the JIT eviction path:

- UserFnComparator::rank clamps a NaN user score to -inf (evict-first). A NaN
  compares false against every candidate, so it could never be picked as the
  eviction minimum, and an all-NaN bucket would find no victim and silently drop
  the incoming key. Clamping keeps eviction deterministic and inserts progressing.
  Document the finite-return contract (comparator header + API doc).
- reduce()/reduce_ranked() assert num_scores_ == 1 / == 2 respectively, so a
  misrouted call fails loud instead of silently misreading the layout (nvcc is not
  built with -DNDEBUG, so the device assert is live). Guards a future regression;
  after the plain-insert routing both paths already send num_scores==2 to the cubin.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…lti-GPU)

score_function_key ignored the device compute capability, so on a single process
driving GPUs of different arch the custom score_function registered only the first
device's numba LTO-IR (the Python _registered_keys dedup short-circuited the
others). A later different-arch device then linked that LTO-IR under the wrong
-arch and cuModuleLoadData failed on its first custom-eviction insert.

Include cc in the key so each arch gets a distinct key -> its own numba compile
and C++ registration (cc is already stored per key, so link_custom picks the right
-arch). No C++ change needed. Same-arch devices still share one key/compile with
the module cached per device, so homogeneous setups are unaffected.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@jiashuy
jiashuy force-pushed the feat/dynamicemb-lru-lfu-score-strategy branch from 9579353 to f2b242d Compare July 30, 2026 09:16
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.

4 participants