Skip to content

Ignore torchrec's memory budget when plan for dynamicemb. - #106

Merged
shijieliu merged 1 commit into
NVIDIA:mainfrom
jiashuy:ignore_torchrec_topology
Jul 22, 2025
Merged

shijieliu merged 1 commit into
NVIDIA:mainfrom
jiashuy:ignore_torchrec_topology

Conversation

@jiashuy

@jiashuy jiashuy commented Jul 21, 2025 •

Copy link
Copy Markdown
Collaborator

Description

When we plan reserved HBM/DDR for both dynamicemb and torchrec, we adopt the fellow method:

1. Compute dynamicemb's needed.
2. Remove dynamicemb's consumption from the total budget(implemented by torchrec's topology).
3. Plan for torchrec using new budget.

In previous version(non-fused), the optimizer states' consumption is always not considered.
At present, we put embedding and optimizer states together, we can't detemine how many optimizer states needed when plan as we don't know the optimizer type.

So my solution is, if users use:

  • dynamicemb only: just provide the global_hbm_for_values.
  • both dynamicemb and torchrec: provide the global_hbm_for_values for dynamicemb; provide the topology for torchrec.

That means the dynamicemb's consumption is no longer covered by torchrec's memory budget.

Optional:

  1. users specify the optimizer type in DynamicEmbTableOptions:
  • they have to set the optimizer_type twice(another is in fused_params);
  • Need to update existed example and tests.
  1. hack the DynamicEmbeddingShardingPlanner
  • lazy initialization in collective_plan and get optimizer type from Sharder's fused_params.

Checklist

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

@jiashuy
jiashuy requested a review from shijieliu July 21, 2025 08:58
@jiashuy
jiashuy force-pushed the ignore_torchrec_topology branch from 0426ed9 to 6a0b5ab Compare July 22, 2025 02:43
@jiashuy
jiashuy force-pushed the ignore_torchrec_topology branch from 6a0b5ab to 5170d8d Compare July 22, 2025 02:49
@jiashuy

jiashuy commented Jul 22, 2025

Copy link
Copy Markdown
Collaborator Author

Please track CI hereCI

@shijieliu
shijieliu merged commit 5af4f9b into NVIDIA:main Jul 22, 2025
jiashuy added a commit to jiashuy/recsys-examples that referenced this pull request Oct 12, 2026
…r's budget

A DynamicEmb table is free in the planner's search space on purpose: one 1x1
shard per rank, because the planner does not choose its placement. Nothing
took its memory out of the budget, though. The planner was handed the whole
device and gave back five percent, then packed TorchRec tables into memory the
DynamicEmb tables had already claimed. `DynamicEmbeddingShardingPlanner`'s
docstring has said so since NVIDIA#106: "The memory budget does not include the
consumption of dynamicemb."

TorchRec has the seam for this. A `StorageReservation` reserves storage for
"non-sharded parts of the model", and from the planner's side that is exactly
what these tables are -- spent, but not searched over. Subclass the heuristical
one and subtract what the tables will take on top of what it already reserves.

Both tiers. A table spends the host tier for whatever does not fit its HBM
budget, and under `caching` the host holds every row while HBM only caches
them -- the same shape TorchRec's own estimator uses for `fused_uvm_caching`.
TorchRec's budget has a `ddr` column that `fits_in` checks and that
`fused_uvm`-family tables draw on, so leaving the host side out would have
repeated the HBM mistake one tier down.

Sizing a table needs to know its optimizer, and TorchRec lets a model say that
two ways -- `apply_optimizer_in_backward` puts the class on the parameter,
a sharder's `fused_params` carries the EmbOptimType. DynamicEmb's own tests
use both. Read either, parameter first, the way `merge_fused_params` resolves
them; `optimizer_type_to_emb_opt_type` is the bridge TorchRec already maintains
between the two vocabularies. A table with neither is counted without optimizer
state rather than guessed at.

Reading `local_hbm_for_values` in `reserve` rather than at construction is what
makes the timing work: `_prepare_dynemb_table_options` fills it in the planner's
constructor, after `get_planner` has built the Topology and well before `plan`
reserves.

Measured on two ranks, three tables chosen to take one branch each -- fits in
HBM, spills to host, caches -- against both optimizer conventions: 21.46 GB of
HBM and 25.03 GB of host reserved, equal to the hand-computed figures to the
byte, identical between the two conventions. Dump/load at 1, 2 and 8 ranks,
roundrobin and hash_roundrobin, the twin module and the pooled suite all pass.

Two limits, both written down at the class. What it reserves is a floor: the
value rows and the optimizer state sharing them, not the key map, the slot
metadata or the score columns. And the subtraction is per device by the same
amount, which is right only while every rank holds a slice of every table --
table-row-wise breaks that, and is where this has to become per-rank.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
jiashuy added a commit to jiashuy/recsys-examples that referenced this pull request Oct 12, 2026
…ables

A DynamicEmb table is free in the search space on purpose -- one 1x1 shard per
rank, because the planner does not decide its placement. What was missing is
the other half: nothing takes its HBM out of the budget either.
`local_hbm_for_values` is computed when the options are prepared and read when
the tables are built, and the planner never sees it, so TorchRec tables get
planned into memory that is already spoken for.

It is not a TRW bug -- the planner's own docstring has admitted it since NVIDIA#106.
It belongs in this document because TRW multiplies it by the node count, on
exactly the configurations TRW exists to serve, and because the risk list
otherwise reads as though R1 were only about eviction rate.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
shijieliu pushed a commit to shijieliu/recsys-examples that referenced this pull request Oct 19, 2026
…r's budget

A DynamicEmb table is free in the planner's search space on purpose: one 1x1
shard per rank, because the planner does not choose its placement. Nothing
took its memory out of the budget, though. The planner was handed the whole
device and gave back five percent, then packed TorchRec tables into memory the
DynamicEmb tables had already claimed. `DynamicEmbeddingShardingPlanner`'s
docstring has said so since NVIDIA#106: "The memory budget does not include the
consumption of dynamicemb."

TorchRec has the seam for this. A `StorageReservation` reserves storage for
"non-sharded parts of the model", and from the planner's side that is exactly
what these tables are -- spent, but not searched over. Subclass the heuristical
one and subtract what the tables will take on top of what it already reserves.

Both tiers. A table spends the host tier for whatever does not fit its HBM
budget, and under `caching` the host holds every row while HBM only caches
them -- the same shape TorchRec's own estimator uses for `fused_uvm_caching`.
TorchRec's budget has a `ddr` column that `fits_in` checks and that
`fused_uvm`-family tables draw on, so leaving the host side out would have
repeated the HBM mistake one tier down.

Sizing a table needs to know its optimizer, and TorchRec lets a model say that
two ways -- `apply_optimizer_in_backward` puts the class on the parameter,
a sharder's `fused_params` carries the EmbOptimType. DynamicEmb's own tests
use both. Read either, parameter first, the way `merge_fused_params` resolves
them; `optimizer_type_to_emb_opt_type` is the bridge TorchRec already maintains
between the two vocabularies. A table with neither is counted without optimizer
state rather than guessed at.

Reading `local_hbm_for_values` in `reserve` rather than at construction is what
makes the timing work: `_prepare_dynemb_table_options` fills it in the planner's
constructor, after `get_planner` has built the Topology and well before `plan`
reserves.

Measured on two ranks, three tables chosen to take one branch each -- fits in
HBM, spills to host, caches -- against both optimizer conventions: 21.46 GB of
HBM and 25.03 GB of host reserved, equal to the hand-computed figures to the
byte, identical between the two conventions. Dump/load at 1, 2 and 8 ranks,
roundrobin and hash_roundrobin, the twin module and the pooled suite all pass.

