Trillion Parameter Scale Recommendation Models on PyTorch: Productionizing Continuous Training, Export, and Low-Latency Inference
Modern recommendation systems operate over massive, constantly changing catalogs. Every day, millions of short videos, images, and other content items are created, shared, and consumed, and recommendation models decide what each user sees next. Large-scale deployments often rely on hundreds of deep learning models in production. Many are relatively small, with parameter storage ranging from a few gigabytes to under 20 GB, and serve as lightweight rankers, retrieval towers, or models specialized for particular product surfaces. The most critical models, however—the main rankers—can be substantially larger. Architectures such as RankMixer and HSTU support feature interaction and user-behavior sequence modeling, alongside a sparse component comprising dozens to hundreds of embedding tables keyed on IDs such as item_id, creator_id, and user_id. This sparse component often dominates the parameter count, reaching the trillion-parameter scale in the largest systems and occupying hundreds of gigabytes to terabytes on disk, depending on quantization. Snap faces these same challenges across its visual-first product surfaces, including Stories, short videos, and Lenses.
Model architecture. At a high level, the large ranking models in the industry share a common layout: a sparse embedding layer looks up the IDs and other categorical features, and its outputs feed two dense modules that are stacked rather than run side by side. A sequence module encodes the user’s activity history together with the candidates, and its outputs become additional input tokens to a feature-interaction module, whose output goes to the multi-task prediction heads. For feature interaction, RankMixer replaces the hand-designed cross layers of earlier rankers (DCN, DHEN, and similar) with a Transformer-like block built for hardware efficiency. The embeddings of the non-sequence features are grouped and projected into tokens of width D, the sequence-module outputs are appended as additional tokens, and together they form X ∈ ℝT×D. Each layer first applies a parameter-free multi-head token mixing step, which splits every token into H heads and regroups the h-th head of every token into a new token. It then applies a per-token FFN (PFFN), where each token position has its own weights instead of sharing a single FFN:

With H=T, the token grid keeps its shape from layer to layer. Everything reduces to dense matmuls over a fixed-size grid, which is why RankMixer scales to billions of dense parameters at high GPU utilization. For user activity, HSTU treats the user’s history of (item, action, timestamp) events as a sequence of n tokens and stacks layers of pointwise gated attention:

Here f₁,f₂ are linear layers, φ₁,φ₂ are SiLU, and rabp,t is a relative attention bias over position and time. Replacing softmax with SiLU keeps the attention weights unnormalized, so the model retains how strongly a user engaged rather than only the relative ranking of past events. In ranking, the candidate items are appended to the history. The attention mask lets candidates attend to the history but not the other way around, so the history’s keys and values do not depend on the candidates. This property makes the history KV cacheable per user, which is what we exploit with FlexKV in Section 2. The HSTU outputs at the candidate positions are then projected to width D and appended to RankMixer’s token set. This lets the interaction layers cross the user’s sequence representation with every other feature.

When we look closely at these online ranking models, two challenges stand out.
Large and dynamic vocabularies. Features like item_id have vocabularies that are both enormous and never stationary. Everyday, millions of new items are created and added to the vocabulary. Short-form content has a short shelf life, so many of the IDs being ranked at any moment did not exist a few days earlier. A static, hash-bucketed embedding table forces a bad trade-off: if we size it for today's vocabulary, collisions corrupt tomorrow's new items, and if we over-provision it, we waste HBM on rows that are never touched. Worse, a brand-new item lands in a shared, stale bucket during exactly the hours when ranking it well matters most. Dynamic embeddings (DE), which are hash tables that admit new IDs on the fly and evict cold ones, remove this trade-off and let the model represent each new item as it appears.
Shifting distributions. Even for IDs the model already knows, the world keeps moving. Content popularity spikes and decays within hours, user interests drift, and seasonal and viral effects reshape engagement faster than any batch retraining cycle. A full retrain of a large ranking model takes days of multi-node GPU time and still ships a model whose newest knowledge is many hours old. Keeping up requires incremental training, where each model resumes from its previous state and consumes only the newest data, together with an equally continuous deployment path to inference so that fresh parameters reach serving every few hours.
Existing tools do not always address these requirements together, and the gaps stack on top of each other:
Legacy TensorFlow stacks. For historical reasons, many ranking training and inference stacks are still built on TensorFlow, which makes it hard to adopt what the PyTorch community is building: sharded embedding frameworks, compiler-based export, and the surrounding ecosystem.
Static embeddings, even in PyTorch. For teams that have moved to PyTorch, the mature option for large-scale embeddings is TorchRec with static tables, whose capacity and vocabulary are fixed at construction time. A fast-moving catalog cannot live with that.
Dynamic embeddings are hard even in training. GPU hash tables that admit and evict IDs on the fly still have to work with TorchRec's sharding, optimizer state, and distributed checkpointing.
Export to C++ inference engines. Online ranking runs under high QPS and tight latency budgets, so production inference engines are mostly written in C++, while models are trained in Python. Bridging the two means exporting the trained model into a compiled, Python-free artifact and giving the C++ engine a way to serve embedding tables it did not train.
One stack for models of very different sizes. All of the above has to work across a fleet where a model can be anything from a few GB to several TB. These sizes call for very different update strategies, ideally without different training code or serving binaries.
This blog describes how we close these gaps across the full incremental loop, from training on the newest data to landing fresh parameters in the inference engine. Together with NVIDIA, we built a production architecture on four pieces:
DynamicEmb (DE) from NVIDIA's recsys-examples, which provides GPU hash-table-backed dynamic embedding tables integrated with TorchRec for training, plus the inference-side lookup ops used at export time.
PyTorch 2 export (torch.export and AOTInductor), which produces a compiled, Python-free serving artifact (model.pt2) that deliberately keeps embedding storage outside the compiled graph.
NV-Embedding Cache (NVE), NVIDIA's inference embedding store, which serves the same exported graph in three modes: fully in HBM, in host memory behind a GPU cache, and in a hierarchy of GPU cache, host cache, and remote parameter server for tables that do not fit on a single node.
FlexKV, a multi-tier KV-cache manager from the LLM ecosystem (CPU DRAM, SSD, and remote storage). recsys-examples integrates it to cache the attention KV of the user-sequence module per user at inference, so each request only computes the new history and the candidates. [Note: validated in pre-production as of writing]
One architectural idea runs through all of this: the compiled model graph is decoupled from embedding storage by a stable custom-op boundary. The graph calls an opaque embedding lookup op identified by a layer ID. Where the embeddings live (HBM, host memory, or a remote store) and how fresh they are is decided by sidecar metadata and the storage tier, not by the compiled artifact. This boundary is what lets a 20 GB model ship as one hot-swapped artifact, while a TB-scale model refreshes its sparse rows and its dense weights on independent schedules. It is also what makes the design reusable by other teams facing the same mix of freshness, scale, and deployment constraints. The KV cache of the user-sequence module follows the same pattern: the graph calls thin, tensor-only kvcache_manager ops, and FlexKV together with a C++ runtime owned by the serving engine decides where each user's history KV lives, whether in HBM, host memory, or SSD.
The rest of the blog is organized as follows. Section 2 introduces the building blocks: DE in training, NVE at inference, the export path that connects them, and FlexKV. Section 3 describes the incremental training loop built on TorchRec and DE. Section 4 presents the end-to-end production architecture, a single export and deployment design that covers both small models and TB-scale models.
This section follows an embedding from training to serving. We start with how distributed DE tables work in training and why their communication pattern resembles expert parallelism in Mixture-of-Experts (MoE) LLMs (Section 2.1). We then look at the NV-Embedding Cache that serves embedding rows at inference (Section 2.2), and at the export path that connects the two inside a compiled .pt2 (Section 2.3). Finally, we introduce FlexKV, an inference-only component that caches the attention KV of the user-sequence module (Section 2.4).
A dynamic embedding table stores embeddings in a GPU hash table keyed by the raw ID, rather than in a dense [num_rows, D] tensor. When the table sees a new key, it inserts the key and initializes its row on the spot. When a bucket fills up, the entry with the lowest score is evicted, where the score can be LRU, LFU, or a custom policy. Admission policies can hold a key back until it has been seen N times, and an optional host or UVM tier, with an HBM cache in front of it, adds capacity beyond HBM.
DynamicEmb (DE) extends TorchRec rather than replacing it. Users still declare tables with EmbeddingBagConfig / EmbeddingConfig, DE-specific options (capacity, eviction, admission) travel with the table, and the input distribution, all-to-all, output distribution, DMP, and training pipeline all stay TorchRec's.
Only one fundamental difference needs extending: TorchRec assumes a table is a dense [num_embeddings, D] tensor. Row IDs fall in [0, N), memory is fixed at planning time, rows are assigned to ranks by contiguous ranges, and parameters are tensor shards. A DE table is a key-value store instead: keys are arbitrary 64-bit integers, capacity is an upper bound that the table grows into and evicts at, rather than a fixed allocation, the table itself changes during the forward pass (inserts and evictions), and its state is keys, values, and scores rather than one tensor. For every TorchRec component that relies on the dense assumption, DE subclasses it and replaces only that piece, as Table 1 shows.
What TorchRec assumes
What DE needs
How DE extends it
Memory is num_embeddings × D, allocated up front and fixed at planning time
Capacity is an upper bound, planned as a memory budget; the table grows on demand and evicts when full
Subclass the planner: plan DE tables first and subtract their HBM from the topology, then hand the remainder to TorchRec, so DE tables and static tables coexist in one model
IDs are assigned to ranks by contiguous row ranges
Arbitrary 64-bit keys, each routed to the rank that owns it by a fixed rule (such as round-robin or a hash of the key)
Subclass row-wise (RW) sharding and swap only the bucketize step in the input distribution for a DE kernel (which applies the rule per feature); the all-to-all and output distribution are reused as is
FBGEMM's table-batched embedding (TBE) gathers and updates dense row indices
Hash lookup, insert and evict on demand, and rows that carry optimizer state
Plug in through TorchRec's custom-lookup hook (≥ 1.2) with DE's own lookup and fused optimizer, covering both EmbeddingBagCollection (pooled) and EmbeddingCollection (sequence)
state_dict is a set of tensor shards
State is keys, values, and scores
Use DE's own parallel dump/load, and expose only a placeholder weight to TorchRec so its bookkeeping keeps working
The sections below look inside a single DE table; they describe one table shard on one GPU.
Logically, a DE table consists of four tensors, shown in Figure 2.

key: the IDs supplied by the user. The key space is the full 64-bit integer range and does not have to fall in [0, N). This is what sets it apart from a static table.
value: a dense 2D tensor in which each row concatenates the embedding (D) and the optimizer state (S), so a key's weights and state are inserted, updated, and evicted as one unit. S depends on the optimizer: 0 for SGD, 2D for Adam (one copy each of the first and second moments). Because the tensor is dense, once the row is located, reading it is an ordinary row gather.
index: a GPU-accelerated hash layer that maps a key to a row of value (the slot is the row number). A key hashes into one fixed-size bucket, so a lookup scans a single bucket.
score: records how important each key is, and eviction ranks keys by it. A score can be an access timestamp (LRU, the default), an access frequency (LFU), a combination of the two (optionally computed by a custom score function), or a value set directly by the user.
In a training step, each key passes through three phases: prefetch, forward, and backward, as Table 2 shows. Prefetch depends only on the input IDs and brings every key used in this step into the table; forward and backward then touch only rows that are already in place.
Phase
Step
What happens
prefetch
Deduplicate
Deduplicate the step's keys per table and count each key's occurrences (used by LFU), so each key is handled once afterwards
prefetch
Lookup
Probe the hash table. On a hit, get the row and update the key's score according to the score policy (LRU refreshes the timestamp, LFU accumulates the occurrence count; scores are read-only in eval), and mark the key "in use"
prefetch
Admission
Keys that missed go through the admission filter first; a rejected key does not enter the table or take a slot
prefetch
Insertion
An admitted key first gets its embedding initialized and its optimizer state set to the initial value, and is then inserted into the hash table; if its bucket is full, the key with the lowest score is evicted and its slot is reused
forward
Read and expand
Read embeddings by row number, fill non-admitted keys with a default value, then expand to every input position; pooled tables also apply sum or mean
backward
Aggregate and update
Aggregate the gradients of each key, update the row's embedding and optimizer state in place with a fused kernel, and finally clear the "in use" mark
Admission. A new key does not necessarily enter the table right away. The admission policy decides whether a key is eligible to take a slot. Frequency admission counts the occurrences of every waiting key and lets it in only once it reaches a threshold; probabilistic admission lets a key in with a fixed probability. As a result, long-tail IDs that show up only once or twice neither take up capacity nor trigger unnecessary evictions. A key that is not admitted gets a default embedding in the forward pass and is not updated.
Eviction when the table is full. Eviction happens only inside the bucket the key hashes to, so no global ordering is needed and the work parallelizes fully on the GPU. A larger bucket makes eviction more accurate at the cost of speed. A key marked "in use" is protected from eviction, so a row is never swapped out between its lookup and its update. In the multi-tier configurations described below (hybrid and caching), keys evicted from HBM fall to the host tier, and only an eviction from the last tier actually discards a key.
Keys, scores, and the indices always live in GPU memory (HBM) in the built-in storage; only the location of the values is configurable. Where the values go depends on the total size of all values of the table (num_embeddings × (D + S) × dtype) relative to the global HBM budget for values (global_hbm_for_values, split evenly across ranks by the planner), and, when they do not fit, on the caching option. This gives four layouts:
HBM-only: the total size is within the budget, and all values live in HBM.
Host-only: caching is off and the HBM budget is 0, so all values live in host memory.
Hybrid: caching is off and the HBM budget is greater than 0 but too small. The table is split into an HBM tier and a host tier whose capacities are divided in proportion to the budget; the two tiers do not overlap, so the total capacity is their sum. When the HBM tier is full, evicted keys spill into the host tier, and only the host tier actually discards them.
Caching: caching is on. The full data lives in a backing store (host memory by default, or an external parameter server through external_storage), and the HBM table serves only as a cache in front of it, holding a copy of the hot keys. Keys evicted from HBM are written back to the backing store.
In short, each storage tier has one hash map (the keys, scores, and indices on the GPU) and one value buffer. HBM-only and Host-only have one tier; Hybrid and Caching have two, one in HBM and one on the host.
A table starts at init_capacity, and its capacity limit follows from the num_embeddings declared for the table, after the planner shards it. When the load factor exceeds max_load_factor (0.5 by default), the table doubles automatically, up to that limit, after which eviction takes over. The whole process is implicit.
The value tensor accounts for most of a table's memory. Reallocating a buffer twice as large and copying the data over would keep both copies alive and double the peak memory. DynamicEmb avoids this by allocating values with VMM (CUDA virtual memory management): it reserves a large range of virtual addresses up front but maps physical GPU memory only for the current capacity, and expanding just maps more physical pages after the existing ones. The base address stays the same and nothing is copied, so the values never exist twice. (Values in host memory grow in place the same way, using mremap.) The much smaller index is rebuilt as a larger hash table, and the existing rows are then moved to their new slots in batches.
Between two full checkpoints, only a small fraction of the rows in a table change. DynamicEmb therefore provides an incremental (delta) pipeline: incremental_dump exports the changes and replay_increment writes them back.
Eviction records. An evicted key cannot silently disappear, because downstream needs to know which rows to delete (Section 3.1). With evicted_item_mode=RETAIN_KEY, the last tier records the keys it drops, and keys removed by an explicit erase are recorded as well. Each key is reported once.
The export rule. For score policies that carry a timestamp (such as the default LRU), every hit or insert refreshes a key's score to the current time, so "score at least a threshold" is equivalent to "changed since a point in time". incremental_dump uses this to pick out those keys in each table and exports them together with their embedding, optimizer state, and score (the upsert part), together with the evicted and erased keys recorded above (the deletion part) and a metadata record of each key's slot, the table capacity, the bucket size, and the sharding scheme. Other score policies are filtered by the absolute value of the score instead.
Why replay works. A key's position in the table is not random: it can only land in the bucket determined by its hash and the table capacity. So as long as the target table has the same capacity, bucket size, and sharding scheme as the source, replay_increment can write each key back into the slot it occupied in the source and reproduce exactly the same layout; before writing, it checks the metadata and fails before any write if they do not match. The same reasoning explains deletions: writing into a slot overwrites its previous occupant, which reproduces the source's eviction, so evicted keys need no separate replay. An erase, in contrast, leaves no new key to take over the slot, so it has to be replayed explicitly, and before the writes. The precondition is that the target table is built only from deltas of this one source.
The upsert and deletion parts of the export are exactly the input the sparse publisher in Section 4.2 needs.
Everything above describes one table shard on one GPU. The rest of this section shows how DE distributes these tables across GPUs.
At our scale, a single table does not fit on one GPU, so DE tables are row-wise (RW) sharded. Each key has exactly one owner rank, chosen by a fixed rule: round-robin or hashed round-robin. The last option spreads skewed IDs most evenly.
Readers familiar with LLM serving will recognize this layout. Large MoE deployments usually run attention in data parallel (DP) and experts in expert parallel (EP). A recommendation model with RW-sharded DE is split the same way, as Figure 3 shows. Throughout this section, the MoE baseline we compare against is an EP layer built on standard NCCL all-to-all. At the end of the section, we describe how we are optimizing DE communication beyond this baseline.

In both cases, the dense part is replicated and runs in data parallel: attention in the LLM, and the interaction layers, MLPs, and transformers in the recommendation model. In training, it is synchronized with a DDP-style all-reduce. The high-capacity sparse part is sharded by its "address", which is the expert in LLM case and the embedding row in the RecSys case, and inputs reach it through all-to-all communication. In both cases, load balance depends on the data, and router skew in MoE LLM plays the same role as hot-key skew in the recommendation model.
The forward passes also line up step by step. Both run permute → splits exchange → dispatch all-to-all → owner-local compute → combine all-to-all → unpermute, as Table 3 shows.
Step
Where
DE (sequence table, RW)
MoE EP
0
sender
Optional per-table dedup of the local microbatch
—
1
sender
Bucketize: fixed-rule owner, top-1, permute to rank-major
Gate top-k, permute by expert
2
all
Splits all-to-all, copy counts to CPU
Same
3
all
Dispatch all-to-all of keys (8 Bytes each)
Dispatch all-to-all of hidden states
4
owner
Regroup rank-major → feature-major
Regroup by local expert
5
owner
Dedup across senders → hash lookup / insert / evict → gather
Grouped GEMM
6
owner
Inverse regroup
Inverse regroup
7
all
Combine all-to-all of embeddings (D × dtype), reusing step-2 splits
Combine all-to-all, reusing splits
8
sender
Unpermute to original order
Unpermute + weighted top-k sum
9
sender
Expand step-0 dedup
—
Although the overall structure is the same, the differences between the two determine where the optimizations should go:
Routing depends only on raw input IDs. An MoE layer cannot dispatch until the previous layer has produced its activations. DE's owner rule needs nothing but the input batch, so the dispatch for batch i+1 can be issued while batch i is still computing, and TorchRec's sparse-dist training pipeline does exactly that. This is the biggest scheduling difference between the two. The blocking splits exchange in step 2 sits on the critical path of every MoE layer, which is one reason MoE stacks are moving beyond NCCL all-to-all to dedicated EP kernels. In DE, pipelining hides it instead.
One exchange instead of dozens. MoE pays for a dispatch and combine pair in every MoE layer. DE pays for one pair per table group, at the input of the model.
The return trip carries most of the bytes. MoE moves an H × dtype hidden state in both directions. DE dispatches 8-byte keys and returns D × dtype rows (512 B at D=128 in fp32), so the combine typically carries 10–100× more bytes than the dispatch. For pooled tables, each owner sums its partial bags before sending, and the combine becomes a reduce-scatter that folds the reduction into the collective.
Compute is memory-bound and mutable. MoE experts are compute-bound GEMMs over fixed weights. A DE lookup is memory-bound hash probing and random row gathering, and the table changes during the forward pass as keys are inserted and evicted.
Deduplication matters. RecSys embedding keys repeat heavily within a microbatch and also across ranks. DE therefore deduplicates twice. On the sender, this cuts both all-to-alls by the local duplication factor. On the owner, deduplication across all senders means a hot key is read from HBM once, no matter how many ranks asked for it. In contrast, MoE only does dedup at node level e.g. in DeepEp High Throughput mode.
There is no gate, no capacity factor, and no token dropping. Every key has exactly one owner and is always delivered, so the combine needs no weighted top-k reduction.
DE's current row-wise path runs over one flat process group with stock NCCL, exactly like the EP baseline above. On a job with 2 nodes of 8 GPUs, about 8 of each rank's 15 peers sit across the inter-node link, which usually becomes the bottleneck for the embedding-heavy combine. We are working on two complementary optimizations for this traffic. The first changes the sharding topology so that most traffic never leaves the node. The second applies ideas from high-throughput EP kernels to the traffic that still has to cross nodes.
Keeping lookups within a node with node-replicated row-wise sharding. The first optimization is a custom node-replicated row-wise topology. This is different from TorchRec’s standard table-row-wise (TWRW) sharding, which places each table on one host and shards its rows within that host. In EP, each expert lives on exactly one rank in the whole cluster, so tokens must cross nodes to reach it. With this topology, each node holds a full set of embedding tables, and each table's rows are split across that node's local GPUs. A rank's keys only ever travel to owners in its own node, so the dispatch and combine all-to-alls stay on NVLink. The per-node copies are kept in sync by a cross-node gradient all-reduce during training. That all-reduce is the main cross-node traffic this topology still pays, in exchange for keeping every lookup on NVLink. The other cost is capacity: the cluster stores one copy of the sparse state per node instead of one copy overall. This topology therefore fits whenever a node's aggregate HBM, or HBM plus host memory, can hold the full tables. Only when the sparse state outgrows a node does DE have to shard rows across nodes and fall back to the cross-node pattern in Table 3.
Applying DeepEP's high-throughput design to cross-node traffic. For the cross-node case, the MoE LLM community has moved well beyond NCCL all-to-all. DeepEP provides two kinds of kernels. Its high-throughput (HT) kernels target training and prefill, where every rank moves large batches. Its low-latency (LL) kernels target decode, where batches are small and latency dominates. LL kernels use pure RDMA with fixed-size receive buffers, avoid any CPU synchronization, and overlap communication through hooks that use no SMs. Newer NCCL releases are moving in the same direction, adding device-initiated communication primitives that EP libraries can build on.
DE training traffic clearly falls in the high-throughput regime: each step moves hundreds of thousands to millions of keys per rank. We are using six ideas from the HT design to guide the DE communication kernel we are building:
Rail-aligned, two-hop routing. DeepEP HT does not send a token directly to a remote GPU. It sends the token over RDMA to the GPU with the same local index on the destination node, and that GPU forwards it to the final GPU over NVLink. Each GPU then talks RDMA to only one peer per remote node, inter-node traffic stays on its own network rail, and NVLink's much higher bandwidth absorbs the fan-out. A DE kernel can route keys, and in particular the much larger returning rows, the same way.
Deduplicate per node, not only per rank. DeepEP sends a token across the network once per destination node, even when its top-k experts include several GPUs on that node. DE has an even stronger version of this opportunity, because recommendation keys repeat heavily. Today DE dedups keys within the sender's microbatch and again at the owner. A node-aware kernel can dedup at node granularity in both directions. On dispatch, a key requested by several GPUs of one node crosses the network once. On combine, the owner returns each unique row once per requesting node, and the receiving node fans it out over NVLink. Because the combine carries 10–100× more bytes than the dispatch, deduplicating the return trip is where most of the savings are.
Reduce before crossing the network in the backward pass. In DeepEP's combine, partial expert outputs are reduced on the way back. DE's backward pass has the mirror-image need: the gradients of all occurrences of a key must be summed before they update the owner's row. Summing gradients per key within each node before the RDMA hop shrinks the cross-node gradient all-to-all by the same duplication factor as point 2.
Size each direction separately. The two directions of DE traffic are very different: 8-byte keys go out, and D × dtype rows come back, in the forward pass, while gradient rows go out in the backward pass. DeepEP configures channels and buffers for asymmetric NVLink and RDMA bandwidth, and a DE kernel should also tune its buffers and channel counts per direction rather than reuse a symmetric all-to-all.
Bound the SMs that communication uses. DeepEP HT runs its kernels on a configurable number of SMs, on a separate communication stream with explicit events, so that compute keeps the rest of the GPU. This matches DE's training pipeline, where the input dispatch for batch i+1 already overlaps the compute of batch i. A DE kernel that fits within a small SM budget makes this overlap more predictable.
Fuse layout computation into routing, and keep the host off the critical path. DeepEP computes per-rank and per-node token counts in one GPU layout kernel before dispatch. DE's bucketize kernel already counts keys per destination, so routing, node-level dedup, and count computation can become one fused kernel. Like DE today, DeepEP HT still waits on the host for the received counts to size its output buffers. DE can keep hiding that wait through pipelining, or remove it by receiving into an upper-bound buffer, which is the approach LL kernels take.
Beyond these six, we are also evaluating low-precision transport, which DeepEP uses for FP8 dispatch, for the embedding-heavy combine and the gradient all-to-all, though its accuracy impact on embeddings needs careful validation. The remaining CPU-GPU synchronizations in today's DE forward pass (the sender dedup count, the splits copy, and the owner-side missing-key count) are also on our list to move to the device.
NV-Embedding Cache (NVE) is the inference-side store behind every embedding lookup in our exported models. A single NVE layer holds one embedding table with a fixed row size of dim × dtype_size bytes, typically 64 B to 1 KB. NVE supports four storage modes, GPUEmbedding, LinearUVM, HostEmbedding and Hierarchical, and all of them are reached through the same lookup op. In this section, we focus on the Hierarchical mode that carries our largest model. Specifically, we will go through the GPU embedding cache that is also shared by other modes, including the GPU memory layout design, and the cache management policies. Then the hierarchical multi-tier cache architecture for embeddings that does not fit in the GPU cache.
Mode
Where the full table lives
Caches
What happens on a cache miss
GPULayer (NoCache)
HBM, as a dense linear table
none (direct gather)
NA (no cache)
LinearUVM
host memory (cudaMallocManaged, preferred location CPU)
set-associative cache on the GPU
the same kernel reads the row over PCIe/NVLink through UVM
HostLayer
Host memory
none
NA (no cache)
Hierarchical
remote parameter server
set-associative cache on the GPU, then secondary cache in host memory
the GPU cache miss is forwarded to the host tier, then the remote tier
GPU memory layout
At the core of NVE is a software-managed, set-associative cache in HBM. NVE allocates and owns one device pool per cache and divides its byte budget into sets of a small, fixed number of ways W (8 in current releases). The pool is carved into separate arrays, one for row data and one for each kind of per-set metadata.
The mapping from a key to its slot is plain arithmetic rather than a hash function: the set is key mod num_sets, the tag is key / num_sets, and the key can be rebuilt as tag × num_sets + set. A row's address is therefore base + (set × W + way) × row_bytes, so a key's location is fully determined by its set's W tags.
By default, modifications run on the GPU and all persistent metadata lives in the device pool, with a host-side mirror of the tags. NVE can also run modifications on the CPU, in which case the counters and set clocks live in host memory. Either way, the read path touches only the tags and the data.
A lookup never writes cache metadata. NVE has several lookup kernels and picks one per call by batch size. The kernel choice and the switch-over point are layer configuration, so they can be tuned at load time without re-exporting.
Direct lookup, for typical batches. Each warp handles a group of 32 keys, one key per lane. A lane computes its key's set, compares the key's tag against the set's W tags, and takes the first matching way. The warp then copies each hit row into the output together: lanes take turns broadcasting a row address with warp shuffles, and all lanes copy that row with vectorized, coalesced loads. Each warp builds its group's 32 hit bits in a register and writes them to the hit mask in a single store, so the bitmap needs no atomics. Keys whose bit is already set on entry are skipped, which lets a chain of tiers share one bitmap. A miss leaves its bit at 0. In LinearUVM mode, the same kernel reads the missing row from the host table over PCIe/NVLink through UVM.
Sort-then-gather, for very large batches. A find pass resolves every key to a pair of addresses, a source and a destination. The source is the cache slot on a hit or the host-table row on a miss. The find pass also emits a sort key that separates hits from misses and orders the misses by key. After a radix sort, a gather pass copies the rows in that order, so reads from host memory arrive in address order and coalesce better.
Pipelined gather. An optional mode uses the cache's miss counter to split the gather into stages. The miss counter is the only atomic on the read path, and it is enabled only when a mode needs it.
Pooled and dequantizing lookups use variants of these kernels that fold the reduction or the dequantization into the gather, so the output holds one row per bag rather than one per key.
All modifications follow the same pattern: build a modify list, then commit it. An insert, which promotes rows into the cache, builds its list in three GPU steps:
Deduplicate and score. A sort followed by a run-length encoding turns the candidate batch into unique keys, each with a priority equal to its frequency in the batch. The list is capped at a configurable maximum modify size.
Group by set. NVE computes each key's set, radix-sorts the keys by set, and uses a run-length encoding plus a prefix sum to get each set's range of candidate keys.
Choose replacements per set. A replacement kernel assigns W threads to each touched set. It first ages the set's counters by the decay factor for every insert round since the set's clock was last stamped, then stamps the clock. Candidates that are already resident add their priority to their way's counter. For new candidates, the threads sort the best W by priority and the ways by counter in registers, and pair the highest-priority candidates with the lowest-counter ways. A candidate takes a way only if its priority is at least that way's counter. Each accepted pair becomes a modify-list entry, and the way's counter is set to the new key's priority.
The commit is the same for every operation. NVE sets the tags of all listed slots to the sentinel, waits for in-flight lookups on every registered stream to drain, copies the rows into place, and then writes the new tags. A concurrent lookup sees either the old row or a miss, never a partially written row. Updates (overwrite if resident) and accumulates (add in place) build their list from resident keys only and skip the replacement step. Erases only invalidate the tags. Only one modification can be in flight per GPU table.
Admission and eviction on the GPU use a decayed LFU with an admission filter. An insert first builds a histogram of the batch on the GPU with a sort and a run-length encoding, and each unique key's priority is its frequency in the batch. Within each set, counters decay by e.g. 0.95 for every insert round since the set was last touched, and the decay is applied lazily. A resident key adds its priority to its counter. A new key replaces the way with the lowest counter only if its priority is at least that counter, so a one-off key cannot evict a steadily hot one.
Insertion is gated by hit rate, probabilistic, and asynchronous. After each lookup, an auto-insert handler decides whether to promote the batch's rows. Below the target hit rate (for example, 0.75 for the GPU tier), it inserts with probability 1 − h to warm up the cache. Above the target, it inserts with probability (1 − h)³, so a warm cache is barely churned. Candidates accumulate until a minimum batch size is reached (e.g. 64K keys for the GPU) and are then inserted on a background thread pool. The lookup never waits for a promotion.
Updates use invalidate-then-commit. New values from training arrive through update (overwrite if resident), accumulate (add in place), insert, or erase. To modify the GPU cache, NVE first sets the affected tags to the sentinel, waits for in-flight lookups on every registered stream to drain, writes the rows, and then restores the tags. Readers therefore never see a partially written row. Only one modification can be in flight per GPU table.
The host tier is a simple hash map. The host cache is an open-addressing, Swiss-table-style hash map that stores keys, optional LRU/LFU metadata, and 32-byte-aligned value blobs as separate arrays. Probing runs on a CPU thread pool with software prefetching. By default, the host cache evicts randomly down to 90% occupancy when it fills up, on the assumption that the GPU cache already holds the hot keys.
Hierarchical mode chains the tiers into GPU set-associative cache → host hash map (optional) → remote parameter server, as shown in Figure 4.

A lookup makes one pass down the tiers with a shared hit mask. It passes the full key array and one hit mask to each tier in turn, and each tier resolves only the keys whose bit is still clear, with no compaction step in between. Rows resolved on the host are copied back into the device output in a single scatter, so one call always returns a complete batch. Keys that miss every tier fall back to a configured default row.
The hierarchy is mostly inclusive, with no demotion. A row served by the remote store is promoted into both the host cache and the GPU cache through the auto-insert path described above. A row evicted from the GPU is simply dropped rather than written down to the host, because the lower tiers already hold it or can fetch it again. Further, Intermediate tables, e.g. the host cache, can have their own criteria for introducing keys to the table. Leveraging this property, in the production environment, we can predict hot keys based on traffic heuristics, and prefetch the hot rows from the remote store to the host cache. As a result, subsequent cache misses from GPU cache can fetch keys directly from the host cache, saving the trip to the remote store.
The remote tier is the source of truth. The Redis plugin stores raw 8-byte keys and raw row bytes and supports two formats. Hash mode shards keys into Redis hashes, reads them with HMGET in batches of 16K, and keeps a companion metadata hash for LRU/LFU. String mode uses flat MSET/MGET with an optional namespace prefix. Our deployment uses String mode because flat keys can be routed through a proxy (Section 4.2). For a local SSD tier, a RocksDB plugin offers the same table interface.
Finally, a note on freshness. The caches have no TTL or versioning. When the sparse publisher upserts rows into Redis, cold rows become fresh on their next miss. Hot rows that are already resident in the GPU or host cache keep their old value until they are evicted, unless the publisher also calls update() or erase() for them. Section 4.2 refers to this as proactive invalidation of updated hot keys.
With DE on the training side and NVE on the serving side, the export path is what connects them. It turns a TorchRec checkpoint containing DE tables into a compiled, Python-free model.pt2 whose embedding lookups call NVE. We walk through it in three steps.
The export job groups the tables by embedding dimension, separately for pooled and sequence (aka. non-pooled) tables, and turns each group into one InferenceEmbeddingCollection (IEC). In one of our production models, 87 tables collapse into 14 IECs. Training-time sharding is not visible from this point on.
Each IEC is a pair of two independently configured parts [1]. An indexer turns a feature's (table, ID) pair into the key that NVE looks up, and an NVE layer stores the rows under those keys. Both are chosen per collection (InferenceEmbeddingCollectionConfig), so different groups in the same model can use different combinations. DE/IEC provides four indexers:
Fused identity (FusedIdentityIndexer), for tables whose IDs are already row indices. Each table gets a contiguous section of the fused table, preceded by one reserved "not-found" row. An in-range ID maps to its section's base plus the ID, and an out-of-range ID maps to the not-found row.
Linear hash map (LinearHashMapIndexer), for dynamic tables with arbitrary 64-bit IDs. A hash table maps each (table, ID) pair to a key in one dense key space. The first keys are the per-table not-found rows, and every ID loaded afterwards gets the next free key, so the fused table is packed in load order, with no per-table reservation. An ID that the hash table has never seen maps to its table's not-found row.
Bit concatenation (BitConcatIndexer), for tables stored remotely. The key is (table_id << feature_id_bits) | id. In our production settings, we use the same 16-bit table prefix and 48-bit ID across training and inference, so DE's keys and NVE's keys are the same 64-bit values. There is no key-to-row map at all, and this indexer is only allowed with Hierarchical NVE. The prefixed key can be built in either of two places, and both work: feature serving can build it and supply it to the graph as is, or the graph can build it from (table, ID) pairs with this indexer.
Identity (IdentityIndexer), for a collection with a single table whose IDs are already the keys.
The linear hash map's state is a full hash table, and LinearHashMapIndexer can keep it in one of two places, selected by indexer_state_sidecar. With True (the default), the state stays out of the graph: the indexer is identified in the graph only by a marker tensor, like an NVE layer, and the hash table is written next to the .pt2 as a sidecar and registered under that marker at load time (Step 3), so an update can publish a new snapshot while inference keeps running. With False, the hash table is baked into the .pt2 as buffers, and the forward pass probes them directly. Fused identity follows the same flag for its few per-table integers, and bit concatenation has no state.
The NVE layer can be any of NVE's modes, GPUEmbedding, LinearUVM, or Hierarchical , or the CPU-only HostEmbedding (Section 2.2). Indexers and layers combine freely, with one restriction: bit concatenation requires Hierarchical. In production, we use two combinations:
Small models (Section 4.1): fused identity with GPUEmbedding or LinearUVM. This is the per-table offset layout, in which each table owns a contiguous section of one fused table behind its own not-found row. The whole fused table ships inside the artifact, and the indexer's only state is a base offset and a size per table.

Large models (Section 4.2): bit concatenation with Hierarchical. The key depends only on the table and the ID, never on the order in which rows were loaded, so the mapping is stable: the keys already in the remote store stay valid across every export and every incremental update, and the indexer has no state at all. Because the export groups tables by embedding dimension before it builds the IECs, the bit-concatenated tables are naturally fused per dimension as well, with one Hierarchical layer per dimension group. They can optionally be fused further into a single table by padding the shorter embeddings to one uniform dimension. Section 4.2 discusses these tradeoffs.
Loading the rows works the same way for every combination. The IEC streams the source through the indexer in batches, asks it for each row's key, and writes the row under that key. For small models, the source is the checkpoint reassembled into dense per-table tensors, and the rows go into the fused NVE table. For large models, the source is DE's dumped (key, value, score) files, read batch by batch, so a table is never materialized as a single tensor. The rows are inserted straight into the remote parameter server, and the NVE layer, with its empty GPU and host caches, is created only after the load.
Step 2: Trace the forward pass
At inference, the forward pass of an IEC is a short sequence of ops that torch.export can trace:

expand_table_ids is a grid-stride binary search over the feature offsets, and the hash-map indexer runs a bucketed hash probe against the indexer state registered under its marker. Both are DE kernels. With the fused-identity and hash-map indexers, an unseen or out-of-range ID lands exactly on its table's reserved not-found row, so it gets a well-defined default instead of reading out of bounds. With bit concatenation, an unseen key misses every NVE tier and falls back to NVE's configured default row (Section 2.2). In every layout, the final nve_ops call is the only point where storage is involved. NVE supports sum, mean, weighted sum, and weighted mean pooling, and sequence features use the non-pooled nve_ops::embedding_lookup.
torch.export traces the model with FakeTensors, so every custom op needs a shape-only (fake or meta) implementation that never touches real storage.
For the DE routing ops, table_lookup and get_table_range register Python fakes through torch.library.register_fake. The fake for table_lookup returns (n,) scores, (n,) found flags, and (n,) slot indices. expand_table_ids registers a C++ Meta kernel (empty_like(keys, int64)) instead. Note that the op library must be loaded before the fake modules are imported; otherwise the registration only emits a warning.
For the NVE lookup ops, the fakes are pure shape functions that return (num_keys, dim) for sequence lookups and (num_bags, dim) for pooled lookups, with the output dtype taken from a baked integer tag. Early versions resolved the live layer inside the fake, which meant the layer had to exist in the exporting process. Newer versions are fully standalone. These fakes are written in Python because stable-ABI C++ Meta kernels cannot resolve SymInts.
For dynamic shapes, batch size is a single shared symbolic Dim, and the key count of each feature gets its own Dim. One artifact therefore serves any batch size or sequence length up to the declared maximums.
The NVE layer object, with its HBM cache, host map, and Redis client, never enters the graph, and there is no TorchBind object either. The graph carries only an identity for each layer.
This identity is a per-layer marker tensor, a one-element constant that is passed as the first argument of every NVE op. Its device pointer is the registry key. At load time, a C++ LayerDirectory reads metadata.json and builds each layer in its configured mode: a GPUEmbedding layer gets a device memory block, a LinearUVM layer gets a managed memory block loaded from weights/*.nve, and a Hierarchical layer gets GPU and host caches on top of a Redis plugin, with no weights loaded. The loader then allocates a fresh marker for each layer, points the AOTI package's marker constant at it through user-managed constants, and registers the layer under the marker's pointer. Because each loaded instance gets its own markers, several copies of the same model can be served in one process, and the binding can be re-pointed after a dense-weight hot-swap.
The marker must stay a runtime-updatable constant, so the .pt2 has to be compiled with runtime constant folding enabled. If it is not, AOTI inlines the marker, and the loader rejects the package at load time. Indexers with sidecar state follow the same pattern. At load time, DE's indexer directory (EmbeddingCollectionIndexerDirectory) reads the sidecar manifest, loads each hash-map snapshot, and registers it under the indexer's marker, so the graph again carries only an identity.
The export produces the following files and sidecars:

For small models, GPUEmbedding and LinearUVM share the fused-identity layout, so one .pt2 serves both, and switching between them is a metadata.json decision made at deployment time. For large models, the graph has the same structure, the same per-dimension fusion, and the same lookup op, and the only difference is the indexer: the prefixed key (table_id << feature_id_bits) | id either arrives from feature serving or is computed in the graph by bit concatenation, with no key-to-row map in either case. weights/*.nve is absent, because the rows live in the remote store. Section 4 builds the two deployment paths on these two configurations.
With this DE-to-NVE path in place, the whole model is torch.export compatible. These dynamic embedding lookups require custom ops with fake implementations and no Python state. Everything else, including feature preprocessing, the feature-interaction modules, the user-sequence module, and the prediction towers, is ordinary PyTorch code that torch.export captures as one graph and AOTInductor compiles as a whole. Those modules therefore get Inductor's optimizations directly: fused elementwise and reduction kernels, generated Triton kernels, autotuned matrix multiplies, and fewer kernel launches and memory round trips. The custom ops act as opaque boundaries that Inductor schedules around, so no model-specific serving code is needed to make the dense part fast.
We learned a few lessons while making this work in production:
Get the calling convention right. The routing op's offsets are feature-level (T + 1 entries), while pooling uses bag-level offsets (T·B + 1 entries). Mixing them up produced row indices past the end of storage, revealing an indexing issue that required correction to ensure consistent results across storage modes.
Expect some untraceable code. A few library calls, such as converting a pybind enum to an int inside forward, had to be patched before Dynamo could trace them.
Leave memory headroom. The training-time tables must be freed before the fused NVE tables are allocated, or the export runs out of HBM.
Mind the dtypes. Keys are int64, and embeddings are fp32 or fp16.
The HSTU-based ranking models from Section 1 include a user-sequence module, an HSTU transformer that processes sequences of relevant interaction features to support content recommendations. At inference, the expensive state of this module is its attention KV cache over the user history, which holds 2 × layers × heads × head_dim values per token for tens of thousands of tokens per user. The history changes slowly between requests, while the candidates change with every request, so recomputing the history KV each time wastes most of the module's FLOPs. LLM serving solves the same problem with prefix caching. We do the same with the recsys_kvcache_manager, which manages the HBM tier itself and uses FlexKV, a multi-tier KV-cache manager from the LLM ecosystem, for the tiers below it. Unlike DE and NVE, this component exists only at inference.
The manager splits the work between a device cache that it owns and a pluggable host storage backend, as shown in Figure 8.

The GPU tier decides which users stay in HBM and when their KV moves down. FlexKV decides how that KV is stored, indexed, and evicted below the GPU. The two meet at a single shared paged table in HBM.
The GPU tier is one preallocated tensor that holds all layers, viewed as one table per layer:
KV table: [num_layers, num_pages, 2 (K/V), page_size, num_heads, head_dim]
page_size is a configuration value (the examples use 32 tokens, or 128 on Blackwell). The table itself has no metadata. All bookkeeping lives in host memory inside the C++ manager:
a queue of free pages,
per user, the list of page IDs that hold the user's history, the cached range as a start position and a length, and the offloaded length, meaning how much of the history is already stored in a lower tier,
a user-level LRU list, and a per-user offload lock count for pages that a lower tier is still copying.
A user's cached range normally starts at token zero. It starts later when the manager has released the user's leading pages because their KV is already safe in a lower tier.
For each request, allocate gives every user enough pages for their whole history, reusing resident pages and taking free pages for the rest. It also builds the per-request metadata that the kernels consume: each user's page IDs, the fill level of each user's last page, and, for every newly appended token, which user and position it belongs to. This metadata is staged in a pinned host buffer and copied to the GPU on a side stream. HSTU attention reads the table directly through FBGEMM's paged attention kernel (hstu_varlen_fwd), and a paged append kernel (paged_kvcache_ops.append_kvcache) writes the new history K/V into place.
When there are not enough free pages, the manager evicts in two passes over the LRU list, oldest user first:
Release already-offloaded pages. For each user, it frees the leading pages whose KV is already stored in a lower tier. Users who lose all their pages leave the cache. This pass costs nothing to recover, because an onboard can bring those pages back.
Evict whole users. If that is still not enough, it evicts entire users in LRU order.
Both passes skip the users in the current batch and any user with an offload in flight. Eviction only drops pages and never writes back, because offloading happens ahead of time (see below). If a user's GPU range no longer starts at token zero and the lower tier does not cover the gap, the manager evicts the user and the history is recomputed instead of serving a sequence with a hole.
Offloading is the other half of the policy. A user's unsaved tail becomes an offload candidate once it reaches a configurable offload chunk, which is a multiple of the page size. With the native host backend, the manager also offloads the tails of other LRU users until a configurable budget of cheaply reclaimable pages (free or already offloaded) is reached, so that later evictions mostly take the cheap first pass. With FlexKV, the users of each batch are offloaded after the request, and FlexKV skips the part of the prefix that it already stores. Pages stay locked until the offload is reaped on a later request. A failed transfer is handled by a configurable policy: fail-open keeps serving and recomputes what was lost, while fail-close raises an error.
FlexKV manages the tiers below the GPU: CPU DRAM, which is the required hub tier, local SSD, and remote storage such as Mooncake Store, 3FS or NIXL file backends, or peer nodes over RDMAconfigurable remote storage backends, enabling cached model representations to move between storage tiers as needed for inference. FlexKV does not allocate HBM itself. It runs as a separate server process. The serving engine shares its paged GPU KV pool with FlexKV once through CUDA IPC handles, and FlexKV copies whole blocks between those pages and its own tiers. A block is one page of tokens_per_block tokens across all layers, K and V, all heads, and head_dim.
FlexKV accepts the engine's GPU layout, whether layer-first, block-first, or one tensor per layer. It stores its CPU and SSD copies block-first, so each block is one contiguous byte range across all layers that moves as one large DMA or file read. The CPU tier is pinned host memory. The SSD tier is a set of preallocated files striped round-robin across devices and accessed with io_uring.
To find cached data, FlexKV identifies each block by a chained hash over the namespace and every token up to the end of that block, so a single hash identifies a whole prefix. Each tier keeps a radix tree over these hashes, and a lookup is a longest-prefix match.
FlexKV's policies follow from this design:
Writes go through the tiers in order. A put copies data from GPU to CPU, at which point the request is complete, and then from CPU to SSD or remote storage in the background. A block only becomes visible in a tier's index after its write to that tier finishes.
Eviction is per tier and removes radix-tree leaves first, because a block is useless without its prefix. A node can be evicted only when it is a leaf, its write has finished, and no transfer holds it. LRU is the default policy, and LFU, SLRU, FIFO, and others are available. By default, eviction runs when a tier needs space, and it can also be configured to start earlier at a utilization threshold.
SSD hits are promoted. On their way to the GPU, SSD hits are promoted into DRAM, or they are read from SSD directly into GPU memory with GPUDirect Storage.
The manager registers its KV table with FlexKV as a layer-first layout with tokens_per_block = page_size, so a FlexKV block and a GPU page have the same shape. A transfer names its GPU destination or source with a slot mapping, the list of token slots page_id × page_size + offset derived from the user's page IDs. FlexKV then moves data directly between its CPU and SSD blocks and the recsys GPU pages, with no staging copy.
An important design choice is that cache entries are associated with individual sequence contexts rather than shared content prefixes. In Snap’s content recommendation system, the diversity of interaction sequences limits opportunities for cross-sequence prefix reuse. The integration uses a sequence-specific namespace and position indices to identify reusable cached representations. FlexKV's prefix match then answers a single question: how many full pages of this user's history are already cached? This relies on the history being append-only. Exact reuse also requires causal history attention, a prefix-stable attention scale, and unchanged prefix inputs and parameters; model or history-feature changes require cache invalidation or a new cache namespace. New engagements extend the prefix and reuse everything before them, but an edited or reordered history would silently serve stale KV.
Putting these together, each request goes through six steps:
Look up. The manager first checks its GPU bookkeeping by user ID. If the GPU already holds the user's history from token zero, it skips FlexKV for that user. Otherwise it calls FlexKV's get_match, which returns the length of the cached prefix and a task ID for the transfer. The two results are merged into one cached length per user.
Allocate GPU pages for each user's full history, evicting as described above.
Onboard. If FlexKV holds more of the history than the GPU, or the GPU has released the user's leading pages, the manager launches the matched transfer from CPU or SSD into the GPU pages. The transfer overlaps with token stripping, embedding lookup, and feature preprocessing, and the model waits for it just before the first HSTU layer needs the KV. If the transfer fails, the pages are revoked and the history is recomputed under fail-open.
Compute HSTU only on the new history tokens and the candidates, appending the new history K/V into the GPU pages.
Offload. The manager launches an asynchronous put of each user's history, rounded down to whole pages, under the user's namespace. FlexKV writes only the pages it does not already hold. The trailing partial page is not offloaded, but it stays in the GPU table until the user is evicted.
Reap. On later requests, completed offloads are collected, which updates each user's offloaded length and releases the page locks.
In production serving, the whole request flow above runs inside an AOTI-compiled .pt2 loaded by a C++ server, with no Python on the hot path. This is the same pattern we use for NVE in Section 2.3: the graph contains thin, tensor-only custom ops, and all state lives in a C++ runtime owned by the server. The design has three layers.
Custom ops in the graph. The exported HSTU model calls one custom op for each step of the request flow: lookup, allocate, onboard launch and wait, offload launch and reap, plus a few for initialization, eviction, and shutdown, all registered under the kvcache_manager_ops namespace. Each op has a shape-only fake registration for torch.export, like the DE and NVE ops in Section 2.3. Because these ops act mostly through side effects and return little data, a compiler could reorder or drop them. To prevent this, they pass a small ordering tensor from one call to the next, which gives each op an explicit data dependency in the compiled graph.
A stateful C++ runtime behind the ops. The ops themselves hold no state. Each one finds the active runtime through a thread-local context (KVCacheRuntimeContext), which holds one runtime per inference instance, and forwards the call. The runtime (ExportKVCacheRuntime, behind the IKVCacheRuntime interface) combines the GPU paged-cache manager from above (GPUKVCacheManagerImpl) with a FlexKV client. It merges the GPU and FlexKV lookup results itself, and it skips the FlexKV round trip entirely when the GPU already holds the user's history from token zero.
A Python-free FlexKV client. The runtime talks to the FlexKV server process over ZMQ IPC through FlexKVCppClient, using a compact binary protocol instead of the pickled messages of FlexKV's Python client. A separate registration step (FlexKVGPURegistrator) hands the GPU KV table to the server once, through CUDA IPC. The client keeps FlexKV's split between matching and transferring: a match (get_match) only reports how much of a user's prefix is cached and reserves a transfer, and the copy starts only when the runtime launches it (launch_tasks) with the slot mappings of the newly allocated pages. This split is what makes the overlap possible. The model launches the onboard, continues with embedding lookup and preprocessing while the copy runs, and waits only right before the first HSTU layer needs the KV. Offloads are launched the same way and collected without blocking on later requests.
The C++ server binary ties everything together. It loads the operator libraries for the KV-cache ops, the paged-KV and HSTU CUDA kernels, the DE inference ops, and FBGEMM. It reads a shared YAML runtime config that specifies the model shape, page geometry, CPU and SSD cache sizes, timeouts, and the fail-open or fail-close policy, connects to a FlexKV server started with the same config, and loads the .pt2 with AOTI's package loader. The same binary also hosts NVE's loader for the model's embedding tables, so a single serving process runs both caches: NVE for embedding rows and FlexKV-backed paging for sequence KV. Note that the C++ client currently depends on a customized FlexKV branch that adds this protocol.
In our benchmarks on an RTX PRO 6000 with the KuaiRand-1K dataset, a GPU KV-cache hit achieved measured end-to-end inference speedups of 1.7–4.5× for a 3-layer HSTU and 2.1–5.9× for an 8-layer HSTU at batch sizes 2 to 8, compared with recomputing the full history. For CPU hits on H100, our breakdown shows an onboard wait of 17–37 ms for histories of 1K to 4K tokens. Transfer time dominates, which is why the onboard is overlapped with the rest of the request. These results reflect the specified benchmark configurations and should not be interpreted as performance improvements across all production workloads.
The two cache systems nve-cache and kv-cache serve different purposes, and a ranking model with a user-sequence module needs both. NVE caches independent embedding rows which are part of model parameters, at most about a few KB each, and updated in place by incremental training and export loop (Section 3 and 4). The KV cache keeps per-request computation of the user sequence module from being repeated. It holds each user's history KV, many megabytes per user, generated during inference. The two differ in granularity, in who writes them, and in how they are reused, so neither can stand in for the other. Yet both compete for the same HBM on the same GPU.
LLM serving now faces a similar problem inside a single model. Hybrid-attention models keep several kinds of cache side by side, each with its own entry size and layout. Kimi K3 interleaves linear-attention (KDA) layers, which keep a fixed-size recurrent state per sequence, with MLA layers, which keep a per-token paged KV cache [4, 5]. DeepSeek V4 mixes compressed-attention KV, indexer entries, and sliding-window state, so its serving stacks manage several pools with different page sizes [6, 7]. Our recsys server currently carves HBM into statically sized pools when the server starts, which fixes the split no matter how the workload shifts. vLLM’s hybrid cache manager uses a shared pool, and SGLang offers an opt-in unified pool [5, 8, 9], so that capacity can follow the traffic instead of a startup flag. The same idea would let a recsys server shift HBM between the embedding cache and the KV cache as the request mix changes.
Capacity and eviction. We size DE capacity from the observed number of active keys, the key churn, and the expected growth, with enough headroom to limit eviction. We persist eviction records and propagate them downstream so that serving can remove the corresponding embeddings.
Sharding topology. We choose the sharding scheme to match the network topology. Row-wise sharding across nodes requires cross-node all-to-all communication, which is expensive on bandwidth-constrained clusters. Our node-replicated row-wise topology instead gives each node a full set of embedding tables and splits each table's rows across that node's GPUs, so the lookup all-to-alls stay on fast intra-node links (Section 2.1). A cross-node gradient all-reduce keeps the per-node copies in sync. We split rows only for the tables that are large enough to need it, and we fall back to cross-node row-wise sharding only when the sparse state no longer fits in one node.
Checkpoint state. Training checkpoints save the DE keys, embedding values, and optimizer state of each shard. Separate incremental dumps export the embedding updates for downstream publishing.
Each increment starts from the previous committed state, trains on the next data window, evaluates the model, and publishes the update.
Warm start. We carry forward the model weights, the DE state, and the optimizer state. Newly admitted IDs receive fresh embeddings and fresh optimizer state, and we tune the learning rate for the shorter incremental training windows.
Window size. We aggregate training data every hour to start training, and refresh changed embedding weights every 10 minutes. For very large models, a long-running trainer keeps the model and optimizer state in memory across windows, which avoids repeated startup and checkpoint loading.
Because each window builds on the previous committed state, recovery must preserve that sequence without skipping windows or duplicating committed updates.
In production, we see worker and infrastructure outages, incomplete or invalid input windows, checkpoint and publishing errors, and jobs that keep running but stop making progress. Recovery happens at window boundaries: the trainer restores the last committed checkpoint and resumes with the next uncommitted window. We also wait for complete input data before training, handle invalid windows explicitly, and use progress-based health checks to detect stalled jobs.
Incremental training produces a fresh checkpoint every few hours. In the rest of this section, we call that interval X (Section 3.2). The question that actually shapes the production design is: how many bytes must move to turn that checkpoint into a serving update, and can the serving fleet absorb them?
For a model under about 20 GB, the answer is "all of them, and yes": the whole artifact can be re-exported and hot-swapped like any other build. For a TB-scale model, the answer is "absolutely not". Re-shipping terabytes of model params to every replica every few hours would saturate both the artifact pipeline and the fleet's load path, for an update in which most of the bytes, namely the untouched cold embedding rows, did not change.
The fleet therefore runs two deployment paths. They share one incremental trainer, one export stack, and one serving binary, and they differ only in which NVE storage mode backs the embedding lookups and in what moves on each refresh. Figure 9 shows the full loop.

Both paths start from the same trainer and end in the same serving binary. Feature serving builds the 64-bit IDs once, and both training and online requests use them. The small-model path (Section 4.1) moves the whole artifact through export, validation, and the artifact store every X hours, and swaps it atomically. The large-model path (Section 4.2) splits the refresh into two lanes. Every X hours, the sparse publisher writes only the changed rows, and deletes evicted ones, in the remote parameter server, which serving reads through on cache misses. Every Y hours, a dense export ships a new model.pt2 (whose size depends on the dense parameter count) through the same validation and artifact store as the small-model path. We describe the small-model path first and then show how the large-model path builds on it.
Most of the models take the simple path. After each incremental training round, we re-export the whole model and atomically swap the serving artifact.
What the export produces. The exported artifact has a deliberate split:

torch.export traces the model, and AOTInductor compiles it into model.pt2, which holds the dense backbone's weights and the generated GPU kernels but none of the embedding bytes. The embedding tables ship as sidecar .nve files described by metadata.json.
Per-dim table fusion with fused identity Indexer. As described in Section 2.3, the export groups tables by embedding dimension into fused NVE tables; in one of our production models, 87 trained tables become 14. Small models use the fused-identity indexer, so each fused table is one flat storage tensor in which every member table owns a contiguous section behind its own reserved "not-found" row, and an ID maps to its section's base plus the ID. Fusion pays off twice. First, there is one fused kernel launch per dimension group instead of one per table. Second, mapping IDs to global row indices takes a single vectorized add before the lookup. The compiled graph then calls one opaque custom op:
nve_ops::embedding_lookup_with_pooling(marker, keys, pooling_offsets, weights?, pooling_type, ...) -> Tensor
Note what this op does not carry: no embedding weights, no cache mode, and no storage location, only a one-element marker tensor that identifies the layer. This is the decoupling boundary from Section 1, expressed in one line of schema.
NVE GPUEmbedding and LinearUVM modes. At serving time, the runtime reads metadata.json, constructs one NVE layer per fused table, loads the .nve bytes into it, and registers it under its marker. The same model.pt2 runs unmodified in either of two modes:
In GPUEmbedding mode, the fused table lives entirely in HBM, and lookups are direct GPU gathers. This is the right choice when the tables fit alongside the dense model and the latency budget is tight.
In LinearUVM mode, the fused table lives in host memory behind NVE's GPU set-associative cache. Hits are served from HBM, and misses are read across the PCIe/UVM boundary. This covers models whose tables do not merit full HBM residency, at the cost of host-memory bandwidth on the cold tail.
Because the cache mode is a field in metadata.json rather than a property of the compiled graph, switching a model between modes, or serving it in both modes on different replica pools, requires no re-export.
The refresh loop. Every X hours, after the incremental training round lands its checkpoint, three steps run:
The export job loads the checkpoint, a TorchRec distributed checkpoint reassembled into full tensors on a single device, rebuilds the fused layout, and emits a complete new artifact: model.pt2, metadata.json, weights/*.nve, and the indexer sidecar.
The artifact is validated with a signature check and golden-batch parity against the training model, and then published to the artifact store.
Inference replicas load the new version and atomically cut traffic over, while the previous version is kept for instant rollback.
The export itself is cheap. It is memcpy-class work from end to end (checkpoint download, table fusion, and sidecar writing) with no numerical transformation of the trained values, so the cadence of the loop is bounded by training and validation, not by export. For a model under 20 GB, the whole cycle is easy to repeat every few hours across hundreds of models. Its main virtue is atomicity: dense weights and embeddings always come from the same checkpoint, so there is no version skew to reason about.
The main ranking models break the full-refresh path for simple physical reasons. A TB-scale artifact cannot be rebuilt, re-shipped, and reloaded across the fleet every few hours, and it does not fit in a serving node's HBM and host memory in the first place. However, the artifact split above already contains the solution. Because the .pt2 never held the embedding bytes, the sparse and dense halves of the model can be exported and refreshed on independent paths and independent schedules, as Table 5 shows.
Property
Sparse (embedding tables)
Dense (backbone + graph)
Trained with
TorchRec + DynamicEmb
TorchRec (same job)
Exported as
rows upserted to a remote parameter server
model.pt2 (AOTInductor)
Update cadence
incremental, every X hours
full, every Y hours (X ≪ Y)
Update size
only rows touched since last increment
depends on the dense parameter count
Serving side
NVE Hierarchical mode
AOTI model loader
Serving with NVE Hierarchical mode. For large models, the fused embedding tables are backed by a three-tier, read-through hierarchy:

The compiled graph has the same structure as in the small-model case, with the same per-dimension fusion and the same embedding_lookup_with_pooling(marker, ...) op. The one difference is the indexer from Section 2.3, bit concatenation: the keys are prefixed 64-bit values, either built by feature serving and passed through as is, or built in the graph from (table, ID) pairs. Either way, the graph carries no key-to-row map, and new IDs never require a graph change. metadata.json also differs: the layer entry says Hierarchical, specifies the sizes of the GPU and host cache windows, and carries the remote-store connection config.
A lookup hits the GPU cache first, and misses fall through to the host cache and then to the remote store. Because recommendation feature ID access is heavily skewed, modest cache windows absorb the vast majority of lookups, while the long cold tail lives off-node. As a result, total embedding capacity is bounded by the remote store rather than by any single serving node, and this is the tier that carries trillion-parameter sparse state. One serving binary loads all three modes, and the choice between them is a metadata field, never a rebuild.
Why bit concatenation for remote tables. The linear hash map from Section 2.3 would also work with Hierarchical, and it would pack the rows densely, but it is the wrong fit at this scale for three reasons:
Its keys are not stable. The hash map assigns keys in load order, so every export would renumber the rows, and every key already in the remote store would have to be rewritten. Bit-concatenated keys are a pure function of the table and the ID, so the store is written once, new keys from incremental updates do not alter existing keys.
Its state is as large as the vocabulary. A hash map over billions of IDs must ship with the model, as a sidecar or baked into the .pt2, and every sparse increment would have to update it on every replica, in step with the rows, before a new ID could be found. Bit concatenation has no state, so a brand-new ID is servable as soon as its row reaches the store, and an evicted ID disappears with a single delete.
Dense keys buy little here. Packing matters for a flat table in HBM or host memory, where an unused row costs memory. The Hierarchical tiers are a set-associative GPU cache, a host hash map, and a remote key-value store, and all of them handle sparse 64-bit keys natively.
The price of bit concatenation is a fixed bit budget: 16 bits of table prefix allow 65,536 tables per key space, and IDs must fit in the remaining 48 bits. Both limits are sufficient for what our models need.
Per-dimension fusion or one padded table. By default, each dimension group gets its own Hierarchical layer, which keeps every row at its exact size in every tier, on the wire, and in the store. The cost is that each group has its own GPU and host cache windows, sized statically at load time, and its own lookup per request. Padding all embeddings to the largest dimension fuses everything into one layer: one cache budget that the hottest rows of every table share, one key space, and one lookup. The padding bytes, however, are paid in every tier, in every cache transfer, and on every remote read, roughly a fraction 1 − D/D_max of each padded row. Per-dimension fusion is the better default when the dimensions differ widely. Padding becomes attractive when they are close and the per-group cache windows would otherwise be hard to balance.
The wire contract. The remote store uses a deliberately minimal format, because three independently deployed components (the sparse publisher, the compiled graph, and the serving read client) must agree on it for the lifetime of the system. The contract has three parts:
Key: 8 bytes, with a 2-byte table_id prefix. Per-dim fusion means that many logical tables share one physical key space. The key packs a 2-byte table identifier into the high bytes of the 8-byte ID, and the remaining 6 bytes carry the ID within that table. Whether feature serving builds this key or the graph builds it by bit concatenation, it is the same 64-bit value end to end: DE trains on it, the sparse publisher writes it, and NVE looks it up. Nothing in the trainer, the export, or the compiled graph translates between key spaces. This keeps the benefit of fusion (one lookup stream and one kernel path per dimension group) while keeping the key space partitioned by table, which is exactly what incremental publishing needs. A dynamic table that grows by a few million IDs never renumbers or collides with the rows of other tables, because each table's increment upserts into its own prefix range, with no global re-layout and no cross-table coordination.
Value: the raw embedding row bytes. There is no header and no framing, only dim × dtype_size bytes per row. Flat, untagged keys and raw values make the store easy to route through a proxy, and they let us swap or re-point the read client (a new endpoint, a new topology, or resized caches) by editing metadata.json alone.
Op schema and marker binding. The .pt2's only reference to storage is the stable-ABI custom-op call that carries the layer's marker, and the runtime binds that marker to the concrete hierarchical layer at load time.
As long as these three invariants hold, every other component can be replaced independently without touching the compiled artifact.
The sparse increment, every X hours. This is where dynamic embeddings and incremental training come together. During each incremental training round, DE's hash tables admit the new IDs that appeared in the window and update the rows that the window's data actually touched. The sparse publisher then ships only that delta: touched and newly admitted rows are written to the remote store as idempotent upserts under the prefixed-key contract. IDs that DE evicted during the window, which are persisted as eviction records (Section 3.1), are deleted from the store and erased from the serving caches in the same increment. Within an ordered increment, repeating the same upsert or delete is idempotent; the publisher must also preserve checkpoint order and apply each key’s final state. Serving replicas need no restart and no reload: the next cache miss, or a proactive invalidation of updated hot keys, pulls the fresh row through the hierarchy. For a TB-scale sparse state in which each increment touches a small fraction of rows, this turns an impossible full redeployment into a modest, bounded stream of writes. It is also how a brand-new item's embedding can become available to the recommendation system within hours of initial interactions, subject to the incremental training and publishing cycle.
The dense update, every Y hours. The dense backbone does not need, or want, the same cadence. Dense weights drift smoothly and have no vocabulary problem, so a full torch.export and AOTInductor rebuild ships on a slower cycle. Each rebuild produces a new model.pt2 containing the dense weights but no embedding bytes, together with a regenerated metadata.json, and it is hot-swapped exactly like a small-model artifact. It is cheap to build, cheap to ship, and easy to roll back.
Managing version skew. Splitting the paths means that the sparse rows and the dense weights in a serving replica come from different, usually nearby, training states. In our implementation, we manage this version skew based on the observation that embeddings and the backbone co-adapt slowly compared with X and Y. Two rules help maintain compatibility and support monitoring:
Layout changes force synchronization. Adding a table, changing a dimension, or regrouping the fusion changes the key layout and the baked routing buffers. In that case, sparse and dense must be republished together from one checkpoint and gated as one deployment. Routine increments never change the layout, and the 2-byte-prefix key space is what guarantees this.
Both paths pin their source. Each sparse increment and each .pt2 records the training run and checkpoint timestamp it came from, so version skew is observable and alertable.
Although the two paths look different operationally, they are one design. They use the same incremental trainer, the same DE and TorchRec stack, the same export code, the same custom-op contract, and the same serving binary. A model takes the simple path or the split path based on one number, the bytes a refresh has to move, and it can move from Section 4.1 to Section 4.2 as it grows without changing its training code or its model code. The move flips three things in the export and deployment configuration: the indexer from fused identity to bit concatenation, the NVE layer from an in-artifact GPUEmbedding or LinearUVM table to Hierarchical, and the sparse publisher from off to on. More than either endpoint, this graduation path is what lets the architecture hold up across a fleet of hundreds of models that span several orders of magnitude in size.
In this blog, we described how Snap and NVIDIA built a PyTorch stack that trains, exports, and serves recommendation models at trillion-parameter scale, with fresh parameters reaching production every few hours. DynamicEmb gives TorchRec dynamic embedding tables that admit and evict IDs during training, with a communication pattern closely mirrors MoE expert parallelism. torch.export and AOTInductor produce a Python-free artifact whose embedding lookups are opaque custom ops. NV-Embedding Cache serves those lookups from HBM, host memory, or a remote parameter server, and FlexKV caches the per-user attention KV of the user-sequence module across GPU, CPU, and SSD. Because storage stays behind a stable custom-op boundary, the same training code, export code, and serving binary cover both small models that are refreshed as whole artifacts and TB-scale models whose sparse and dense halves are refreshed independently.
By sharing these experiences, we hope to help other teams who are moving large recommendation models to PyTorch and need them to stay fresh in production.
[1] NVIDIA recsys-examples, including DynamicEmb and the recsys KV-cache manager. https://github.com/NVIDIA/recsys-examples
[2] FlexKV: a multi-tier KV-cache manager for LLM serving. https://github.com/taco-project/FlexKV
[3] NVIDIA NV-Embedding Cache. https://github.com/NVIDIA/nv-embedding-cache
[4] vLLM team. "Kimi K3 Is Here: Efficient Day-0 Support on vLLM." July 2026. https://vllm.ai/blog/2026-07-27-k3
[5] LMSYS Org. "SGLang and Miles Add Day-0 Support for Kimi K3." July 2026. https://www.lmsys.org/blog/2026-07-27-kimi-k3-day0-support/
[6] DeepSeek-AI. "DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence." 2026. https://arxiv.org/pdf/2606.19348
[7] vLLM team. "DeepSeek V4 in vLLM: Efficient Long-context Attention." April 2026. https://vllm.ai/blog/2026-04-24-deepseek-v4
[8] vLLM documentation. "Hybrid KV Cache Manager." https://docs.vllm.ai/en/stable/design/hybrid_kv_cache_manager/
[9] vLLM team. "vLLM x AgentX: Optimizing for Real-World Agentic Serving." September 2026. https://vllm.ai/blog/2026-09-08-vllm-agentx
Acknowledgement
This work reflects a 'one-team' collaboration between Snap and NVIDIA, from joint design and implementation to production deployment. We thank everyone across both teams for their technical contributions, close partnership, and shared commitment to advancing recommendation training and serving.