Skip to content

Chained only - #5

Open
jiashuy wants to merge 44 commits into
mainfrom
chained-only
Open

jiashuy wants to merge 44 commits into
mainfrom
chained-only

Conversation

@jiashuy

@jiashuy jiashuy commented Oct 25, 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 30 commits October 24, 2026 10:00
…ement core; external storage as a third tier

Squash of the lw-cache-wip branch (31 commits) for review.

- New src/embedding_cache: lock-free placement and reference protection
  (node state, reclaim queue, row pool kernels, evict-by-key, eviction
  guard), bound as EmbeddingCacheCore. DynamicEmbCache is now a thin
  Python wrapper over it; the old score-carrying cache is gone.
- DynamicEmbStorage drives the cache through an eager prefetch flow
  (backing store first, then cache), including determinism mode, with
  in-place flush.
- The backing insert takes the cache's eviction guard and can report each
  evicted key, its table and the slot it held (collect_evicted).
- External storage (a parameter server) as the tier below the table: a
  miss is looked up there, an evicted row is written there.
- The prefetch's tensors are recorded on the stream that consumes them.
- The unused overflow buffer is removed from the hash table, the CUDA
  kernels, the JIT eviction ABI and the INFERENCE_EMB::table_lookup
  schema (three trailing optional arguments; models exported against the
  old schema need re-exporting).
- Evicted keys are matched to the same insert's keys by the whole
  (key, table_id) pair, not a folded value; the deterministic insert
  returns its evicted tensors cut to num_evicted.
- Design docs, benchmark results and a component architecture review.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Design notes for a new key index that lives beside the existing one: a
chain inside each bucket, value rows from a global pool, a two-phase
step (find_and_stage, then commit), eviction reduced once per bucket,
and the guard kept for pinning. Lists the open risks and the staged plan.
No code changes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…x design

Eviction scope is the 128-slot bucket, eviction makes room for the step
only, determinism is on only under DEMB_DETERMINISM_MODE and only
self-consistent, and the new formats do not read the old ones.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
A key index with value rows apart from slots: a chain inside each bucket,
rows from a pool, find_and_stage / commit / release_rows, victims chosen
once per bucket, the cache's eviction guard honoured. One table, one score
word, a bucket that cannot make room is an error. It sits beside the
existing index and changes nothing of it. See
docs/chained_bucket_index_design.md.

Tested against a model slot for slot (26 tests); lookup is 1.8x to 9x
faster than the existing index on a 16.7M-slot table, a whole step is
slower at small batches because the sorting and bookkeeping are still done
in python.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Several tables behind one launch (a device array of table views), a
table grown on its own by moving only its keys, a table that never
evicts growing when a bucket cannot hold its keys, and a count of
references per row that keeps a row from being chosen as a victim.
The sorting and bookkeeping are still done in python; the next commit
moves them into C++.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Staging the misses, sorting by bucket, cutting runs, taking rows, placing
and putting rows back in input order are now kernels and cub calls, with
the row pool's stack top on the device. A step costs two small host
synchronisations. The design document records what stage two delivered,
the measurements, and the place kernel as the next thing to speed up.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… a lane per key

Victim choice keeps each lane's scores in registers and costs a warp
reduction per victim. Placement takes 32 new keys at a time, one per lane:
victims leave their chains (one lane per chain, the others in parallel),
the records are written, the new keys join their chains in lane order.
About a quarter faster than before; a whole step of 524288 new keys on a
full 16.7M-slot table is 1.5x the existing index. Tests gain three shapes
that put more than 32 new keys, and several on one chain, in one bucket.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
DEMB_CHAINED_INDEX (experimental) makes the module's storage a
ChainedStorage: the backing behind a cache, or the HBM-direct table, with
or without a tier below. Prefetch finds and stages, asks the tier below,
decides admission, gives the cache its nodes, and only then places the new
keys and makes room, so the victims' rows are intact when they are read
and nothing is copied out ahead of a write. Training, flush and eval
lookup are covered; checkpoints are not.

Twelve end-to-end tests (every key must end at 1 - lr * uses, however
often it was evicted and brought back; a dropping lower tier must fail
the check), the old path's whole suite unchanged. A training step is
1.05x (HBM-direct) and 1.45x (cache) the existing index on a full
4.2M-row table.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ed, and growing

Two tables step by step against the existing index, with and without
frequency admission and for two score strategies; a prefetch on its own
stream while the previous backward is still queued (the cache layout
crashes without the stream bookkeeping); growth toward the maximum
capacity. The main test file also runs under DEMB_CHAINED_INDEX with the
two storage-type assertions relaxed: the forward/train/eval matrix and the
backward tests pass; what fails reads the old index's internals or
checkpoints.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…emental dump and replay

