Skip to content

[FEA](DynamicEmb) intput per key score by PRECISE_CUSTOMIZED score strategy - #530

Merged
shijieliu merged 10 commits into
NVIDIA:mainfrom
jiashuy:feat/dynamicemb-per-key-score
Nov 3, 2026
Merged

shijieliu merged 10 commits into
NVIDIA:mainfrom
jiashuy:feat/dynamicemb-per-key-score

Conversation

@jiashuy

@jiashuy jiashuy commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Per-key int64 score input for EmbeddingCollection / EmbeddingBagCollection

Summary

Add a per-key int64 score input to DynamicEmb's EmbeddingCollection (EC) and EmbeddingBagCollection (EBC). The caller supplies one score per key, and the score decides which rows the table evicts. The feature is exposed as a new score strategy, DynamicEmbScoreStrategy.PRECISE_CUSTOMIZED, and the input is a ScoredKeyedJaggedTensor.

Scores travel on their own channel and are kept separate from the LFU frequency counters. A table uses either frequencies (LFU) or per-key scores (PRECISE_CUSTOMIZED), never both, and a single function (score_source) chooses between them on every path.

The PR has 8 commits: two preparatory ones, the feature, three fixes found in review, and one refactor.

Motivation

Existing strategies (TIMESTAMP, STEP, LFU, CUSTOMIZED) derive the score from the table itself: access time, step, hit count or one scalar per call. Some models know better which rows matter, for example a business weight or a user tier per key. PRECISE_CUSTOMIZED lets the caller state that importance for each key instead of one value for the whole batch.

Usage

DynamicEmbTableOptions(
    score_strategy=DynamicEmbScoreStrategy.PRECISE_CUSTOMIZED,
    ...
)

features = ScoredKeyedJaggedTensor.from_kjt(kjt, scores)  # scores: int64, one per key
out = ec(features)

A repeated key in one batch keeps the largest of its scores (MAX). A later batch assigns the new score to the key.

Changes

Preparation

  • Carry int64 weights through bucketize (446536b)
    • block_bucketize_sparse_features accepts int64 weights next to float32. The kernel only copies each weight to its new position, so both are bit-exact.
    • segmented_unique_cuda gets a reduce argument ("sum" by default, "max", "min") for combining the values of a repeated key. It also checks that input_frequencies is int64, on the keys' device and contiguous. Any other dtype used to be misread silently.
  • Decide frequency counting per sharding and per kernel group (63e021b)
    • ShardedDynamicEmbeddingCollection took is_lfu_enabled and has_admit_strategy from the first table only. A collection whose first table was not LFU gathered no frequencies for the LFU tables after it, and one whose first table was LFU handed frequencies to tables that never asked for them.
    • The answer is now computed per sharding type (collect_frequency_requirements), and ctx.frequency_counters has one entry per sharding. BatchedDynamicEmbeddingTablesV2 keeps counters only if its group evicts by LFU or admits.

Feature

  • ScoredKeyedJaggedTensor (scored_kjt.py) is a KJT with a per-key int64 _scores tensor. from_kjt, get_scores, without_scores, split, permute, to and record_stream all keep the scores.
  • Config (dynamicemb_config.py)
    • New enum value PRECISE_CUSTOMIZED = 5.
    • It is only allowed as (NO_EVICTION, PRECISE_CUSTOMIZED) among compound strategies.
    • DynamicEmbTableOptions.takes_score_per_key reports whether a table uses it. Combining it with admit_strategy raises ValueError.
  • Input dist (shard/input_dist.py, shard/rw_sharding.py)
    • Scores are sent by a separate all2all (_ScoredSplitsAwaitable) and permuted with the keys.
    • Whether to send scores is decided the same way on every rank, so the collectives cannot diverge.
  • Dedup (shard/embedding.py): when index dedup is on, scores of duplicate keys are merged with largest_score_per_unique_key (a scatter_reduce_ amax).
  • Storage and prefetch (key_value_table.py, batched_dynamicemb_function.py, batched_dynamicemb_tables.py)
    • score_source(state, frequency, key_scores) is the single place that picks the score input: LFU gets the frequency, CUSTOMIZED and PRECISE_CUSTOMIZED get the key scores, anything else gets none.
    • It is used by get_find_score_arg/_find_keys, the cache lookup and load path, and the three prefetch paths (cache + storage, HBM direct, generic). The public Storage.find signature is unchanged.
    • In the cache + storage path the storage owns the scores and the cache ranks by timestamp only. Scores of rows that miss the cache go through flagged_compact together with the keys.
    • Cache write-back uses preserve_existing=True so it does not overwrite a stored score.
  • Validation (BatchedDynamicEmbeddingTablesV2._check_scores)
    • Scores must be int64, with one value per key.
    • A negative score follows DynamicEmbCheckMode: ERROR raises, WARNING warns, IGNORE skips the check.
    • set_score rejects per-key tables, and scores are record_stream'd on the prefetch stream.