Two limits, both written down at the class. What it reserves is a floor: the
value rows and the optimizer state sharing them, not the key map, the slot
metadata or the score columns. And the subtraction is per device by the same
amount, which is right only while every rank holds a slice of every table --
table-row-wise breaks that, and is where this has to become per-rank.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
shijieliu pushed a commit to shijieliu/recsys-examples that referenced this pull request Oct 19, 2026
…ables

A DynamicEmb table is free in the search space on purpose -- one 1x1 shard per
rank, because the planner does not decide its placement. What was missing is
the other half: nothing takes its HBM out of the budget either.
`local_hbm_for_values` is computed when the options are prepared and read when
the tables are built, and the planner never sees it, so TorchRec tables get
planned into memory that is already spoken for.

It is not a TRW bug -- the planner's own docstring has admitted it since NVIDIA#106.
It belongs in this document because TRW multiplies it by the node count, on
exactly the configurations TRW exists to serve, and because the risk list
otherwise reads as though R1 were only about eviction rate.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
shijieliu added a commit that referenced this pull request Oct 19, 2026
* refactor(dynamicemb): one place that says which rank owns a key

A dynamic table stores global keys, so which rank holds one is not recorded
anywhere -- it is a rule, recomputed from the key at every point ownership
matters. That rule was written out five times: twice correctly (the bucketize
kernel and the replay mask, both dist_type-aware) and three times as a bare
`keys % world_size == rank`.

Collect it into dynamicemb/key_ownership.py and move `murmur3_fmix64` there
with it, since the rule is its only reason to exist on the host. This commit
only moves code; the three open-coded copies are converted next.

The shared version works in torch on the keys' own device rather than in
numpy on the host, which drops a round trip from the paths that hold a CUDA
tensor, and it narrows in unsigned 64-bit the way the device kernel does --
verified bit for bit against the numpy original over 200k keys, negatives
included, for thirteen fan-outs including non-powers-of-two.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(dynamicemb): a checkpoint load keeps the keys its dist_type gives this rank

The load path filtered with a bare `keys % world_size == rank`, which is the
roundrobin rule spelled out by hand. A hash_roundrobin table's rank-r file
holds the keys with `murmur(k) % ws == r`; that filter keeps only the ones
that also satisfy `k % ws == r`, roughly 1/ws of them, and discards the rest
without a word. The same line filtered the admission counter.

It was also signed where the device kernel is unsigned, so a negative key
disagreed with the kernel even under roundrobin.

Route both through `owned_key_mask`. The rule is the table's own, and the
loader already proves it matches the checkpoint's a few lines earlier, so
carry it on `_LoadParams` rather than reading the meta twice.

Two shapes this fixes at once: when the shard count matches the world size
each rank reads only its own file and the filter should be a no-op -- true
only for the right rule -- and when the counts differ the filter is what
re-splits the files across ranks.

`continuous` now raises here instead of dropping keys. It rewrites indices on
the way in (`new_idx = idx % blk_size`), so what a rank stores is not a global
key and no key-derived rule can place it; `replay_increment` already refuses
it for the same reason.

`ScoredHashTable.load` takes the rule as an optional argument: a table loaded
outside any sharding has no rule to apply, and defaulting to one would bring
back exactly the silent-drop this commit removes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): let tables in one sharding choose different dist_types

`_init_customized_distributor` asserted that every table carrying a dist_type
in a sharding carried the same one. Nothing needs that: the bucketize kernel
reads the rule per feature (`dist_type_per_feature[t]`), so a roundrobin table
and a hash_roundrobin table in one sharding are already handled. The assert
only rejected a configuration that works.

The method was also a verbatim duplicate across the sequence and pooled
classes; collect it into one function so the next two changes land once.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(dynamicemb): a dynamicemb table without a dist_type raises

A feature whose fused_params carry no dist_type fell back to `continuous`.
That is right for a plain TorchRec table -- it is what TorchRec's bucketizer
does -- and wrong for a DynamicEmb one, which `continuous` leaves storing
transformed indices rather than global keys. `incremental_dump`,
`replay_increment` and the checkpoint loader all refuse a table sharded that
way, so the fallback converts a missing setting into a table that cannot be
dumped incrementally or reloaded, and says nothing at the point the setting
was missing.

The planner always sets it, so nothing configured through
DynamicEmbeddingShardingPlanner reaches this; the raise is for plans built
another way.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* perf(dynamicemb): build the per-feature dist_type tensor once

The input distributor rebuilt it on every forward: a Python loop over
`kjt.keys()` with a dict lookup and string compares per feature, then a
`torch.tensor(..., device=cuda)`, which stages through pageable host memory
and blocks the host. It sits at the very front of the input dist, the part a
training pipeline most wants to run ahead on.

Its sibling `_feature_block_sizes_tensor` was already a constructor-time
buffer, and both describe the same fixed set of features. Build this one the
same way.

Two things follow. The bare loop, `assert key in ...` and `raise` leave the
traced graph, in a file that goes out of its way to stay traceable
(`torch.fx.wrap("len")`, `assert_fx_safe`, `_fx_wrap_gen_list_n_times`). And
the two arrays now come from one source in one order -- the kernel indexes
both with the same `t`, and nothing checked that the order agreed, only that
the counts did.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(dynamicemb): dump and reload a hash_roundrobin table on more than one rank

The hash_roundrobin dump/load smoke ran at --nproc_per_node 1, which is the
one world size where the load path does no ownership filtering at all -- so
it could not see the rule being wrong. Every multi-rank dump/load case used
the default roundrobin, where the wrong rule happens to be the right one.

Run it at 1 and 2 ranks. The load mode already compares the reloaded model's
output against the reference, so keys dropped on load fail the comparison.

Also point the dist_type assertion at the distributor's new buffer; it had
been reading an attribute that no longer exists, which its own
`seen_input_dist` guard would have reported as "not found" rather than as a
mismatch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): name the key->rank rules instead of numbering them

The bucketize kernel branched on a bare int -- `dist_type == 1`, `== 2`, and
an else -- while Python held the only statement of what 1 and 2 meant, in a
dict of its own. Two places had to agree on numbers neither of them named.

Give the rule an enum in src/utils.h, next to PoolingMode and for the same
reason: it is now the single source of the numbering, and the Python codes
are read from the bound enum rather than restated. `SUPPORTED_DIST_TYPES`
falls out of the same mapping, so the list of valid names stops being a third
copy.

Name it for the block / cyclic / block-cyclic vocabulary the kernels in that
file already use, and that FBGEMM's block_bucketize_sparse_features comes
from -- `continuous` is the only one of the three rules that uses the
`block_sizes` argument, and was the only one not named for it. The
Python-facing strings keep their older names: they go into every checkpoint's
meta and are compared on load, so renaming them would strand existing
checkpoints. `dynamicemb_config.DIST_TYPE_CODES` is the single place the two
vocabularies meet, and where a later rename would start.

Behaviour is unchanged, including the else-branch catch-all, which is now a
`default:` labelled with the case it stands for.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): the twin module seeds the keys its own dist_type gives it

Last of the five places that wrote the key -> rank rule by hand. This one was
not wrong: the twin module never sets dist_type, so its tables get the
"roundrobin" default and `indices % world_size == rank` is exactly right.

It is right by coincidence, though -- the rule is written here and the table
is configured over there, and nothing ties them together. Give the module one
dist_type, use it for both, and let owned_key_mask apply it. Changing how the
twin module shards now moves the seeding with it instead of silently seeding
the wrong ranks, and a hash_roundrobin twin becomes something that can be
asked for.

No behaviour change at the default.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): put the sharding runtime with the sharded modules