Checkpoints reuse the existing file formats and helpers through a view of
the chained index that answers what they read. Erase fills a hole with the
bucket's last record. Incremental dump is the existing one; replay goes key
by key, and removes what the source evicted or erased. Host-only layouts
run on the chained storage too.

88 chained tests, the old path's suite unchanged, and under
DEMB_CHAINED_INDEX the forward/train/eval matrix (160), the backward group
(97) and the dump/load group (43) pass. What still fails there needs
compound scores, buckets over 256, slot-for-slot replay, or reads the old
index's internals.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The compound strategy ranks by frequency, then by age, then by slot. A hit
sets the timestamp and adds to the frequency. Checkpoint and incremental
dump read the pair through a map from rows to slots that the index view
builds when the table last changed.

13 more chained tests (model slot for slot, the ordering, erase and growth
keeping both words, end to end with a tier below, against the existing
index). Under the chained index the existing incremental-dump suite (18),
the pop-evicted tests (5), the collect tests (13) and the distributed
incremental dump on 1 and 8 ranks now pass; what still fails reads
slot-for-slot replay, buckets over 256, or a step with more new keys in a
bucket than it has slots.

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

INFERENCE_EMB::table_lookup, exportable_tables.py and lookup_meta.py are
byte-identical to upstream again, and so are the python binding and the
declaration of table_lookup: the three overflow arguments are back in the
signature, and a request that gives a buffer is refused (nothing ever did).
A model already exported against the op loads and runs as before.

Checked against an upstream build with one probe run on each tree: table_insert
to fill the storage, the op with seven arguments and with the ten of the old
schema, torch.export of a module that calls it, and the fake kernel give the
same answers (debug_inference_check/, not tracked).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
An HBM tier and a host tier over the chained index, disjoint: new keys go to
the HBM tier, what it evicts goes down to the host tier with its score,
lookups ask the HBM tier and then the host tier, updates stay where the key
is. Checkpoints write the host tier and append the HBM tier; incremental dump
and replay run over both. find updates the scores of a training step's
accesses, which host-only and hybrid rely on.

All five layouts now pass the forward/train/eval matrix (160), the backward
group (97) and the dump/load group (43) under DEMB_CHAINED_INDEX.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…d training path is deleted

DynamicEmbStorage, HybridStorage, the old prefetch paths and the NO_EVICTION
score kernel are gone; BatchedDynamicEmbeddingTablesV2 always builds
ChainedStorage / ChainedHybridStorage. The pieces the inference ops use are
untouched.

Tests that read the old internals are removed or ported. Porting turned up two
bugs, both fixed: ChainedStorage.load read two-word scores as one word and did
not undo the logical column order, and a configured bucket_capacity above 256
(the planner default asks for the maximum) is now lowered to 256 instead of
raising.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
bucket_capacity must be a multiple of BUCKET_ALIGNMENT and at most
MAX_BUCKET_CAPACITY, which is now 256 (the most slots a bucket of the chained
index takes) instead of the old 'one bucket for the whole table' sentinel.
It is checked when the options are built, not lowered at each place a storage
is made. max_load_factor must be in (0, 1], and a custom score_function, which
the chained index cannot honour, is refused at once.

safe_check_mode and DynamicEmbCheckMode are removed: nothing reads them any
more, since a step that does not fit raises ChainedTableFull. The call sites in
examples/hstu, the tests, README and the API doc follow.

Tests: replay tests that encoded slot-for-slot replay are rewritten for replay
by key or removed; the forward-only scripts run a backward, because a training
forward holds its rows until then; the distributed pop-evicted test gets a table
that holds the keys of one step.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
bucket_capacity is any positive number. One not smaller than the per-rank rows
(MAX_BUCKET_CAPACITY always is) makes the table one bucket of exactly those
rows; otherwise the rows are rounded up to a multiple of it. BUCKET_ALIGNMENT is
gone, and bucket_capacity now takes part in what groups tables into a storage,
so the tables of a storage share it.

The chain links (head, next) are 2 bytes wide, or 4 when four times the bucket
capacity does not fit in 2. A bucket of more than 256 slots chooses its victims
by scanning for the smallest rank above the last one chosen, instead of out of
registers; the dead mark of a leaving key moves from shared memory to the top
bit of its row, so nothing is sized by the bucket any more.

Tests: large buckets and 4-byte links against the model, link width by capacity,
the alignment test over 128, 1024 and the one-bucket sentinel.

Not yet built or run on a GPU.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ions are one component

MixedDimBuffers holds the buffer of each table, the dimensions of every table (on
the device, on the host, as a list), the widest of them, whether all allow 4-wide
access, and the device array of buffer pointers -- and the operations on them,
kernel calls included: load and store of rows (padded to the widest table, or one
table's own compact rows), growing a buffer with its pointer refreshed, applying
the optimizer to stored rows or to padded rows, and resetting optimizer states.

DynamicEmbTableState keeps a single 'values' in place of eleven fields, and
load_from_flat, store_to_flat, their single-table variants and get_table_ptrs are
gone. A hybrid tier whose bucket is as large as the whole table is one bucket of
the tier's size; a storage no longer lowers the bucket to the table's maximum.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…knows no optimizer

DynamicEmbCache(options, value_dims) keeps its MixedDimBuffers, its options and the
size of a wave of threads, and nothing else: no DynamicEmbTableState, no optimizer.
The Cache interface only ever dealt with keys; what is done to the values (the
optimizer update, the initial optimizer state) is the user's. The width of each
value row is passed in by whoever knows the optimizer. create_cache_state and the
cache's unused init_optimizer_state and evict_strategy are gone, and the memory
report takes (values, options).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…on the device, a CacheCore

DynamicEmbCache(capacities, values): the buffers are made by whoever owns the
module, and the cache has neither options nor a thread count. Its metrics are a
CacheMetrics dataclass instead of the first four slots of a ten-slot tensor.

The cache's offsets (where each table's keys start, the total last) are int64
tensors on the device, in Python and in C++: lookup_pin, allocate, publish and
release are each one launch for all the tables, block row y being table y, and
read their range from the offsets themselves. The host never reads them, and
the prefetch's per-table counts no longer have to be copied to it. lookup_pin no
longer compacts its misses, which nothing used. Queues get a device array like
the maps, and allocate takes a snapshot of every table's.

EmbeddingCacheCore is renamed CacheCore: it places keys and holds references, and
there is nothing of embeddings in it.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… storage layout and its builder get a module

RowExchange moves value rows between a cache and the storage behind it. Giving a
cache node to another key writes the old key's row back to its row in the storage
and brings the new key's row in, and the two touch the same node, so one kernel
takes a node per block and does both: every thread reads its columns of the old
row and of the new one before it writes either. The cache prefetch's four copies
and the staging tensor of every victim become one swap, and a storage in host
memory sees the write-back and the fetch cross the link in opposite directions at
once. Rows are copied as raw words of 16, 4 or 2 bytes, whatever the element type.

storage_layout.py holds StorageLayout and build_storage, which picks the layout
from the tables' values against their HBM budget and builds it, returning a
StorageBundle(layout, storage, cache, exchange). BatchedDynamicEmbeddingTablesV2
calls it and no longer decides or builds layouts.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
A GPU pays a fixed price for each random row it reaches in host memory, whatever its
width: 10 ns a row from a table up to 256 MB, 34 ns from 13 GB, which is where the
translations stop fitting. Rows in order are about twice as fast. The fused kernel paired a
node's old row with its new one, so it could not put both lists in order, and the two
directions of the link did not overlap.

The victims are now gathered into a staging buffer, sorted by the storage row they go back
to, and one kernel takes item i of the two lists, each sorted on its own: the i-th victim
out, the i-th fetched row into its node. A node with nothing to fetch keeps its row.
Measured on an H100 with 200K rows a step: sgd 12.9 ms to 5.4 ms, adam 14.9 ms to 9.0 ms,
68 GB/s both ways, about 68% of what cudaMemcpy does in both directions at once.

Also a model-based test of 40 steps over two tables, and a benchmark of the swap alone.
Everything else tried -- a CPU gather and scatter through pinned buffers on several streams,
in chunks, a paired kernel over a pinned buffer -- is on the branch
row-exchange-experiments.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…; MixedDimBuffers knows no optimizer

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… strategy; the scattered score helpers go

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…wer tier, beside tier, retain as a wrapper)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…row face on the user's Storage

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
jiashuy and others added 14 commits October 25, 2026 12:59
… and eval lookup get modules of their own

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…/ and training/ packages; component tests get a directory

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…kpointer, ShardInfo and the file-name helpers get their own modules

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…heckpoint/files.py, a table's row export and write are storage/row_io.py

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ws, for comparing row by row with a dense table

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… free stack, taking and giving back, identity rows; the index only places keys

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ws in chunks before a key takes them; a new key is brought from its row like any other

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…as built, and what is left

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… run in unit_test.sh

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…e, namespace cache, test/cache, cache_assert.h

Not yet built or tested on EOS when committed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… run in run_tests.sh

rows.cuh (writeback, fill, publish) is built into nothing: RowExchange moves the rows now,
and the module-level tests check their values. Not yet built or run on EOS when committed.

Co-Authored-By: Claude Sonnet 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.

1 participant