Fixes made during review

  • Record per-key scores on the prefetch stream (aa8cdff): the scores tensor could be reused by the allocator while the prefetch stream was still reading it.
  • Index dedup merges scores only when the input carries them (2df92aa): evaluating a plain KJT with dedup enabled called scores() on a non-scored input and failed.
  • Drop scores on every rank in evaluation (36d4fd2): if some ranks passed scores and others did not, the ranks entered different collectives and the job hung. In eval every rank now drops the scores with without_scores.

Refactor

  • Take a score per key through DynamicEmbScoreStrategy.PRECISE_CUSTOMIZED (50299d6): the first version used a separate per_key_score table option. It is replaced by the new strategy, and per_key_score is removed (no deprecation path, the option never shipped). The Hybrid-storage rejection is moved to the place that creates the storage.

Restrictions

The PR refuses a configuration with a clear error instead of working around it:

  • Row-wise sharding only. Other sharding types do not support scores.
  • No variable batch embeddings (VBE).
  • HybridStorage is not supported (NotImplementedError), because it has no need for scores for now.
  • No admit_strategy, and no compound with LFU, TIMESTAMP or CUSTOMIZED.
  • All-or-none: either all tables in a collection use PRECISE_CUSTOMIZED or none do, and the collection must hold only DynamicEmb tables.
  • While training, the input must be a ScoredKeyedJaggedTensor. Evaluation does not need scores, and they are dropped.

Tests

New tests are registered in test/unit_test.sh:

  • test/unit_tests/per_key_score/test_per_key_score.sh runs, in one script:
    • pytest on test_scored_kjt.py, test_scored_bucketize.py and test_per_key_score_options.py (76 cases);
    • a 2-GPU torchrun of test_per_key_score_dist.py, which covers input dist with and without dedup, EC scores under default, dedup, caching, host-only, (NO_EVICTION, PRECISE_CUSTOMIZED) and reverse-order inputs, dump/load, evaluation without scores (including ranks with mixed inputs), negative scores, EBC pooled scores, and the Hybrid refusal.
  • test_int64_weights_channel.py and the reduce / dtype cases in test_unique_op.py.
  • test_frequency_requirements.py, test_frequency_counter_guard.py and a mixed LFU/TIMESTAMP collection in test_lfu_scores.py (test_lfu_scores.sh is new).

Results on 50299d6, freshly synced and rebuilt on an 8×H100 EOS node:

  • unit_test.sh fwd_bwd: 26 test files, 0 failures. This includes per-key score (76 pytest cases and "per-key score distributed ok") and TWRW ("all modes passed").
  • unit_test.sh load_dump: 5 test files, 0 failures. This covers admission, 72 dump runs, hash_roundrobin, table scope, 144 cross-GPU loads, incremental dump and table_row_wise.

Docs

  • DynamicEmb_APIs.md: PRECISE_CUSTOMIZED added to the strategy listing, plus a new "Per-key score" section covering usage, MAX merging and the restrictions.
  • README.md: usage note on feeding scores.

Compatibility

  • No behavior change for existing strategies. The change to Storage.find is internal: its signature is the same.
  • The frequency fix (63e021b) changes behavior only for collections that mix LFU and non-LFU tables. Before the fix those collections were wrong.
  • block_bucketize_sparse_features and segmented_unique_cuda keep their float32 and sum defaults.
  • The C++/CUDA changes (unique_op.cu, bucketize) need the extension to be rebuilt.

Checklist

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

@greptile-apps

greptile-apps Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with a non-blocking gap in negative-score checks when index dedup is enabled.

Findings

  1. P2 Dedup hides negative scores ▶

Summary

Adds per-key int64 eviction scores through PRECISE_CUSTOMIZED and ScoredKeyedJaggedTensor.

  • DynamicEmb tables use an input score for each key when choosing rows to evict.
  • Mixed LFU collections collect counters for the tables that need them.

The previous-review merge bases differ, so this review used the full PR changes. No runtime tests were run.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
    A[Keys and per-key scores] --> B[Row-wise distribution]
    B --> C[Merge repeated keys using MAX]
    C --> D[Check scores]
    D --> E[Assign storage scores]
    E --> F[Read embeddings]
    F --> G[Backward updates values only]
Loading

Reviews (6) · Last reviewed commit: "[FIX](DynamicEmb) Keep external stores w..." · Reviewed by Greptile

@jiashuy