`planner/rw_sharding.py` holds RwSequenceDynamicEmbeddingSharding,
RwPooledDynamicEmbeddingSharding and their two lookups -- none of which plan
anything. They are the layer TorchRec keeps in distributed/sharding/, next to
the sharded modules, and the layering showed: shard/embedding.py and
shard/embeddingbag.py both reached back up into planner/ to construct them.

Move them, and input_dist.py with them, into shard/. Flat rather than a
sharding/ subpackage: TorchRec needs one because it has a dozen sharding
types, and we will have two or three, at which point the extra level costs
more than it explains.

Nothing but import paths changes. The layout, and why a new sharding type
belongs here rather than under planner/, is written down in shard/__init__.py
-- table-row-wise is about to add one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): name the planner module what torchrec names its own

`dynamicemb.planner.planner` stutters, and the file it mirrors upstream is
`torchrec/distributed/planner/planners.py`. Matching the name means that when
something changes in TorchRec's planner there is no step between reading the
upstream path and knowing which file here to open.

Nothing but the module name changes; everything outside the package imports
from `dynamicemb.planner` and does not notice.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): import from torchrec what we had copied out of it

Three things here were copies of TorchRec source, taken so that something
nearby could be changed, and then left to age.

`_calculate_rw_shard_sizes_and_offsets` was copied with no change at all --
it is line for line what `torchrec.distributed.sharding_plan` exports, minus
the `num_buckets` branch upstream has since grown for ZCH. The six
`_fx_wrap_*` helpers are likewise byte for byte `embedding_sharding`'s, each
checked against it before being dropped. Import all seven instead, and the
ZCH branch arrives for free.

`CACHE_LOAD_FACTOR_STR` came along with the `rw_sharding.py` copy that became
input_dist.py and was never referenced by anything here.

This leans on names TorchRec marks private. They are not covered by any
stability promise, so an upgrade can break the import -- but it breaks loudly
at import time, which is the failure mode we want: a copy that drifts instead
fails silently and years later.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): let the enumerator's filters fall through to torchrec

`_filter_sharding_types` and `_filter_compute_kernels` were copied whole so
that a DynamicEmb table could be answered with one line each. Everything
after that line was TorchRec's, and had stopped keeping up: upstream now
excludes GRID_SHARD unless asked for, guards row-wise for feature-processed
modules, drops KEY_VALUE when no device has SSD, and -- deliberately --
filters in the caller's order rather than through a set, because set-of-str
iteration depends on PYTHONHASHSEED and a collective planner would otherwise
build a different search space on different ranks.

Answer the DynamicEmb case and hand the rest to `super()`.

They took `use_dynamicemb` as an argument, which is why `enumerate` was
copied too: something had to thread it down. It was never necessary --
TorchRec passes these hooks the table's name, and the constraint is reachable
from it. Read it there instead, and both hooks go back to TorchRec's
signatures.

The module logger went with the bodies that used it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): hand the shard-size and constraint helpers back to torchrec

Two more copies, each carrying one DynamicEmb-shaped addition.

`_extract_constraints_for_param` returned TorchRec's tuple with
`use_dynamicemb` prepended, and threaded it down to whoever needed it. After
the filters started reading the constraint themselves, one caller was left --
so the copy goes entirely and TorchRec's is imported. That restores the
`copy.deepcopy` upstream added for `cache_params` and `key_value_params`,
which this copy had handed out by reference.

What it costs is a positional unpack of ten values from a function TorchRec
marks private. Adding or removing a field there fails loudly here; reordering
two fields of the same type would not, and `enforce_hbm` and
`stochastic_rounding` sit next to each other. The copy could not mis-bind but
could go stale, and stale is the harm we have already watched happen.

`calculate_shard_sizes_and_offsets` keeps a wrapper, because the 1x1 shard a
DynamicEmb table gets is genuinely not something TorchRec can express: there
are no rows to divide, only a hash table whose size and key placement come
from elsewhere. That case is now written down where it happens, and everything
else is delegated. GRID_SHARD stops raising as a result; `num_buckets` does
not follow, because `enumerate` here is still a copy and never computes it --
the capability arrives, the caller does not ask.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): inherit torchrec's row-wise distributor instead of copying it

`RwSparseFeaturesDist` reimplemented the whole distributor -- block sizes,
KJTAllToAll, splits, the sequence permute -- so that its forward could call
DynamicEmb's bucketizer instead of FBGEMM's. Everything but that one call was
TorchRec's, copied from a version whose `__init__` was 40 lines; upstream's is
now 106, having grown MPZCH bucket divisors, KVZCH uneven sharding and
`zch_bucketize_row_pos` in the meantime.

Subclass it. `super().__init__` does the distribution, this adds the
per-feature dist_type buffer, and `forward` swaps the one call.

Checked before relying on it: with the bucket arguments left at their
defaults, upstream computes the same `(hash_size + world_size - 1) //
world_size` per feature that this copy did, so nothing about the placement
moves.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(dynamicemb): ask the sharding rule which rank a key belongs to

The dump/load checks decided what each rank should be holding with
`key % world_size == rank`, the roundrobin rule written out by hand. It is
the sixth copy of that rule, and the one that made the other five hard to
see: the hash_roundrobin coverage ran at a single rank, where the only rank
owns everything and the oracle cannot be wrong.

Raised to two ranks it fails on `main` and on this branch alike, before
reaching any conclusion about the data -- so the test could not have told us
whether the load path it covers was correct.

Route it through the same `murmur3_fmix64` the sharding uses. With the oracle
fixed the two-rank hash_roundrobin case separates the trees the way it should:

    main  1 rank pass, 2 ranks FAIL
    here  1 rank pass, 2 ranks pass

`test_hybrid_storage_export.py` has the same line and is left alone: it never
configures a dist_type, so roundrobin is what it gets and the rule it wrote
out is the right one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): move get_planner into the planner package

It assembles constraints, a topology, an enumerator and a
DynamicEmbeddingShardingPlanner, and does nothing else. Sitting at the package
root it had to reach into `dynamicemb.planner` from outside to build the three
things that package exists to provide; inside, those are siblings.

Re-exported from `planner/__init__.py`, so the import reads
`from dynamicemb.planner import get_planner` -- imported last there, since it
builds what the other modules define.

This changes the module path. `get_planner` was never in the root package's
`__all__` and is not in DynamicEmb_APIs.md, but it is not purely internal
either: examples/commons/distributed/sharding.py imports it, and is updated
here along with the two tests.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): enumerate with torchrec's walk, then resize what it cannot know

The copy of `enumerate` existed for one keyword argument: the 1x1 shard a
DynamicEmb table is given, because it has no rows to divide and the planner
replaces its ParameterSharding wholesale afterwards anyway. Everything else in
those 120 lines was TorchRec's walk, and it had drifted four releases behind.

Let TorchRec walk, and rewrite those shards afterwards.

The most useful thing this gets back is not a fix. `populate_estimates` passes
`self._sharder_data_map` to every estimator, and the estimators index into it
unguarded; the field is initialised empty in `__init__` and filled by
`enumerate` -- by the one line this copy never had. The TorchRec in our
container predates that field, so nothing has broken yet. The upgrade that
introduces it would have raised KeyError on the first table, and no amount of
care in maintaining a copy would have caught it: a parent had given the child
a field to fill, and the child did not know.

Along with it come memoization, ZCH bucket sizes, weight stashing, and the
diagnostic context TorchRec wraps a ZeroDivisionError in. EmbeddingTowerCollection
stops raising "please revisit this logic" and does what upstream does.

The `calculate_shard_sizes_and_offsets` wrapper goes with it; rewriting the
shards afterwards is the only caller it had. 439 lines to 140.

Measured rather than argued, on two ranks with a model mixing DynamicEmb and
plain tables: the ShardingPlan comes out byte-identical to the copy's. Two
consecutive `enumerate` calls agree, which the memoization made worth checking
-- it caches before this rewrites, and returns a copy the rewrite then runs on
again. Full dump/load at 1, 2 and 8 ranks, roundrobin and hash_roundrobin, the
twin module and the pooled suite all pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): say where a dynamicemb table's compute kernel is decided

`compute_kernel_type = []` sat in the DynamicEmb branch under a TODO and was
never passed anywhere -- the other two branches hand theirs to the constraint,
this one computed a value and dropped it.

The TODO reads as unfinished work, and it is not: the kernel is decided, just
somewhere else. `DynamicEmbeddingEnumerator._filter_compute_kernels` pins it to
a single placeholder so the table stays in the search space without expanding
into kernels it will never use, and the planner replaces the whole
ParameterSharding, CUSTOMIZED_KERNEL included, once planning is done. Say that
instead, so the next reader looks in the right place rather than at an empty
list.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(dynamicemb): take the dynamicemb tables' memory out of the planner's budget

A DynamicEmb table is free in the planner's search space on purpose: one 1x1
shard per rank, because the planner does not choose its placement. Nothing
took its memory out of the budget, though. The planner was handed the whole
device and gave back five percent, then packed TorchRec tables into memory the
DynamicEmb tables had already claimed. `DynamicEmbeddingShardingPlanner`'s
docstring has said so since #106: "The memory budget does not include the
consumption of dynamicemb."

TorchRec has the seam for this. A `StorageReservation` reserves storage for
"non-sharded parts of the model", and from the planner's side that is exactly
what these tables are -- spent, but not searched over. Subclass the heuristical
one and subtract what the tables will take on top of what it already reserves.

Both tiers. A table spends the host tier for whatever does not fit its HBM
budget, and under `caching` the host holds every row while HBM only caches
them -- the same shape TorchRec's own estimator uses for `fused_uvm_caching`.
TorchRec's budget has a `ddr` column that `fits_in` checks and that
`fused_uvm`-family tables draw on, so leaving the host side out would have
repeated the HBM mistake one tier down.

Sizing a table needs to know its optimizer, and TorchRec lets a model say that
two ways -- `apply_optimizer_in_backward` puts the class on the parameter,
a sharder's `fused_params` carries the EmbOptimType. DynamicEmb's own tests
use both. Read either, parameter first, the way `merge_fused_params` resolves
them; `optimizer_type_to_emb_opt_type` is the bridge TorchRec already maintains
between the two vocabularies. A table with neither is counted without optimizer
state rather than guessed at.

Reading `local_hbm_for_values` in `reserve` rather than at construction is what
makes the timing work: `_prepare_dynemb_table_options` fills it in the planner's
constructor, after `get_planner` has built the Topology and well before `plan`
reserves.

Measured on two ranks, three tables chosen to take one branch each -- fits in
HBM, spills to host, caches -- against both optimizer conventions: 21.46 GB of
HBM and 25.03 GB of host reserved, equal to the hand-computed figures to the
byte, identical between the two conventions. Dump/load at 1, 2 and 8 ranks,
roundrobin and hash_roundrobin, the twin module and the pooled suite all pass.

Two limits, both written down at the class. What it reserves is a floor: the
value rows and the optimizer state sharing them, not the key map, the slot
metadata or the score columns. And the subtraction is per device by the same
amount, which is right only while every rank holds a slice of every table --
table-row-wise breaks that, and is where this has to become per-rank.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(dynamicemb): give the planner a node's host memory divided by its ranks

`Topology` keeps ddr per rank -- `[ddr_cap] * world_size`, replicated rather
than divided. `get_planner` handed it a node's host memory: the parameter's own
comment says "Assume a Node have 512GB memory", and example.py names its
variable the same way. So every rank was told it owned the whole node's RAM,
eight times too much on an eight-GPU node.

Nothing noticed while nothing was counted against it. Now that the DynamicEmb
tables' host footprint is reserved, an eight-fold overstatement is the
difference between a budget and a formality: on eight ranks the same tables go
from 1.0% of the stated ddr to 8.4% of it.

The parameter keeps meaning what its comment always claimed; the conversion
happens where the Topology is built. Dividing is right while the ranks of a
node spend host memory evenly, which they do under row-wise -- each holds a
slice of every table. Table-row-wise breaks that the same way it breaks the
per-device HBM subtraction, and in the same place.

The default moves from 512GB to 1TB per node. Dividing by the local world size
shrinks what any single rank is told it has, and the old figure was never a
measurement of a machine -- it was a guess made when it did not matter, since
nothing was being counted against it. A terabyte is a conservative guess for
the same nodes; a caller who knows theirs should pass it.

Not covered: the tests and benchmarks that construct a Topology directly with
`ddr_cap=1TB` bypass `get_planner` and still overstate it.

Also sorts this file's imports, which had accumulated `dist` and `ShardingType`
twice each, a commented-out import, and a comment about finalize_model_grads
sitting above something else.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* style(dynamicemb): run black over what this branch touched

black 23.9.1, the version both .pre-commit-config.yaml files pin. Three files
had drifted -- line joins and a stray blank line, no behaviour in any of them.
The other eighteen were already clean.

autoflake reports nothing new on the files this branch changed; what it flags
in types.py it flags on origin/main too. isort and codespell are not installed
here, and `corelib/dynamicemb/.pre-commit-config.yaml` does not run isort in
the first place, so the import order there is a judgement rather than a rule.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(dynamicemb): what supporting table-row-wise would take

Walk TorchRec's TWRW end to end -- construction, forward, backward -- and
write down what of it DynamicEmb can reuse and what it cannot. The compute
path turns out to be small: two method overrides, a ten-line permute, and
the whole backward comes free. The work is elsewhere -- a node placement
decision that does not exist because row-wise never needed one, a capacity
divisor that becomes per-table and is computed before placement is known,
a key-ownership rule copied into five places, and a checkpoint format that
assumes one shard per rank.

Record the risks with the same honesty: N-times per-rank capacity on an
evicting hash table is inherent to TRW and decides the project before any
code does.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(dynamicemb): the planner's budget never counted the dynamicemb tables

A DynamicEmb table is free in the search space on purpose -- one 1x1 shard per
rank, because the planner does not decide its placement. What was missing is
the other half: nothing takes its HBM out of the budget either.
`local_hbm_for_values` is computed when the options are prepared and read when
the tables are built, and the planner never sees it, so TorchRec tables get
planned into memory that is already spoken for.

It is not a TRW bug -- the planner's own docstring has admitted it since #106.
It belongs in this document because TRW multiplies it by the node count, on
exactly the configurations TRW exists to serve, and because the risk list
otherwise reads as though R1 were only about eviction rate.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(dynamicemb): the storage reservation has to become per-rank for trw

The reservation added on the fix branch subtracts one figure from every device,
which is correct precisely because row-wise gives every rank a slice of every
table. TRW does not: a table's HBM sits on one node's ranks and is zero on the
rest, so a uniform subtraction charges ranks holding nothing and the planner
refuses plans that would have fit.

`Topology.devices` carries a per-device `storage` and `rank`, so the per-rank
form is expressible; what it needs is which ranks hold which table, which is
the §4.1 placement decision. Recorded next to the capacity divisor, since both
follow from the same change and both land with §4.1.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(dynamicemb): point the trw plan at the code as it now stands

Written before the cleanup it depends on, the document still described the
layout it was reading: `planner/rw_sharding.py` for the sharding runtime,
`planner/planner.py` for the planner, `input_dist.py` at the package root. All
three moved, and the line numbers moved with them.

Rebased onto that cleanup and corrected against it -- seven spot-checked
references now land on the line they name. `planner/tw_rw_sharding.py` in the
files-to-change table becomes `shard/twrw_sharding.py`, which is where a new
sharding type goes now, and the table gains the two files the cleanup created:
`key_ownership.py`, whose rule has to learn a shard base, and
`planner/storage_reservations.py`, whose subtraction has to become per-rank.

The larger correction is that §8 described four defects as open when all four
are fixed, and §9 planned M0 as the next thing to do when it is done. Say so,
keep what each defect showed rather than only that it existed, and record the
one fact that outlived them: the hand-written ownership rule turned up in six
places, not five, because the sixth was in a test -- which is where to look
again when TRW makes that rule take a node.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(dynamicemb): stop the example handing a node's RAM to every rank

`example.py` builds its Topology by hand, on purpose -- it spells the planner
out step by step so a reader can see what goes into one -- and so it never
went through the `get_planner` fix. It carries the same mistake that fix was
for: `ddr_cap = 512GB  # Assume a Node have 512GB memory`, handed straight to
a Topology that replicates it to every device rather than dividing it. On
eight GPUs the example teaches the planner that the node has 4TB.

A wrong example is worse than wrong code, because it gets copied. Name the
variable for what it holds, divide where the Topology is built, and say why
in the comment, since explaining is what this file is for.

`hbm_cap` is left alone and marked: 80GB is already per GPU.

All four modes of run_example.sh pass on eight ranks.

The tests and benchmarks that construct a Topology directly still overstate
ddr the same way; they are not documentation and are left for their own change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(dynamicemb): count the dynamicemb tables wherever a planner is built

`get_planner` is not the only way to build one. Eight places construct a
Topology and a DynamicEmbeddingShardingPlanner by hand -- five tests, two
benchmark paths, `construct_twin_module`, and the example -- and each carried
both halves of the problem the last two commits fixed for `get_planner`:
`ddr_cap=1TB` handed to a Topology that replicates it per rank rather than
dividing it, and `HeuristicalStorageReservation`, which does not know the
DynamicEmb tables exist. The example was fixed for the first half one commit
ago and left with the second; that was half a fix.

`DynamicEmbStorageReservation` now takes the constraints instead of an options
dict, because the constraints are what every one of these sites has in hand
where the planner is built, and the options reached that way are the same
objects the planner mutates. `HeuristicalStorageReservation` no longer appears
outside the module that subclasses it.

Also: an external store takes the backing tier off the box, so it costs the
rank no host memory. Honoured in the two layouts that have a backing tier to
move -- CACHING_PS and HOST_PS -- and not in HybridStorage, which ignores
`external_storage` and warns, or in HBM-only, where there is no host tier.
Without this the reservation charged host memory for rows that live on a
parameter server, and could refuse a plan that would have run.

Two things it still gets wrong, now written down where the estimate is made:
the runtime sums across a grouped module and decides once for all of it, and
turns caching on for the group if any member asked. A mixed group is
under-counted and a table that fits alone can still be spilled with its group.
Neither is knowable here -- `group_tables` runs after planning.

Verified: test_pooled_embedding, test_sequence_embedding and test_twin_module
pass. incremental_dump, retain_evicted_keys and the example's four modes have
not been run against this -- the node expired mid-suite and the next one is
still queued. These are the paths where a tightened budget would show up, so
they need to run before this is relied on.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): one options object on the parameter sharding, not four fields

DynamicEmbParameterSharding carried four fields; three of them earned
nothing.

`customized_compute_kernel` was never read. Its whole life was to be set
to the constant `DynamicEmbKernel`, ride down into fused_params, and get
popped again before the kernel saw it -- in this tree and in TorchRec,
the only mentions are the declaration, the assignment and the pop.

`compute_kernel` only supplied a default. The one construction site
always passed it explicitly, so the default never applied. Dropping the
redeclaration restores the inherited field, which has no default, so a
construction that forgets it now fails loudly instead of silently
picking a kernel.

`dist_type` was a copy: the plan built it as `dist_type=opts.dist_type`
while also carrying `opts` itself. Nothing kept the two in step, so a
later edit to one of them would have left two readers disagreeing about
where a key lives -- and that rule decides which rank owns a key, so
disagreement is a wrong answer, not a warning. The reader in
rw_sharding now takes it from the options object.

What is left is one field, which is also the honest statement of what
crosses the boundary: a table's DynamicEmbTableOptions.

get_additional_fused_params already computed its payload as a field-set
difference, which is what keeps it correct when TorchRec adds fields to
ParameterSharding. pop_additional_fused_params wrote the same list out
by hand, so a fourth field would have had to be remembered in two
places. Both now share `_additional_field_names()`.

No checkpoint depends on any of this: the dist_type written into table
metadata comes from options_list, never from the ParameterSharding, and
nothing here serializes a plan. TorchRec cannot depend on the names
either -- it merges the dict wholesale and never indexes into it.

Not yet run on a GPU.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): take the dynamicemb tables out of the search space

The enumerator used to hand TorchRec a search space containing the
DynamicEmb tables, then the planner overwrote whatever TorchRec had
decided about them. Neither half was true to what happens: their
capacity comes from DynamicEmbTableOptions rather than num_embeddings,
and their placement is settled by the key -> rank rule, so there is
nothing for a proposer to propose or a perf model to rate. The 439-line
fork of `enumerate` existed to keep those pretend options alive through
a search whose result was then thrown away.

So they leave the search space instead. `enumerate` becomes a filter
over TorchRec's own result, and the fork -- with `_filter_sharding_types`,
`_filter_compute_kernels` and the 1x1 shard rewrite -- goes away. That
also ends the `_sharder_data_map` hazard: the fork never called
`build_sharder_data_map`, which a newer TorchRec's estimators index
unguarded.

Removing them from the search space means the merge can no longer be an
overwrite. A module whose tables are all DynamicEmb is now absent from
TorchRec's plan entirely, and DistributedModelParallel shards a module
only if the plan has an entry for its path -- it does not complain about
the ones it skips. So `_insert_dynamicemb_plan` walks the module tree to
find the path each table lives under, by the same rule the enumerator
descends by, and raises if a table's module is claimed by no sharder
rather than letting it fall through to an unsharded module.

This is the first half of the C2 split written up in the design
document's new section 4.9: planning is where we call TorchRec, so it is
where the dependency can come down to its API.

Not yet run on a GPU.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(dynamicemb): write down which seams stay subclassed and which do not

The question keeps coming back in a different form -- should we inherit
this enumerator, should we override module_type, do we still need our
own ParameterSharding -- so section 4.9 answers it once, with a rule
that decides each case instead of a judgement per case: subclass where
TorchRec calls us, compose where we call TorchRec.

The first set is the template-method hooks. TorchRec's base classes
invoke them from inside their own construction, so there is nothing to
register an implementation into and overriding is the only entry.
CUSTOMIZED_KERNEL reads like a dispatch point but is not one: all five
of its uses upstream skip something, and the branch that actually picks
our kernel is ours. That is why the chain ending at
BatchedDynamicEmbeddingTablesV2 is our code at every step that matters.
Six seams, and the version check in rw_sharding is what one of them
costs when a signature moves.

The second set is planning, where we drive. Nothing calls back into a
planner subclass, so inheritance buys nothing there and the enumerator,
the storage reservation and the planner itself become fields. That is
the C2 split, and the reason it is worth doing beyond the placement
problem in 4.1.

ParameterSharding and ParameterConstraints stay subclassed despite
sitting on the composition side, because they carry data rather than
behaviour and get_additional_fused_params is how TorchRec means that
data to travel.

