Repository navigation
[FEA] Support table row wise sharding in DynamicEmb - #493
Conversation
[High impact] The latest changes appear safe to merge, with both numbered previous findings addressed. SummaryAdds
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Table configs and constraints] --> B[Size DynamicEmb shards]
B --> C[Choose nodes for table-row-wise tables]
C --> D[Subtract per-rank memory costs]
D --> E[TorchRec plans remaining tables]
E --> F[Combine plans]
F --> G[Attach each rank's local options]
Reviews (34) · Last reviewed commit: "style(dynamicemb): drop an import this b..." · Reviewed by Greptile |
|
To date, we have carefully reviewed the coupling between
|
|
/build |
|
❌ Pipeline #69015387 -- failed
Result: 10/17 jobs passed |
df71ea0 to
27c01c7
Compare
|
/build |
2 similar comments
|
/build |
|
/build |
|
❌ Pipeline #73173064 -- failed
Result: 7/17 jobs passed |
|
/build |
|
/build |
|
❌ Pipeline #74304918 -- failed
Result: 0/3 jobs passed |
|
/build |
1 similar comment
|
/build |
|
❌ Pipeline #74319169 -- failed
Result: 0/3 jobs passed |
The table-row-wise sharding used to write the intra-node group straight onto the kernel, through a hasattr guard that also matched TorchRec's own kernels: a table sharded table-row-wise but not on a DynamicEmb kernel is grouped into this same sharding and falls back to TorchRec's, which owns its collectives and never reads the field. It got one anyway. The guard is now a type, and the write a method. The method is also the one place shard_ranks and the shard group meet -- the planner builds one and the sharding the other, and they must name the same ranks -- so the sizes are checked against each other there. They disagreeing means the two halves have forked, which is worth raising over, not deadlocking on. Verified on EOS (8xH100, job 6254040): planner 59 passed 1 skipped; table-row-wise all modes, 2 and 4 GPUs over 1 and 2 nodes, both dist types; pooled and sequence embedding rc=0; incremental dump 16 passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ts authority dump and load have taken a pg since before this branch, and since this branch moved shard identity onto the plan they had stopped reading it: a parameter accepted and silently ignored, which is worse than one that was never offered. It is now what the barrier falls back to. The group set_shard_pg named wins, pg is used when the sharding named none, and None is the world -- which is what upstream did for row-wise, where a table is on every rank and the caller's group is the right one. It can be no more than a fallback: a caller holds one group for a whole model while each kernel's tables may sit on a different node, and dump_load.py hands the same pg to every module. Shard identity deliberately does not follow. rank and world_size stay _shard_index and _num_shards, which -- unlike the barrier group -- are never unknown, and which five things must agree on: the file names, the num_shards and shard_ranks written into the meta, the check that reads them back, and the key-ownership modulus. Letting pg decide one of them splits it from the other four. That is a behaviour change from upstream in one case: upstream named files by dist.get_rank(group=pg), so a caller passing a sub-group got names numbered within it. DynamicEmbDump and DynamicEmbLoad default to dist.group.WORLD, where the two agree; only an explicit sub-group differs, and checkpoints round-trip either way. Verified on EOS (8xH100, job 6254040): planner 59 passed 1 skipped; table-row-wise all modes, 2 and 4 GPUs over 1 and 2 nodes, both dist types, dump/load across geometries; pooled and sequence embedding rc=0; incremental dump 16 passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three things it got wrong, found by walking every file:line it names. The section 2 map described a planner that no longer exists: a `_settle` that was never a real method name, a `sharding_type` "hardcoded ROW_WISE" that this branch exists to un-hardcode, and post-rename paths on pre-change line numbers, so it read as a tour of the current tree while describing the old one. It is now the current map, with anchors that resolve, and the history under it says it is history. Line numbers into our own files had drifted: eleven of them landed on a blank line, a closing paren, or a string fragment -- `_shard_world_size` pointed at `enforce_hbm`, `get_sharded_table_capacity` at an unrelated assignment. The claims were all true; only the numbers were wrong. Those describing the state before this branch now name the symbol and no line, because a number in a passage about code that has since moved will rot again. Those describing current code are corrected and keep their line. And 2.1 still said the plan record was always ROW_WISE over every rank. Citations into TorchRec were checked too, at c5e147ff, and all twelve in code comments plus the CUSTOMIZED_KERNEL five were already right. Also makes the two imports this branch added sort where isort puts them, and the two files black would reformat match black. Verified on EOS (8xH100, job 6255032): import smoke; planner 59 passed 1 skipped; table-row-wise all modes; incremental dump 16 passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
I reported the import order as fixed after correcting the two cases I had spotted by eye, without running isort. Having run it -- 5.12.0, the version .pre-commit-config.yaml pins -- sixteen changed files were wrong, two of them (embedding_admission, key_value_table) already wrong on main, the rest this branch's. They are sorted now. One comment was wrong with them. `planner/__init__.py` imported get_planner last, saying it "builds the three above, so they have to exist first"; get_planner imports `.planners` by path and nothing in the package imports back through `__init__`, so there is no such ordering, and isort hoisting it changes nothing. The import smoke test below is that claim checked rather than reasoned about. The compute kernel keeps one import of embedding_types rather than the two isort would otherwise leave: adding ShardingType to that list had pushed a stale commented-out fragment onto a member line, where isort reads it as a reason to split the statement. The fragment is gone. The four tests asserting that tables which do not fuse do not pool their budgets were one test written out four times, so they are parametrized over the field that separates them -- and the fourth, data type, now checks what the other three did. It had stopped at the fusion key and never called `place`, which is the half that matters. Alongside: the row-wise test was two tests under one name, and now says each separately; order-independence is asserted over pinned tables too, since `place` walks those in the order given; and the two calls that shared a placer make their own, because `place` keeps no state between them and sharing one implies it does. `BalancedNodePlacer` prices each node once per table instead of twice -- `added_by` walked every group on the node to answer, and the winner was re-priced after the ranking only to check it fits. Verified on EOS (8xH100, job 6255229): import smoke; planner 60 passed 1 skipped; table-row-wise all modes, 2 and 4 GPUs over 1 and 2 nodes; pooled and sequence embedding rc=0; incremental dump 16 passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`fusion_key` said that staying coarser than the runtime's grouping "errs safely", and that a plan can be refused that would have fit but none accepted that will not. The first half holds and the second does not. Merging tables the runtime keeps apart moves `min(sum total, sum budget)` up, so HBM is over-stated -- conservative -- but the host tier is `total - hbm` and `total` does not move, so it is under-stated by exactly as much. That direction accepts layouts the runtime cannot hold: the planner believes the rows stay in HBM, the runtime keeps the tables apart, and the rows that no longer fit a budget go to a host tier nobody costed for them. The same key is what `per_rank_storage` deducts with, so the Topology handed to TorchRec is short by the same amount -- the two agree, they are simply both wrong. `per_rank_storage` also still described its grouping as the sharding type paired with `get_grouped_key`, which is what it used before `fusion_key` existed. §7.2 of the design document carried both mistakes. `test_tables_that_do_not_fuse_do_not_pool_their_budgets` turns out to be that paragraph as a test, so it now says so: each of its four parameters guards one component of the key, and dropping that component makes a layout the host tier cannot hold stop being refused. The placement tests say what they check, now that reading them closely was what found the above. The two "row-wise tables" tests had no row-wise table in them -- they vary `committed`, which is where a row-wise table's cost arrives -- and one was two tests under one name. The pin tests are one suite, since a pin is one contract with four promises. The test that a crowded single rank rules out its node is gone: `committed` is built by adding the same cost to every rank, so within a node it cannot be uneven. `test_a_node_is_charged_on_every_one_of_its_ranks` stays, because every table after the first in one `place` call does see one node loaded and the other not. Verified on EOS (8xH100, job 6255881): import smoke; planner 58 passed 1 skipped; table-row-wise all modes, 2 and 4 GPUs over 1 and 2 nodes; pooled and sequence embedding rc=0; incremental dump 16 passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The cost-and-topology tests were carrying assertions that restate what a
neighbouring test already proves, and a few whose premise lived in the
reader's head rather than in the code.
Said once:
- a single-rank table's costs adding up, which no sharding type produces
and which grouping already covers
- the length of table_ranks, implied by the two tests that assert the
whole list
- the wording of the per-tier remedies and of the multi-tier message
Said in the open:
- the two placement forms shard_rank accepts are now asserted to be the
two forms, not two spellings of the same assertion
- a table-row-wise table's bill is checked against table_ranks itself
rather than against a slice that only lines up for node 1 of 2, and
against the exact per-shard bytes rather than "greater than zero"
- the machine's per-rank capacities are named HBM_PER_RANK and
DDR_PER_RANK, so the fixture and the assertions share one symbol
- the rank an overdraft is reported on is matched literally, dropping a
case-alternation whose lower half could never match
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
table_fanout is what a table's per-rank capacity and HBM budget are divided by, and what the bucketizer distributes keys over -- the two have to agree or a key goes to a rank that does not believe it owns it. Only its row-wise branch was ever exercised: the one test calling it passed ROW_WISE, which returns on the first line. So the table-row-wise answer, the sharding types it refuses, and the worlds that are not a whole number of nodes all went uncovered, and none of them fails loudly -- a wrong fan-out just sizes every table wrong. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The suite crossed every mode with both distribution rules and every
dump-sharding with every load-sharding, which ran 31 torchrun launches to
make 24 distinct claims.
Three of those dimensions do not interact:
- `plan` reads no key. check_plan asserts sharding types, shard counts,
which node the table landed on and the rows a rank got; the rule that
places keys decides none of them. Once per topology.
- `pooling` happens after the lookup -- the kernel's downgrade to SUM and
the EBC's mean callback -- so it does not depend on where a key was
sent, and a rule that sent one to the wrong rank fails `parity` first.
- row_wise to row_wise holds no table-row-wise table at all. It is the
path the pooled, sequence and incremental-dump suites already cover,
and both of its halves are reached by the two crossings that remain.
`parity` and `jagged` keep both rules: they read keys, and the two rules
bucket by different arithmetic.
The checkpoint combinations are written out rather than nested, since what
is left is no longer a full product.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ean something Two gaps, one cause: every row held `key % DEBUG_EMB_INITIALIZER_MOD` and nothing ever moved it. `check_load` could not fail. DEBUG makes a row a function of its key, so a key the loader dropped is created on miss holding exactly what the file held -- deleting the DynamicEmbLoad call outright left the test green. `check_dump` now takes one optimizer step before writing, which moves every row off that value, and `check_load` asserts the rows did not come back sitting on it. Both of its assertions are live for the first time: the §8.1 failure it names makes the two tables disagree only because they are no longer at their initial value. Nothing ran a backward at all, though the group is called fwd_bwd and the model is built with EXACT_SGD and a learning rate. §3.3 claims a table-row-wise table's gradient arrives divided by L in the intra-node reduce-scatter and by N in the cross-node all-to-all, whose product is the 1/W row-wise gets in one step. A new `grad` mode takes that step and asserts the two tables moved by the same amount; on two nodes of one rank both move by -0.05, which is lr/W. `grad` runs on both topologies and one distribution rule: the divisions follow the node size and the node count, not the rule that placed the key. Four ranks split two ways is the only place where both divisors exceed one. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
NVIDIA#495 added test_rowwise_adagrad_state_precision.py and did not register it, so its 42 cases -- packed fp32 accumulators, odd embedding dims, checkpoint conversion, configurable state precision -- have not run in CI since. It is the only unregistered entry point in test/; the other two files in test/unit_tests/optimizer/ are both listed. The defect it covers is silent: an fp16 accumulator rounds to zero on every store, the update degenerates to a constant step with no decay, and training quietly goes wrong. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Restores the check that `with_options` copies the sharding spec rather than sharing it. The field loop beside it cannot stand in: it compares with `==`, which answers the same for a copy and for the original object, so only identity plus a write can tell them apart. What the write would cost is narrow and quiet -- DMP rewrites placements in place on a meta device, and on rank 0 the plan still holds the planner's own record, because a broadcast hands the leader back its own object. A second `plan` call would then hand out placements the first DMP had already rewritten, on rank 0 and nowhere else. Adds the arrangement that tells `capacity`'s `min` from a `max`: a node whose ranks are not the same size. What the placer is told has been spent is the row-wise tables' cost, which is added to every rank of the world, so the only way one node's ranks differ is a machine whose GPUs differ -- which TorchRec takes through custom_topology_data. A table-row-wise table is split over every rank of its node, so the node holds it only if its tightest rank does; reading the roomiest would place a shard where it cannot fit and the plan would look feasible until the run. Verified by mutation: min -> max fails that test and no other. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…umped under
`_iter_batches_from_files` gained a required `dist_type` when its ownership
filter stopped being a hardcoded `keys % world_size == rank` and became
`owned_key_mask`. Its caller in `exportable_tables.py` passes positionally and
was not updated, so `DynamicEmbExportableTable.load_from_dynamicemb_file`
raised TypeError on the first call.
The rule comes from the checkpoint's own meta, which this function has already
read and which records it -- the same `meta_data.get("dist_type",
"roundrobin")` the dump/load path uses. The default is the rule every
checkpoint written before the meta carried one was dumped with, and the one
this loader assumed for all of them, so nothing that worked changes; a
checkpoint from a `hash_roundrobin` table now loads under its own rule rather
than the wrong one.
Found by mypy, not by a test: nothing under test/ exercises this path.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…hat move
The API document still described the branch at M2. It told the reader the
feature does not work -- "nothing consumes it, the sharding runtime still
dispatches only ROW_WISE" -- which stopped being true when M3 landed and
`create_embedding_bag_sharding` began returning TwRwPooledDynamicEmbedding-
Sharding. In its place is what a reader actually needs at that point: a
table-row-wise table costs world_size/local_world_size times the memory per
rank, and buys an all-to-all that stays inside the node.
Three smaller disagreements with the code, in the same document:
- step 1 wrote `ROW_WISE` for every table; it writes whichever sharding type
the constraint asks for
- the dist_type rules were introduced as row-wise's; both sharding types
bucketize by them
- steps 2-4 were said to run on rank 0. Step 2 runs on every rank, and
deliberately: it is where a table that does not fit is refused, and a
refusal on rank 0 alone leaves the others waiting on a broadcast that
never comes -- an error turned into a hang
The design document's §2 map pointed at `plan.py:506,537` and `:211,344`,
which by then were a `copy.copy` and a closing paren: editing a docstring
moves everything below it, and this is the second time these rotted. Every
line number into a file we own is gone, replaced by the symbol that was
already named beside it; line numbers into TorchRec stay, and now say
"torchrec" where the basename alone was ambiguous. §9's milestone table and
the paragraph under it still read as though M2 were the next thing to do.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The paragraph that replaced the stale "not usable yet" note said the all-to-all that gathers a table-row-wise table runs inside its node. It does not: `create_input_dist` builds the KJT all-to-all on `self._pg`, the global group, under both sharding types. What table-row-wise changes there is the bucket count (`local_size` rather than `world_size`) and a staggered shuffle before the exchange -- not the scope. A rank that is not on the node holding the table still sends that table's keys across the fabric. The saving is on the output side, which is what §3's table has always said: a row-wise table's reduce-scatter spans every rank, so the reduction itself crosses nodes, while a table-row-wise one reduces inside its node and sends one pooled result per node -- O(B·D·world_size) of cross-node output traffic becomes O(B·D). Stated plainly because the wrong reading points a user at the feature for the wrong reason: someone whose input all-to-all is the bottleneck would pay N times the rows per rank, and the eviction rate that comes with them, for nothing. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1cae3e1 to
561eecf
Compare
`table_row_wise_embedding_table_names` was added as get_planner's fifth parameter, ahead of `pipeline_type`. `apply_dmp` passes `pipeline_type` positionally in that slot, so HSTU and SID-GR training handed the string to the new parameter and left `pipeline_type` at its `"none"` default. Nothing raised. `"none"` maps to an empty list of allowed compute kernels, which does not constrain the planner at all, so both pipelines lost their restrictions: `native` its `["fused", "fused_uvm"]` and `prefetch` its `["fused_uvm_caching"]`. The prefetch case is the sharper one -- `enable_prefetch_pipeline` is computed from the caller's argument and still reaches `fused_params["prefetch_pipeline"]`, so the pipeline is requested while the planner is free to pick a kernel that cannot serve it. The misrouted string was no better off: it reached a `config.name in ...` test written for a set, which on a string is a substring match, so a DynamicEmb table named like any slice of `"native"` or `"prefetch"` would silently have been sharded TABLE_ROW_WISE. Put `pipeline_type` back in fifth place and move the new parameter after it, so the positional contract matches main's -- `get_planner` is exported from `dynamicemb.planner`, and fixing only the in-tree caller would leave external ones misbinding. Pass it by keyword at the call site as well, so the next parameter added here cannot repeat this. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Loading a checkpoint has passed `shard_index` and `num_shards` to the backing store since table-row-wise tables could be dumped and loaded, but the abstract `Storage.load` was never widened to take them. The two in-tree stores were, so nothing in the suite failed -- and nothing could have, because no test puts `external_storage` and a checkpoint together: six tests parameterize a store, a dozen dump and load, and the two sets do not intersect. A store supplied through `external_storage` is not wrapped. It is `self._storage` itself under both the CACHING_PS and HOST_PS layouts, so the call lands on the user's method and a correct implementation of the published contract raises TypeError on an unexpected keyword. The arguments are passed unconditionally, so this happens while loading an unchanged row-wise checkpoint too. `PyDictStorage`, which the API documentation names as the implementation to copy, had the same signature and the same fate. Widen the contract and the demo. This is a breaking change for anyone who has written a store against the old signature; the alternative -- probing the store and omitting what it cannot take -- buys little, since a table-row-wise table loaded through a store that ignores its geometry would be filtered by the global rank and world size instead and silently keep the wrong keys, which has to be an error anyway. The geometry is the table's own, not the process's: the world for a row-wise table, one node for a table-row-wise one. Left None it falls back to the global rank and world size, which is the row-wise answer, so a store that only serves row-wise tables may ignore both arguments as the demo does. Say that where an implementer reads it, and say the same on `Counter.load`, which has taken these two arguments all along and documented only `dist_type`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`compute_kernel_to_embedding_location` has been imported and unused since before this branch. autoflake could not remove it: the `from ... import (` line carried a trailing comment, and autoflake leaves an import statement alone rather than risk moving someone's note. Adding `ShardingType` to that block took the comment with it, so `pre-commit run -a` now reaches the dead name and takes it out. Nothing else `pre-commit run -a` reports is this branch's. On upstream main it wants to change 27 files; here it wants 20, and those 20 are main's own, minus the seven this branch already ran black and isort over. The codespell failure is identical on both. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ls TRW future The design note described the planner it was written against rather than the one that exists. - `per_rank_storage` "needed no change" was true of M2 and false since: it is keyed by `TableKey` and buckets by `fusion_key`. The same row listed two of `plan.py`'s helpers where it now holds seven. - `local_hbm_for_values` was said to come from the world size. It is divided by the table's own fanout -- one node's worth under table-row-wise -- which is what §4.2 is about. The same sentence was wrong in `_prepare_dynemb_table_options`'s docstring, which is where a reader is most likely to trust it. - The step 2-4 sketch passed `table_names` to `module_without_tables`, which takes a set of `TableKey`. - Ties in the placer break on the key, not the name. - A pin that does not fit is refused naming `collection.name`. - `test_tables_that_do_not_fuse_do_not_pool_their_budgets` was said to have a case per component of `fusion_key`. It has five of six: the sharding type is fixed at table-row-wise by `TableToPlace.fusion_key`, so what guards that component is `per_rank_storage`, which reads each table's own. Saying "a case per attribute" invites the next reader to assume a guard that is not there. The note also now says that `get_planner` cannot express a qualified key and refuses a name `eb_configs` does not declare. `README.md` was two releases behind in both directions: its usage notes said a dynamic embedding table "is always row-wise sharding", and its future plans still listed `table-row-wise` among the shard types to add. It shipped in NVIDIA#493. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ls TRW future The design note described the planner it was written against rather than the one that exists. - `per_rank_storage` "needed no change" was true of M2 and false since: it is keyed by `TableKey` and buckets by `fusion_key`. The same row listed two of `plan.py`'s helpers where it now holds seven. - `local_hbm_for_values` was said to come from the world size. It is divided by the table's own fanout -- one node's worth under table-row-wise -- which is what §4.2 is about. The same sentence was wrong in `_prepare_dynemb_table_options`'s docstring, which is where a reader is most likely to trust it. - The step 2-4 sketch passed `table_names` to `module_without_tables`, which takes a set of `TableKey`. - Ties in the placer break on the key, not the name. - A pin that does not fit is refused naming `collection.name`. - `test_tables_that_do_not_fuse_do_not_pool_their_budgets` was said to have a case per component of `fusion_key`. It has five of six: the sharding type is fixed at table-row-wise by `TableToPlace.fusion_key`, so what guards that component is `per_rank_storage`, which reads each table's own. Saying "a case per attribute" invites the next reader to assume a guard that is not there. The note also now says that `get_planner` cannot express a qualified key and refuses a name `eb_configs` does not declare. `README.md` was two releases behind in both directions: its usage notes said a dynamic embedding table "is always row-wise sharding", and its future plans still listed `table-row-wise` among the shard types to add. It shipped in NVIDIA#493. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…its collection and its name (#504) * fix(dynamicemb): identify a table by its collection and its name `fusion_key` decides which tables are costed as one TBE, and it carried nothing that said which collection a table came out of. TorchRec shards each shardable module on its own -- one `ShardedEmbedding*Collection` apiece, each with its own `EmbeddingSharding`s -- so tables from two collections never reach the same `group_tables` call, and the runtimes they build cannot lend each other HBM. The planner pooled their budgets anyway. That is the unsafe half of a coarse key. Merging tables the runtime keeps apart moves `min(sum total, sum budget)` up, which over-states HBM and so only refuses layouts that would have fit -- but the host tier is `total - hbm` and `total` does not move, so it is under-stated by exactly as much, and that direction approves a model the machine will not hold. Two collections with per-rank sizes of 4 GiB and 16 GiB and budgets of 20 GB and 2 GB were costed as one 22 GB budget over 20 GiB of rows: no host memory at all, where the truth is 6 GiB of HBM and 14 GiB of host. The information existed and was being thrown away. `_table_configs` walks the model to find the tables, so it is the one place that knows which module each came out of, and it flattened that into a bare list of configs. It now pairs each config with the path to its collection. The path rather than `id()`: every rank runs that walk alone and has to reach the same grouping, and object addresses do not agree across processes. Having that path, the planner stops keying tables by name. A table is now a `TableKey(collection, name)`, which is how TorchRec identifies one -- it names a sharding option `path + "." + name` and keys a `ShardingPlan` by `plan[path][name]` -- and every per-table record follows: `_dyn_emb_plan`, `_dyn_emb_options`, `_table_poolings`, `optimizer_types`, `per_rank_storage`, `TableToPlace`, and the set `module_without_tables` prunes by. Two collections declaring one name are two entries throughout: charged separately, placed separately, grouped apart, filed under their own paths, and handed their own options. That is what lets them hold their own options, which is what the planner could not do before and why it refused the model instead. `DynamicEmbTableOptions` is both the caller's policy and the runtime's per-table config, and `_prepare_dynemb_table_options` writes the geometry into it -- `dim` from `embedding_dim`, `max_capacity` from `num_embeddings` through the bucket layout, `embedding_dtype` from `data_type` -- so one object cannot describe two tables, and the function is not idempotent besides: it reads back `bucket_capacity`, `max_capacity` and `init_capacity` after writing them. Reached by name, both occurrences got the same object. TorchRec does not have the problem because `ParameterConstraints` is policy-only and each occurrence's geometry comes from its own `tensor=param`. So `constraints` gains a second key form, and `get_constraint_key` is how a caller writes one: constraints = { get_constraint_key(shared_a, model): ..., # sparse.ebc_a.shared get_constraint_key(shared_b, model): ..., # sparse.ebc_b.shared } It takes the config object rather than a name, because by name there is nothing to tell the two apart -- and a collection returns the config objects it was built from, so identity matches what the caller is holding. `module` is the root the path is relative to, so passing a collection itself returns the bare name and a caller with one collection needs no special case. The answer is a function of the arguments alone, never of whether some unrelated collection happens to share a name; a key that moved for that reason would be a key written down elsewhere and now silently wrong. `resolve_constraints` is the other half. Each occurrence asks for its keys in turn -- qualified, then bare -- and takes the first `constraints` has. That order is the whole of the addressing rule: a bare name still reaches a table nothing more specific names, so a model whose table names are unique needs no change at all, and a qualified key overrides it for one collection. It refuses three things, all of them constraints that would otherwise be silently unused: a key no occurrence answers to; a qualified key on a table TorchRec plans, since its planner looks constraints up by name alone and would never find it; and one `DynamicEmbTableOptions` object reached by two occurrences, which is what a bare name does when two collections declare it, and whose message names `get_constraint_key`. That last check also closes an older hole. Two differently-named tables sharing one constraint object -- `{"a": c, "b": c}` -- hit the same non-idempotent write and were silently mis-sized; they are now refused for the same stated reason. Having two places that needed the path made it worth having one that finds it. The descent a sharder-claimed module ends -- the enumerator's own rule -- was written out three times: in `_table_configs`, in `_insert_dynamicemb_plan`, and in `optimizer_types`, which wants the sharder and threw the path away. The first two have to agree about the paths they produce and nothing made them, each building its own `f"{path}.{name}" if path else name`; a plan filed under a path `DistributedModelParallel` does not look for is not an error there, since it shards the modules its plan names and leaves the rest alone, so a drift would have surfaced as a collection that silently stayed unsharded. They now share `sharded_modules`, which yields each claimed module with its path and its sharder. `module_without_tables` keeps its own recursion: it rebuilds the tree from the bottom up rather than reading it. Keying its prune set by `TableKey` fixes a bug of its own. It pruned by name, so a name DynamicEmb planned in one collection was taken out of every collection -- leaving TorchRec a table it was told to plan and could no longer see. `per_rank_storage`'s docstring claimed coarseness was safe in both directions. `fusion_key`'s already said otherwise; this makes them agree. `get_planner` is unchanged and still keys by name: its `eb_configs` is a flat list with no module to take a path from, so it cannot express a qualified key. A model that needs one builds its constraints and the planner directly; a comment there says so. BREAKING CHANGE: `TableToPlace.name` is now `key`, a `TableKey`, and `NodePlacer.place` returns `Dict[TableKey, int]`. A custom `NodePlacer` must follow. `per_rank_storage`, `optimizer_types` and `module_without_tables` are likewise keyed by `TableKey` rather than by table name. `fusion_key` takes the owning collection as a trailing argument; new parameters go after it, since the existing ones are passed positionally. Two tables sharing one `DynamicEmbTableOptions` object is now an error rather than a silent mis-sizing. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test(dynamicemb): drop three tests that assert what a neighbour already does `test_a_name_that_is_unique_is_qualified_just_the_same` asserted `get_constraint_key(l, module) == "left.l"`, which the test above it already asserts as the second element of its list -- `l` is in that module precisely so a name nothing collides with is seen to be qualified too. `test_an_overridden_bare_key_is_not_reported_as_a_typo` built the same module and the same constraints as the precedence test and asserted only that nothing was raised, which the precedence test reaches first: were the overridden bare key reported as naming no table, it would raise there and that test would fail. `test_the_path_is_stable_across_calls` compared two walks over two instances of one class, where the paths come from `named_modules` and cannot differ. None could fail on its own. What the first two said is kept: both docstrings move onto the test that survives, since the reason a case is interesting outlives the duplicate assertion. The third's -- that the identity is the path rather than `id()` because every rank walks alone -- is already on `TableKey` and in §7.2, where it is a statement about the design rather than about this model. The helpers they left behind are folded together. `_dynamicemb_planner` spelled out the same row-wise DynamicEmb constraint that `_dynamicemb_constraints` builds, so it now calls it; and `_planned` -- step 1 run over a module, three lines open-coded in two places -- becomes one module-level helper. No behaviour is under test here that was not before: 61 tests in this file become 58. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test(dynamicemb): test what a caller can see, not how it is reached Six tests asserted the shape of an internal return value. `_table_configs` pairs each config with a path -- which every test downstream of it relies on, and which `get_constraint_key` already states from the side a caller sees, since the bare name a root collection yields is the promise that one collection needs no special key. Four more restated what `sharded_modules` does: the paths it yields, the empty path at the root, the sharder it carries, that an unclaimed module is recursed into. All of that is the walk's implementation written twice, and it had to be rewritten once already when the walk started carrying a `TableKey`. What survives of that class is the one thing no caller can see: that the path `_table_configs` records a table's collection as is the path `_insert_dynamicemb_plan` files its ParameterSharding under. Two walks that disagreed would not raise -- `DistributedModelParallel` shards the modules its plan names and leaves the rest alone -- so a collection would silently stay unsharded. `TestResolveConstraints` now drives the planner instead of calling `resolve_constraints`. What a caller writes is a `constraints` dict and what they get back is a planned table or an error; which function inside reaches that answer is ours to move, and the tests should not have to move with it. The precedence case gains something in the trade: it asks which options object the table was *planned* with, by identity, where before it only asked which constraint was selected. Not moved up to `plan()` itself, which needs a process group: these stay in the unit tests, one level below the public entry, rather than becoming four more end-to-end runs where a mis-keyed constraint shows up as an OOM. 52 tests, from 58. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test(dynamicemb): drop the bare-key test, name the class for its claim `test_a_bare_name_still_reaches_its_table` asserted the compatibility every other test in the file is already written in: they all key their constraints by a bare name, so bare lookup breaking turns the file red without its help. The note it carried -- that a `constraints` dict written before any of this keeps working -- moves to the class, where it reads as the premise it is. `TestShardedModules` no longer calls `sharded_modules`; what is left of it is the invariant between two callers, so it is named for that: `TestCollectionPathsAgree`, matching `TestCollectionsDoNotPoolBudgets` rather than the classes named after the function under test. 51 tests, from 52. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test(dynamicemb): say at the call site what the helpers were hiding Each of these wrapped something shorter than the name that hid it, or named half of what it returned. `_sharders()` was `[EmbeddingBagCollectionSharder()]`, and its name -- plural, unqualified -- said less than the expression. Inlined. `_at_ebc(name)` was `TableKey("sparse.ebc", name)`, in tests whose whole subject is which path a table is filed under. Inlined, so the path is on the line that asserts about it. `_planned` returned a planner and said neither that nor which step had run. It is now `_plan_dynamicemb`, after the method it calls, and takes `sharders` so that "only the pooled collection's" is on the signature rather than buried in the body. `_sharding` returned the `(ParameterSharding, DynamicEmbTableOptions)` pair and named the first half; it is `_planned_table`, after the `_Planned` it builds. The class-local `_sharding` in `TestCollectionsDoNotPoolBudgets` does return a bare sharding and keeps a name of its own, `_row_wise_sharding`. `_ebc`, `_ec` and `_TwoCollections` took bare lists, so a call read `_TwoCollections(["shared"], ["shared"])` with nothing to say which side was which. They now take `table_names`, `left_names` and `right_names`, passed by keyword. Two things found while reading. `_key` had an `isinstance(name, TableKey)` passthrough that no caller reaches -- left from when these tests were keyed by name -- so it does one thing now. And its default collection was `"ebc"`, a module that does not exist in this file; it is `"sparse.ebc"`, where `_Model` actually holds its collection, so the string means one thing throughout. No test is added, removed or re-aimed. `test_planner_placement.py` keeps its own `_table(collection="ebc")`: that file builds `TableToPlace` directly and has no module tree, so there is no path for the value to agree with. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(dynamicemb): refuse a get_planner name no table answers to `get_constraint_key`'s docstring said its return value was also the key for `get_planner`'s `table_row_wise_embedding_table_names`. It is not: that set is compared against `config.name` (`get_planner.py`), a bare name, while a qualified key is `collection.name`. A caller following the docstring got neither an error nor table-row-wise sharding -- the `else` branch planned the table row-wise and nothing said so. That is the mistake `resolve_constraints` refuses for `constraints`, in those words, because a constraint that reaches no table reads as "plan this with the defaults" and is found in a profile rather than in an error. `get_planner` had no such check: it has no `raise` of its own at all, and a name matching nothing was dropped silently. So the docstring now says where the key does and does not work, and `get_planner` refuses a name that `eb_configs` does not declare. Three arguments, not one: `data_parallel_embedding_table_names` fails the same way -- a typo there plans the table model parallel -- and an extra key in `dynamicemb_options_dict` is likewise ignored, though a missing one already raises `KeyError` where it is indexed. The message names the qualified-key case, since that is the one the docstring sent people to. The check runs before `torch.cuda.get_device_properties` and `dist.get_world_size`, so it needs neither a GPU nor a process group, and every caller reaches it. `get_planner` still cannot take a qualified key: `eb_configs` is a flat list with no module to take a path from. A model that needs one builds its constraints and the planner directly, which the docstring now says. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(dynamicemb): correct what the API doc says about naming a table Two claims in `DynamicEmb_APIs.md` described behaviour that is gone. The planner no longer "validates that every table name appears exactly once": that uniqueness check was what refused a model two collections could declare one name in, and it is what the `TableKey` work removed. In its place the doc now has a section on how `constraints` is keyed -- qualified before bare, which is why a model whose names are unique needs no change -- what `get_constraint_key` is for and why it takes the config object, and the three cases that are refused. None of this was in the document a caller reads; it was only in the design note. The `NodePlacer` example returned `Dict[str, int]` keyed by table name. `place` returns `Dict[TableKey, int]`, so a placer written from that example would hand back keys the planner cannot look up. The example imports `TableKey`, returns `table.key`, and says what the pair is. The new section also says where the key does *not* work: `get_planner`'s three name arguments are keyed by the bare name, and as of the commit before this one it refuses a name `eb_configs` does not declare instead of planning the table some other way. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(dynamicemb): six design-note claims, and a README that still calls TRW future The design note described the planner it was written against rather than the one that exists. - `per_rank_storage` "needed no change" was true of M2 and false since: it is keyed by `TableKey` and buckets by `fusion_key`. The same row listed two of `plan.py`'s helpers where it now holds seven. - `local_hbm_for_values` was said to come from the world size. It is divided by the table's own fanout -- one node's worth under table-row-wise -- which is what §4.2 is about. The same sentence was wrong in `_prepare_dynemb_table_options`'s docstring, which is where a reader is most likely to trust it. - The step 2-4 sketch passed `table_names` to `module_without_tables`, which takes a set of `TableKey`. - Ties in the placer break on the key, not the name. - A pin that does not fit is refused naming `collection.name`. - `test_tables_that_do_not_fuse_do_not_pool_their_budgets` was said to have a case per component of `fusion_key`. It has five of six: the sharding type is fixed at table-row-wise by `TableToPlace.fusion_key`, so what guards that component is `per_rank_storage`, which reads each table's own. Saying "a case per attribute" invites the next reader to assume a guard that is not there. The note also now says that `get_planner` cannot express a qualified key and refuses a name `eb_configs` does not declare. `README.md` was two releases behind in both directions: its usage notes said a dynamic embedding table "is always row-wise sharding", and its future plans still listed `table-row-wise` among the shard types to add. It shipped in #493. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(dynamicemb): cost a caching group that fits as the runtime builds it `get_group_value_bytes_by_tier` asked about `caching` before asking whether the group fits. The runtime asks in the other order: `_create_cache_storage` tests `total_memory > local_hbm` first, and the `else` branch is HBM_ONLY -- it never reads `caching`, and warns that `external_storage` is ignored there as well. There is no cache and no backing tier for a group whose rows fit their budget. So a group that fits was charged its whole HBM budget plus its whole size again on the host: 4 GiB of rows with a 20 GB budget cost 20 GB of HBM and 4 GiB of host, where the runtime spends 4 GiB of HBM and nothing. Both figures over-state, which is the direction that refuses a layout that would have run rather than accepting one that will not -- the planner and `BalancedNodePlacer` both price through this function, so a model with a generous cache budget could fail to place on a machine with room for it. The fit check now comes first and the caching branch sits inside it, which leaves every other case as it was: CACHING and CACHING_PS when the rows do not fit, HOST_ONLY and HOST_PS when there is no budget to hold them, HYBRID when the budget covers part, HBM_ONLY when it covers all. One case remains deliberately unlike the runtime: `caching=True` with no HBM budget at all raises in `_create_cache_storage` ("Can't use caching mode as the reserved HBM size is too small") and is costed here as a host-only group. The planner accepts a configuration that will not build. That is a refusal to add, not an arithmetic change, and it is left for its own commit. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>

Description
Behaviour changes relative to
mainPublic API removed / moved.
DynamicEmbeddingEnumeratoris gone — theplanner no longer enumerates DynamicEmb tables, it decides them, so there is
nothing for an enumerator to do;
DynamicEmb_APIs.mddrops its section.dynamicemb/get_planner.pymoved todynamicemb/planner/get_planner.py, sofrom dynamicemb.get_planner import get_plannerno longer resolves — usefrom dynamicemb.planner import get_planner. Everything in-tree is updated.Counter.loadgained a requireddist_type. The abstract method indynamicemb.typesnow takes the key→rank rule, plus optionalshard_index/num_shards. Required rather than optional on purpose: a counter always belongsto a sharded table, so its rule is always known, and an implementation that
guesses drops the keys it guesses wrong about without saying so. Any
out-of-tree
Counterimplementation needs the new signature.A multi-rank load of a
continuoustable now raises. Checkpoint and counterloads used to filter with
keys % world_size == rankregardless of the table'sactual
dist_type— correct only forroundrobin, and meaningless forcontinuous, whose stored keys are block-local offsets rather than global keys.Both now apply the table's own rule, and
continuoushas no inverse, so itraises
NotImplementedErrorinstead of silently keeping the wrong ~1/N of thekeys. Single-rank loads are unaffected.
Checkpoint file names no longer follow a caller-supplied sub-group.
dumpand
loadname files by the table's own shard (shard_indexofnum_shards)rather than by
dist.get_rank(group=pg), because a table-row-wise table haslocal_world_sizeshards on one node while the caller holds one group for thewhole model.
pgis now the barrier's fallback instead.DynamicEmbDumpandDynamicEmbLoaddefault todist.group.WORLD, where old and new agree; only anexplicit sub-group differs, and checkpoints round-trip either way.
Checklist