jiashuy commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator Author

I am planning to remove the per_key_score option and instead extend DynamicEmbScoreStrategy, e.g. DynamicEmbScoreStrategy.PRECISE_CUSTOMIZED

@jiashuy jiashuy changed the title [FEA](DynamicEmb) per key score support for CUSTOMIZED score strategy [FEA](DynamicEmb) per key score support for PRECISE_CUSTOMIZED score strategy Nov 1, 2026
@jiashuy

jiashuy commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

Unit tests passed

@jiashuy jiashuy changed the title [FEA](DynamicEmb) per key score support for PRECISE_CUSTOMIZED score strategy [FEA](DynamicEmb) per key score support by PRECISE_CUSTOMIZED score strategy Nov 1, 2026
@jiashuy jiashuy changed the title [FEA](DynamicEmb) per key score support by PRECISE_CUSTOMIZED score strategy [FEA](DynamicEmb) intput per key score by PRECISE_CUSTOMIZED score strategy Nov 1, 2026
@jiashuy
jiashuy force-pushed the feat/dynamicemb-per-key-score branch from 50299d6 to a3e04f2 Compare November 2, 2026 09:12
jiashuy and others added 10 commits November 3, 2026 07:04
…ique max/min

Per-key scores will ride the KJT weights channel as int64. Prepare the two
pieces that act on that channel before the feature itself lands:

- block_bucketize_sparse_features: accept int64 weights next to float32. The
  kernel only copies each weight to its new position, so both are bit-exact.
- segmented_unique_cuda: add a `reduce` argument ("sum" default, "max",
  "min") for combining the values of a repeated key. node_freq starts from
  the identity of the reduction so a representative and its duplicates can
  reduce into it in any order.
- segmented_unique_cuda: check that input_frequencies is int64, on the keys'
  device and contiguous; the kernel reads it as raw int64 and any other
  dtype was silently misread.

Tests: test_int64_weights_channel (bucketize, permute, split keep int64
weights bit-for-bit) and reduce / dtype cases in test_unique_op, both
registered in unit_test.sh.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…el group

ShardedDynamicEmbeddingCollection took is_lfu_enabled and has_admit_strategy
from the first table only (shard() broke out of its loop after one table), so
a collection whose first table was not LFU gathered no frequencies for the LFU
tables after it, and one whose first table was LFU handed frequencies to
tables that never asked for them.

- collect_frequency_requirements groups tables by their sharding type and
  answers "any LFU / any admit" per sharding; the collection keeps the answer
  per sharding and the dedup and input dist read it by sharding index.
- ctx.frequency_counters gets one entry per sharding, None where the sharding
  needs none or its input is empty, so it stays aligned with the shardings.
- BatchedDynamicEmbeddingTablesV2 keeps frequency_counters only if its group
  evicts by LFU or admits; a CUSTOMIZED group next to an LFU one receives the
  counters riding the sharding's weights channel and now drops them.

Tests: per-sharding requirements, the kernel-group guard, and an
end-to-end mixed LFU/TIMESTAMP collection in test_lfu_scores.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…nd EmbeddingBagCollection

A table can take a score per key from the input instead of one score per
batch (`DynamicEmbTableOptions.per_key_score`).

- `ScoredKeyedJaggedTensor`: a KeyedJaggedTensor with an int64 `scores`
  tensor beside the values, kept in step by split/permute/to.
- Scores go through their own all2all and are placed beside their keys by
  the bucketize permutation; they stay a separate channel from the
  frequency counters (LFU / admission).
- Tables hand the scores to the key map through one `score_source`, which
  picks the frequency for an LFU table and the input scores for a
  CUSTOMIZED one. A key repeated in a batch keeps its largest score (also
  with `use_index_dedup`); a later batch assigns.
- cache path: new keys enter the storage with their own score; the
  unused score/in_storage arguments of `_load_storage_values` are gone.
- Rules: row-wise only, CUSTOMIZED (alone or with NO_EVICTION), no
  admit_strategy, no VBE, DynamicEmb tables only in the collection, no
  HybridStorage; every table of a collection sets it or none does.
- Tests under test/unit_tests/per_key_score, one entry in unit_test.sh;
  docs in DynamicEmb_APIs.md and README.md.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…eded in eval, more tests

- A negative score warns under safe_check_mode WARNING and raises under
  ERROR; all-IGNORE tables are not checked.
- Evaluation reads no score: a collection that takes a score per key
  accepts an input without scores while not training, and sends the scores
  only when the input carries them.
- Tests: host-only storage (generic path), (NO_EVICTION, CUSTOMIZED), an
  input whose features are not in the tables' order, dump then load,
  evaluation without scores, negative scores under WARNING / ERROR.