Also marks M1 cancelled. The measurement still matters, but for telling
users which tables suit TRW, not for deciding whether to build it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(dynamicemb): two risks that come from the plan being a shared object

Both turned up while confirming that a sharder only reads the
ParameterSharding it is given. It mostly does, but the plan is passed by
reference the whole way down -- in the same call that deep-copies
feature_names, so TorchRec means it -- and two paths write back into it.

F10: replace_placement_with_meta_device rewrites every ShardMetadata
placement in place whenever DMP's device is meta, which is the ordinary
way to plan on cuda and build on meta. Ours reaches further than
TorchRec's, because _insert_dynamicemb_plan inserts the entries held on
the planner instance rather than copies of them, so a second
collective_plan from the same planner would hand out metadata the first
DMP had already rewritten.

F11: the key -> rank fan-out is read from two different places. Routing
gets it from the sharding process group, ownership from the default one.
Under DistributedModelParallel those agree and nothing shows; under
DMPCollection they do not, and a rank is fed the keys of one partition
while dumping the keys of another. Neither raises. This is true on the
branch today and is not caused by TRW, but TRW adds a second legitimate
reason for the fan-out to differ from the world size, so it should be
given one source before then.

Recommendations recorded, no code change yet.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(dynamicemb): the planner reads the fan-out from dist too, so F11 has a third source

F11 had routing and ownership disagreeing about how many ranks a key is
spread over. Planning is a third: `_prepare_dynemb_table_options` and
`_dyn_emb_plan` both open with `dist.get_world_size()` and never look at
the `pg` they were handed, so rows per shard, the local_hbm_for_values
divisor and the ShardMetadata count are all sized for the whole job
while TorchRec sizes its half of the same plan for pg.size().

That also widens the trigger. It is not only DMPCollection: any `pg`
argument to collective_plan that is not GroupMember.WORLD splits them,
which is an ordinary thing to pass.

Folded into F11 rather than listed separately because it is the same
defect at a third site, and fixing one site alone only moves the
disagreement.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(dynamicemb): what the dynamicemb tables cost each rank

The first half of planning in two steps: DynamicEmb settles its own
tables, then TorchRec plans the rest inside what is left. This is the
arithmetic that connects the two -- what each rank spends on the
DynamicEmb tables, and the topology that leaves behind.

Both read the plan rather than the constraints the plan was built from,
so the bytes subtracted here and the shards handed to the runtime are
one decision read twice instead of the same arithmetic done twice.

per_rank_storage returns one Storage per rank rather than one figure
repeated. Row-wise makes those equal and hides the difference, but a
table need not be on every rank: under TABLE_ROW_WISE it is on one
node's ranks and on no others, and charging every rank for it would
reserve four nodes' worth of room for one node's table.

topology_minus hands TorchRec a smaller Topology instead of a
StorageReservation that subtracts on its behalf. A reservation would
have to wrap whatever reservation the caller passed, which means
deciding which of the two subtracts first, and silently failing the
isinstance checks TorchRec's stats and error messages use
(planner/planners.py:1138, planner/stats.py:1109) -- they gate on
HeuristicalStorageReservation, so a wrapper reports zero dense and zero
KJT reservation in the very message a user reads when planning runs out
of memory. Reducing the Topology leaves the caller's reservation
untouched and doing exactly what the caller expects.

It does not clamp a negative result. Zero reads as "no room, plan
accordingly" and negative as "already oversubscribed"; only the second
is true, and the planner's error path reports the shortfall that a clamp
would hide.

Nothing calls these yet -- the planner still subtracts through
DynamicEmbStorageReservation. Tested standalone: single process, no GPU
and no process group, which is the point of having them as functions
over a plan.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(dynamicemb): hand TorchRec a module without the dynamicemb tables

TorchRec's enumerator walks the module it is given and enumerates every
table a sharder claims, so a table DynamicEmb has already placed has to
be out of that module. Filtering the search space afterwards -- what the
enumerator does today -- still runs the estimators over those tables
first, sizing shards from a capacity that is not what a DynamicEmb table
means by num_embeddings, and then throws the answer away.

Only the modules on the path to a pruned collection are copied. The
caller's module is not touched, and the tree keeps its shape, so the
paths in the returned plan are the paths the caller's module has --
which is what a ShardingPlan is keyed by, and what decides whether DMP
shards a module at all.

The collection's ModuleDict is pruned rather than the collection rebuilt
from a subset of its configs. Rebuilding needs constructor arguments
that are not all recoverable (EmbeddingCollection takes need_indices,
use_gather_select and use_gather_select_per_sharding, none with public
accessors) and would drop a subclass the caller may have passed, which
sharder_name(type(module)) matches on.

_embedding_bag_configs and _feature_names are left whole on purpose. The
enumerator reaches tables through shardable_parameters, which reads the
ModuleDict, so it no longer sees them; the storage reservation sizes the
input KJT from the feature names, and the KJT really does carry the
DynamicEmb features at runtime, so leaving them counted is the accurate
answer rather than a leftover.

A collection whose tables are all DynamicEmb becomes an empty one rather
than disappearing, because removing it would change the paths. That is
the shape the dump/load tests use, so it is the case that matters most.

Still nothing calls this. Tested single-process on meta tensors.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): plan in two steps, and let one rank decide

DynamicEmbeddingShardingPlanner now subclasses EmbeddingShardingPlanner
instead of owning one, and plans in the order the two halves actually
depend on each other:

  1. the DynamicEmb tables are already settled -- their capacity comes
     from their options and their placement from the key -> rank rule,
     so there is nothing for a proposer to propose;
  2. what they cost comes out of the Topology, per rank;
  3. TorchRec plans what is left of the model inside what is left of the
     memory, on a copy of the module with those tables taken out;
  4. the two halves are put back together.

Step 2 reduces the Topology rather than subtracting through a
StorageReservation. A reservation would have to wrap whatever reservation
the caller passed -- deciding which subtracts first -- and would fail the
isinstance checks TorchRec's stats and error messages gate on, so the
message a user reads when planning runs out of memory would report zero
dense and zero KJT reservation. Passing a smaller Topology leaves the
caller's reservation doing exactly what they expect. A
DynamicEmbStorageReservation handed to this planner is now ignored with a
DeprecationWarning, since it would charge for the tables twice.

Step 3 hands TorchRec a module without those tables instead of filtering
them out of the search space afterwards. Filtering still ran the
estimators over them first, sizing shards from a capacity that is not
what a DynamicEmb table means by num_embeddings.

Overriding plan() rather than collective_plan() means the inherited
collective_plan broadcasts the whole thing from rank 0, so the two halves
can no longer disagree across ranks -- which until now held only because
every rank happened to be handed identical constraints, and nothing
checked that.

What crosses the wire is the decisions. The DynamicEmbTableOptions are
reattached from each rank's own constraints afterwards, because some of
what they hold is rank-local by nature: external_storage is a live handle
to a store this process opened, and score_function is a Python callable.
Sending rank 0's copy of either would be wrong even where pickle allows
it. The shard metadata is checked against the options when the kernel is
built, so a rank whose options disagree with the decisions it was sent
does not go unnoticed.

The ParameterSharding put on the plan is a copy with its metadata
deep-copied (design doc F10): TorchRec rewrites placements in place when
DMP's device is meta, which would otherwise reach back into the planner's
own record of the table.

Not yet run on a GPU.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb)!: the planner takes what TorchRec's planner takes

The signature was TorchRec's ten arguments, rewritten, with eb_configs
in front. Rewriting them meant three of TorchRec's were missing --
callbacks, timeout_seconds and plan_loader were unreachable through this
planner -- and that gap would have widened every time upstream added
one. Now only the three arguments this planner actually does something
with are named, and the rest are forwarded.

eb_configs is gone. It carried each table's rows, dimension and dtype,
which the module carries too: the collections a sharder claims answer
embedding_bag_configs() or embedding_configs(). Asking the caller for
them again meant stating the same tables twice and no way to notice when
the two disagreed.

Reading them off the module means settling the DynamicEmb tables at plan
time rather than construction time, which needs care about which ranks
run it. _settle runs on every rank, before the broadcast: the options it
fills in are the half of a DynamicEmb table that stays local, and
_attach_options needs them everywhere, while _decide runs on rank 0
alone. What needs one rank's authority is the placement, and that is
what the broadcast covers. It settles once per planner, since the
options are filled in place and a second pass would re-align already
aligned capacities and warn about it.

Ten call sites updated. They all dropped two arguments and nothing else:
eb_configs, and the DynamicEmbStorageReservation that the previous
commit made redundant.

Breaking for anyone constructing DynamicEmbeddingShardingPlanner
directly. No deprecation shim: keeping eb_configs as an ignored argument
would leave callers believing the planner reads it.

Not yet run on a GPU.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb)!: delete DynamicEmbStorageReservation

Nothing subtracts through a StorageReservation any more -- the planner
takes what the DynamicEmb tables cost out of the Topology -- so the class
had no job left, and the isinstance guard that caught callers still
passing one was guarding against a name that no longer needs to exist.

`_optimizer_types` moves to planner/plan.py as `optimizer_types`, next to
per_rank_storage, its only remaining caller. That empties
planner/storage_reservations.py, which goes.

Also corrects two places that described the old arrangement: the
enumerator docstring, and the TRW design document's account of what
happens to the budget under table-row-wise, which asked for exactly the
per-rank deduction that now exists.

Breaking for anyone importing DynamicEmbStorageReservation. It is
unnecessary rather than renamed: TorchRec's own reservation, or a
caller's, still applies and still means what it meant.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(dynamicemb): stop rebuilding the default topology worse than TorchRec does

The `topology is None` branch built a Topology the base class was about
to build anyway, and built a poorer one. It passed hbm_cap and ddr_cap
from two module constants holding the same 32GB and 128GB TorchRec falls
back to on its own, so those made no difference; what it did change was
dropping `pod_size`, which the base passes from
get_topology_domain_multiple().

pod_size is not decoration. Topology multiplies it by local_world_size to
get _intra_group_size, the size of the high-bandwidth interconnect
domain, which is what tells a perf model that crossing a node costs more
than staying inside one. Losing it flattens exactly the distinction
table-row-wise exists to exploit -- so this would have mismodelled TRW
while looking like it worked.

Now `None` goes straight through to the base. The warning stays and says
more: the fallback capacities are constants rather than a measurement,
and the DynamicEmb tables get sized against them.

HBM_CAP and DDR_CAP go with it, and so does GB -- unused, and defined as
1024**4, which is a terabyte.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): drop the missing-topology warning

TorchRec builds a default Topology from `None` without comment, so
warning about it made an ordinary call look like a mistake. A caller who
wants to say what the machine has already can; one who does not is on
TorchRec's own default path.

That leaves `topology` a straight passthrough in this constructor. It
stays named rather than folded into **kwargs because its meaning here is
worth documenting: it is what the machine has, and what the DynamicEmb
tables cost is taken out of it before TorchRec sees it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb)!: delete DynamicEmbeddingEnumerator

Its whole job was to drop the DynamicEmb tables out of the search space
after TorchRec had enumerated them. The planner now takes them out of
the module before TorchRec sees it, so the filter matches nothing --
and the earlier arrangement was the worse one anyway, since it ran the
estimators over those tables first and threw the answer away.

Nothing else was in it: the constructor forwarded to super and stored a
`_constraints` the base already stores.

Ten call sites all built one the same way, from the topology, batch size
and constraints the planner was given in the same breath, and every one
of them already passed batch_size to the planner too. So the enumerator
TorchRec builds for itself is the same one, on a better set of
constraints -- ours, minus the DynamicEmb tables, which is what the base
is handed now.

DynamicEmb_APIs.md loses the section, and the planner's entry there is
rewritten: it had the old signature, described eb_configs, and said the
planner builds a TorchREC sub-planner, none of which is true any more.

Breaking for anyone importing DynamicEmbeddingEnumerator. It is
unnecessary rather than renamed -- pass TorchRec's own, or none.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* style(dynamicemb): black on five files it had not been run over

Collateral from formatting the directories the planner change touched.
No behaviour, and nothing to do with that change -- kept separate so it
does not hide in one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(dynamicemb): write down how the planner works now

Both documents still described the arrangement from before this branch:
a planner that owned a TorchRec sub-planner, built its tables in
__init__ from an eb_configs argument, let TorchRec enumerate them and
then overwrote the result, and reported their memory through a
StorageReservation. None of that is true.

The design document gets a walkthrough as section 2.1 -- the three
phases, what runs on every rank and what runs on rank 0, and why the
split falls where it does. Its map of where row-wise lives is rebuilt on
the files that exist, and six references to deleted modules and moved
lines are corrected: planner.py, planner/enumerators.py and
planner/storage_reservations.py are all gone. Section 2(a) said
collective_plan overwrites what TorchRec produced, which it no longer
does. The file list in section 5 drops the two deleted files and notes
that plan.py needs no TRW change, since per_rank_storage is already per
rank and reads the metadata _settle writes.

DynamicEmb_APIs.md gets the same walkthrough in the register that
document uses -- what happens when you call it, and what it does to your
options -- ahead of the table that was already there.

Every line number cited in the new text was checked against the file.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(dynamicemb): name the planner's steps after what they are

The methods were called _settle, _decide and _attach_options, which
described how the work is split across ranks rather than what it does.
Read in the order it runs, the planner does four things: plan the
DynamicEmb tables into ParameterShardings, deduct what they cost from
the planner's Topology, plan the remaining tables in what is left, and
assemble both halves into one ShardingPlan.

So _settle becomes _plan_dynamicemb, _decide becomes _plan_torchrec, and
the body of the latter is reordered to run in that order -- the budget
deduction before the module copy, which were independent and written the
other way round. Both documents are rewritten around the same four
steps.

One correction that came with it: _plan_torchrec's docstring said
__init__ settles the DynamicEmb tables. It has not since eb_configs went
away and the table configs started coming from the module.

No behaviour change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(dynamicemb): choose the node for a table-row-wise table (M2)

A DynamicEmb table can now be asked to live on one node, and the planner
works out which. Nothing consumes the result yet -- shard/embeddingbag.py
still dispatches only ROW_WISE -- so this is the plan taking the shape M3
will need.

Placement is a component of its own, planner/placement.py, so the rule
can be replaced without touching how a plan is assembled:

    class HostPlacer(abc.ABC):
        def place(self, tables, topology, committed) -> Dict[str, int]

The planner takes one as `host_placer=` and defaults to
BalancedHostPlacer: largest table first onto the emptiest node. Two
choices in that worth stating. It fits against the tightest rank of a
node rather than the node's total, because a table-row-wise table charges
every rank of its node the same. And it picks the emptiest node rather
than the first that fits, because TorchRec plans its own tables into what
is left afterwards and has a node decision of its own to make -- filling
nodes in order would hand it a machine with nothing on the low-numbered
ones.

Its inputs come from _choose_hosts: what each table costs one rank,
optimizer state included, and what the row-wise DynamicEmb tables have
already taken from every rank. Those shift no choice between nodes, since
they are on all of them, but they decide whether a TRW table still fits.

host_index survives as a pin. Pinned tables are charged first and the
rest fitted around them, so a caller who knows their layout for some
tables gets it without naming every node. It is refused on a row-wise
table rather than ignored: such a table is on every rank, so naming a
node for it means the caller expected something the plan will not do.

Capacity (4.2) splits into table_fanout and table_layout. The fan-out --
world_size for row-wise, local_size for table-row-wise -- depends on how
big a node is, not on which node, so a table is sized before it is
placed and the ordering this document feared would invert does not. That
correction is in 4.1 too: an earlier draft called automatic placement
hard because DynamicEmb tables have no cost notion, when in fact their
size is declared rather than estimated, which is what makes the packing
straightforward.

_prepare_dynemb_table_options takes world_size and local_size instead of
reading dist, and _plan_dynamicemb passes the Topology's. That removes
the planner's share of F11: dist.get_world_size() and get_local_size()
are gone from planners.py, leaving the Topology as the one statement of
how many ranks and how many nodes.

get_planner grows table_row_wise_embedding_table_names, since host_index
is now optional and can no longer double as the request.

Eighteen unit tests, single process. Nothing in this branch has run on a
GPU yet.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(dynamicemb): table-row-wise sharding runtime (M3)

A table-row-wise DynamicEmb table now has something to run on. The plan
M2 produces reaches shard/twrw_sharding.py instead of falling through to
TorchRec's own TwRw sharding, which does not know CUSTOMIZED_KERNEL.

Two methods differ from TorchRec's, the same two row-wise changes:
create_input_dist, to bucketize by DynamicEmb's key -> rank rule with
num_buckets = local_size; and create_lookup, to reach
BatchedDynamicEmbeddingBag. create_output_dist is deliberately not one of
them -- the intra-node reduce-scatter and the cross-node all-to-all are
used as they are, which is also what keeps the gradient division right
without our accounting for it: 1/L from one stage times 1/N from the
other.

create_lookup passes sharding_type=TABLE_ROW_WISE. That is not
decoration: it is what downgrades MEAN to SUM in the kernel, since a rank
holds part of a table's rows and cannot divide by a count it does not
have. ROW_WISE would be arithmetically identical today and wrong the
moment TorchRec separates the two.

The staggered shuffle did not have to be written. The design document
listed it under "must be written", but TorchRec's TwRwSparseFeaturesDist
already computes it and applies it between the bucketize and the a2a, so
overriding forward for the one call that differs inherits it. That is not
luck: the shuffle is arithmetic over feature counts, not over keys, so it
holds whatever the bucketizer did with the values. We pay for the gather
without owning it, which is what section 6 R2 already recorded.

EmbeddingCollection refuses TABLE_ROW_WISE rather than falling through. A
sequence output has nothing to reduce inside a node, so the arrangement
has no meaning there, and TorchRec has no TwRw sequence sharding to fall
through to.

Dump, load and incremental dump refuse a table-row-wise table.
_shard_world_size records a fan-out over the whole world, which is what
those paths filter keys by; a TRW table's keys were spread over one node,
so filtering by the world would keep roughly local/world of them and drop
the rest in silence -- the shape of the defect in section 8.1. Sections
4.5 to 4.7 are what fix it; until then this refuses rather than writing
something that cannot be read back.

The node the HostPlacer chose is written back to the table's options, so
a placed table does not look unplaced to anything reading the options
rather than the plan -- which is how the checkpoint guard above knows.

M3's gate is numerical parity against row-wise on a small model. That has
not been run: nothing in this branch has been on a GPU. What was checked
here is the staggered shuffle's arithmetic, standalone, against the
worked example in TorchRec's own docstring.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(dynamicemb): replay refuses table-row-wise tables too

The previous commit guarded dump, load and incremental_dump, and missed
replay_increment, which is reachable without any of them: a delta taken
from a row-wise run can be handed to a table-row-wise model. _apply_replay
filters the delta's keys with owned_key_mask over _shard_world_size, the
whole world, which is not the fan-out those keys were spread over.

Checked the other direction while here: every site that applies the
key -> rank rule is on a checkpoint or replay path -- key_value_table's
load, scored_hashtable's counter load, construct_twin_module, and
_apply_replay. None is in forward or backward, which is why refusing at
these four entry points is enough and the lookup path needs no guard.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(dynamicemb): two things the design predicted would be work, and were not

Section 3.4 contradicted itself: the staggered shuffle was listed both
under "reusable as-is" and under "must be written". The first entry was
right, and M3 resolved it that way -- TwRwSparseFeaturesDist computes the
shuffle and applies it, so overriding forward for the one call that
differs inherits it.

The CUDA bucketizer was the other. It was already right in section 5,
but as a prediction; it is now confirmed, and src/ is untouched by this
project.

Both are recorded with the reason rather than just the outcome, because
the reason is the same one and it generalises: the shuffle is arithmetic
over feature counts and the bucketizer is parameterized by a count, and
neither depends on what DynamicEmb does to a key. Anything shaped that
way is already ours to reuse, which covers more of TWRW than it looks
like it should.

The file list in section 5 is brought up to date while here: the two
files that turned out to need nothing, the two new planner files from
M2, and which of the remaining rows are M4 rather than undone.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(dynamicemb): three ways the planner rework broke the row-wise path

Found by auditing what the last twenty commits changed for a table that
is not table-row-wise. None of them had a test that would have caught it.

_prepare_dynemb_table_options was being handed only the DynamicEmb table
configs while still being handed every constraint, and it checks that the
two sets match. Any model with both kinds of table -- which is most of
them, and every mixed test in this repo -- would have failed planning
with "Not all constraint keys have matching BaseEmbeddingConfig names".
It now gets every config.

That check also changed meaning when eb_configs stopped being an argument
and started being read off the model. It used to compare two statements
of the same list, which is a real check. Against the model it became "the
model may not have a table you did not constrain", which is stricter than
anything intended: such a table is simply TorchRec's to plan. Only the
other direction survives -- a constraint naming a table the model does
not have is a typo -- and the per-table loop now skips a config with no
constraint instead of raising KeyError on it.

The planner wrote the placer's answer into the options before
table_layout saw it, so a host_index set on a row-wise table was
overwritten with None rather than refused. The documented behaviour, and
the unit test for it, were both still true of the function; the planner
just never let it be reached. It now writes back only for
table-row-wise, and a row-wise table keeps whatever the caller set so
that the refusal happens.

Also checked, and unchanged: table_fanout returns world_size for
row-wise, so no existing table resizes; module_without_tables returns the
module itself when nothing is removed; dist_type still reaches the
sharding through fused_params, and is read at sharding construction,
before the lookup pops it; the fan-out now comes from the Topology rather
than dist, which get_planner builds from dist.get_world_size(), so it is
the same number by that path.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(dynamicemb): build Storage without ssd on TorchRec < 1.5

Storage gained its ssd field in TorchRec 1.5.0; on 1.4.0 every
Storage(..., ssd=0) in the planner raised TypeError, so collective_plan
crashed on rank 0 and the planner tests failed. One helper constructs it
either way.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* test(dynamicemb): planner tests build Storage through make_storage

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(dynamicemb): keep the DynamicEmb constraints past TorchRec's __init__

EmbeddingShardingPlanner.__init__ assigns self._constraints, so setting it
before super().__init__ left the planner with only the non-DynamicEmb
subset. _plan_dynamicemb then found no DynamicEmb tables, pruned nothing,
and TorchRec planned every DynamicEmb table as a fused TBE table with its
default search -- table_wise / table_row_wise on the fused kernel -- with
no error raised. Assign after super().__init__ instead.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(dynamicemb): size the placeholder ShardedTensor by the table's shards

get_state_dict built the kernel's placeholder ShardedTensor with…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants