{"slug": "trillion-parameter-scale-recommendation-models-on-pytorch", "title": "Trillion Parameter Scale Recommendation Models on PyTorch", "summary": "Meta's PyTorch team detailed DynamicEmb (DE), an extension to TorchRec that stores recommendation-model embeddings in GPU hash tables keyed by arbitrary 64-bit integers instead of dense [num_embeddings, D] tensors, enabling trillion-parameter-scale recommendation models. DE subclasses TorchRec components that assume dense tables and replaces only those pieces, keeping TorchRec's input distribution, all-to-all, output distribution, DMP, and training pipeline intact. The design pairs training with the NV-Embedding Cache for inference and FlexKV, an inference-only component that caches the attention KV of the user-sequence module.", "body_md": "**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).\n\nA 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.\n\n**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.\n\nOnly 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.\n\nThe sections below look inside a single DE table; they describe one table shard on one GPU.\n\nLogically, a DE table consists of four tensors, shown in Figure 2.\n\nkey: 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.\nvalue: 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.\nindex: 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.\nscore: 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.\n\nIn 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.\n\n**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.\n\n**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.\n\nKeys, 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:\n\nHBM-only: the total size is within the budget, and all values live in HBM.\nHost-only: caching is off and the HBM budget is 0, so all values live in host memory.\nHybrid: 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.\nCaching: 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.\n\nIn 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.\n\nA 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.\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\nThe upsert and deletion parts of the export are exactly the input the sparse publisher in Section 4.2 needs.\n\n**Everything above describes one table shard on one GPU.** The rest of this section shows how DE distributes these tables across GPUs.\n\n**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.\n\n**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.\n\nIn 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.\n\n**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.\n\nAlthough the overall structure is the same, the differences between the two determine where the optimizations should go:\n\nRouting 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.\nOne 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.\nThe 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.\nCompute 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.\nDeduplication 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.\nThere 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.\n\nDE'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.\n\n**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.\n\n**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.\n\nDE 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:\n\nRail-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.\nDeduplicate 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.\nReduce 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.\nSize 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.\nBound 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.\nFuse 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.\n\nBeyond 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.\n\n**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.\n\n**GPU memory layout**\n\n**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.\n\nThe 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.\n\nBy 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.\n\n**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.\n\nDirect 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.\nSort-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.\nPipelined 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.\n\nPooled 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.\n\n**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:\n\nDeduplicate 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.\nGroup 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.\nChoose 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.\n\n**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.\n\nAdmission 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.\nInsertion 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.\nUpdates 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.\nThe 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.\n\nHierarchical mode chains the tiers into GPU set-associative cache → host hash map (optional) → remote parameter server, as shown in Figure 4.\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\n**Each IEC is a pair of two independently configured parts [**[1](https://eng.snap.com/pytorch#references)**].** 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:\n\nFused 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.\nLinear 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.\nBit 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.\nIdentity (IdentityIndexer), for a collection with a single table whose IDs are already the keys.\n\nThe 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.\n\nThe 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:\n\nSmall 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.\n\nLarge 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.\n\n**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.\n\n**Step 2: Trace the forward pass**\n\nAt inference, the forward pass of an IEC is a short sequence of ops that torch.export can trace:\n\nexpand_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.\n\ntorch.export traces the model with FakeTensors, so every custom op needs a shape-only (fake or meta) implementation that never touches real storage.\n\nFor 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.\nFor 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.\nFor 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.\n\nThe 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.\n\nThis  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.\n\nThe 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.\n\nThe export produces the following files and sidecars:\n\nFor 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.\n\nWith 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.\n\nWe learned a few lessons while making this work in production:\n\nGet 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.\nExpect 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.\nLeave memory headroom. The training-time tables must be freed before the fused NVE tables are allocated, or the export runs out of HBM.\nMind the dtypes. Keys are int64, and embeddings are fp32 or fp16.", "url": "https://wpnews.pro/news/trillion-parameter-scale-recommendation-models-on-pytorch", "canonical_source": "https://eng.snap.com/pytorch", "published_at": "2026-11-23 08:00:00+00:00", "updated_at": "2026-11-23 23:12:48.285829+00:00", "lang": "en", "topics": ["machine-learning", "ai-infrastructure", "ai-research"], "entities": ["PyTorch", "DynamicEmb", "TorchRec", "NV-Embedding Cache", "FlexKV", "Meta"], "also_reported_by": [], "takeaway": "DynamicEmb replaces TorchRec's dense [num_embeddings, D] tables with GPU hash tables keyed by arbitrary 64-bit integers, using prefetch, forward and backward phases plus frequency or probabilistic admission so long-tail IDs that appear once or twice don't consume capacity or trigger evictions.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/trillion-parameter-scale-recommendation-models-on-pytorch", "markdown": "https://wpnews.pro/news/trillion-parameter-scale-recommendation-models-on-pytorch.md", "text": "https://wpnews.pro/news/trillion-parameter-scale-recommendation-models-on-pytorch.txt", "jsonld": "https://wpnews.pro/news/trillion-parameter-scale-recommendation-models-on-pytorch.jsonld"}}