- Docs follow.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The kernels that read the scores in prefetch are queued on the current
stream and can run after the caller has released them; a caller that made
them on another stream would see the memory reused underneath those
kernels. Record them on the current stream on every prefetch call.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…es them

Evaluation may go without scores, but the dedup before the all2all called
scores() whenever the collection takes a score per key, so an unscored
evaluation input failed with use_index_dedup. Merge scores only from an
input that is a ScoredKeyedJaggedTensor; test unscored evaluation with
dedup enabled.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Whether the input distribution sends the scores followed each rank's own
input type, so ranks given different kinds of evaluation input issued
different collectives and could hang. Evaluation reads no score: a
collection that takes a score per key now drops them from the input before
distribution, on every rank, and sends none. Test an evaluation where
ranks are given different kinds of input.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…y.PRECISE_CUSTOMIZED

Replace the per_key_score table option by a score strategy of its own:
PRECISE_CUSTOMIZED, alone or as (NO_EVICTION, PRECISE_CUSTOMIZED). The input
must be a ScoredKeyedJaggedTensor while training. It is stored like
CUSTOMIZED (same policy and score name); what differs is where a score
comes from.

- takes_score_per_key() / DynamicEmbTableOptions.takes_score_per_key replace
  the field; the strategy is already part of the group key, and combining it
  with LFU, TIMESTAMP or CUSTOMIZED is refused by the compound-strategy
  check. admit_strategy is still refused.
- HybridStorage is refused before it is built, instead of after.
- Tests and docs follow; a test that HybridStorage is refused is added.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
TrainPipelineSparseDist replaces each input_dist._dist.forward with
KJTAllToAllForward, which returns KJTSplitsAllToAllMeta (the metadata of a
splits all2all the pipeline fuses across modules), not an awaitable.
_ScoredSplitsAwaitable then called wait() on it and failed, and the fused
path rebuilds the keys' tensors awaitable itself, so it has no channel for
per-key scores.

Refuse it for now: RwSparseFeaturesDist.forward raises NotImplementedError
when it has scores to send and the keys' distribution is the fused metadata.
Evaluation sends no scores and is not affected.

Tests: check_train_pipeline_is_refused swaps in KJTAllToAllForward as the
pipeline does and checks training raises and evaluation does not.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…when given

_generic_forward_path passed key_scores to every Storage.find, None included.
With caching=False and no HBM budget for values, an external_storage is the
only tier and is called there directly; one written against the interface
from before per-key scores (PyDictStorage) has no such parameter, so an
ordinary training forward raised TypeError.

- Pass the keyword only when per-key scores are supplied.
- Refuse score_strategy PRECISE_CUSTOMIZED with an external_storage that is
  the only tier, when the tables are built.

Tests: check_external_storage_alone_is_refused.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@jiashuy
jiashuy force-pushed the feat/dynamicemb-per-key-score branch from a3e04f2 to 1669375 Compare November 3, 2026 01:35
@shijieliu
shijieliu merged commit 0d5b612 into NVIDIA:main Nov 3, 2026
1 check passed
shijieliu added a commit to shijieliu/recsys-examples that referenced this pull request Nov 8, 2026
Merge main up to c6e2bb2 (NVIDIA#514, NVIDIA#530, NVIDIA#532, NVIDIA#498 and three HSTU
inference commits). Main's per-key scores and per-sharding frequency
counters meet the hierarchical dist in the sharding's Python:

- Per-key scores (PRECISE_CUSTOMIZED) travel beside the keys in their own
  tensor; the hierarchical dist does not carry them. A row-wise
  EmbeddingCollection whose tables take a score per key raises under
  output_dist="fused" when it is sharded, and takes TorchRec's dists with
  the usual warning under "auto".
- Frequency counters are decided per sharding. The hierarchical path reads
  its sharding's entry and gives the op weights exactly when
  _dedup_indices attaches them.
- A rank with no keys for a sharding that counts frequencies sends an
  empty weights tensor, so every rank sends the same tensors (on main the
  ranks' all2alls could differ there).
- GroupedEmbeddingsLookup keeps one prefetch, which passes index dedup's
  frequency counters and now main's scores; LFU scores and admission
  counts under a prefetch pipeline then match the plain loop on TorchRec's
  dists too. BatchedDynamicEmbedding.prefetch, which nothing calls, goes.
  PrefetchState.record_stream also records the unique scores.
- unique_op.cu: main's reduce and the shared chain insert merge cleanly.

test_hier_dist.py checks the per-key-score rule under "fused" and "auto",
and LFU with no keys on the last rank. The tests of both sides pass on 1
and 2 nodes.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants