Repository navigation
Conversation
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]>
… 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]>
…t_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]>
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]>
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]>
…n 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]>
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]>
…e 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]>
`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]>
… 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]>
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]>
…rchrec `_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]>
… 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]>
… 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]>
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]>
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]>
…t 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]>
…s 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]>
…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]>
… 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]>
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]>
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]>
…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]>
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]>
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]>
`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]>
`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]>
…ot 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]>
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]>
… 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]>
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]>
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]>
…hRec 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]>
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]>
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]>
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]>
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]>
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]>
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]>
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]>
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]>
…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]>
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]>
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]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…it__ 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]>
…ards get_state_dict built the kernel's placeholder ShardedTensor with one shard per rank of pg and indexed this rank's shard by pg.rank(). A table-row-wise table has local_world_size shards placed on one node's ranks while pg is the world, so the assertion fired and DMP construction failed for any TABLE_ROW_WISE DynamicEmb table. Use the table's own shard count and find this rank's shard by placement. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…shard TorchRec's _initialize_torch_state registers an empty weight for table shards a rank does not hold, but skips CUSTOMIZED_KERNEL tables. Under row-wise every rank holds every DynamicEmb table so this never mattered; a table-row-wise table lives on one node, and on the other nodes reset_parameters then failed with 'Module has no attribute weight'. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…s once GroupedPooledEmbeddingsLookup received sharding_type and dropped it when building BatchedDynamicEmbeddingBag, so BaseBatchedEmbeddingBag kept pooling MEAN. The kernel then averaged each shard's rows and TorchRec's mean-pooling callback divided by the bag length again, so a MEAN-pooled DynamicEmb table returned sum/len^2 under row-wise and table-row-wise sharding. Hand sharding_type through, as TorchRec's own kernels do. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…r as owners The kernel registers a (1, 1) meta-device weight per table on the ranks that hold it. Registering an empty tensor on the other ranks made a torch.distributed.checkpoint save fail: two plain tensors with one fqn but different shapes are not deduplicated and the global plan asserts. Same shape, device and dtype on every rank restores the row-wise behaviour. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
| node = max( | ||
| range(num_nodes), | ||
| key=lambda n: (tightest(n).hbm, tightest(n).ddr, -n), | ||
| ) | ||
| room = tightest(node) | ||
| if not table.cost.fits_in(room): |
There was a problem hiding this comment.
Fitting nodes can be rejected. If the node with the most free HBM lacks enough DDR for a table, this code selects it and then raises “No node can hold,” even when another node has enough of both. Check which nodes fit before choosing among them. Pinned tables also need a fit check before their cost is charged.
| if options.caching: | ||
| return hbm_budget, 0 if external else total | ||
| if total > hbm_budget: | ||
| if external and hbm_budget <= 0: | ||
| return 0, 0 | ||
| return hbm_budget, total - hbm_budget | ||
| return total, 0 |
There was a problem hiding this comment.
Grouped storage is undercounted. When tables share a runtime, this code estimates each table’s HBM and host use separately, but the runtime combines their value sizes and HBM budgets before choosing storage. For tables with value sizes and budgets of 10/20 and 30/0 units, the estimates reserve 10 HBM units while the grouped runtime uses a 20-unit HBM budget. TorchRec can then be planned into HBM that DynamicEmb also uses, oversubscribing the rank.
Knowledge Base Used: Dynamic embedding tables
| counter_table.load( | ||
| counter_key_files[i], counter_frequency_files[i], table_id | ||
| counter_key_files[i], | ||
| counter_frequency_files[i], | ||
| table_id, | ||
| self._dynamicemb_options[table_id].dist_type, | ||
| ) |
There was a problem hiding this comment.
Existing custom counters cannot load. If a custom
Counter implements the previously documented three-argument load method, this new call passes it a fourth argument. The counter can still be instantiated, but checkpoint loading raises TypeError. Preserve compatibility or migrate the extension contract and its API documentation.
Knowledge Base Used: Dynamic embedding tables
| def forward( | ||
| self, | ||
| sparse_features: KeyedJaggedTensor, | ||
| ) -> Awaitable[Awaitable[KeyedJaggedTensor]]: | ||
| """Bucketize by ``dist_type``, shuffle, then TorchRec's AlltoAll unchanged. | ||
|
|
||
| ``num_buckets`` is ``local_size``, not the world: a table-row-wise table | ||
| is split across one node's ranks, so that is how many pieces its keys | ||
| are sorted into. This is the same number the planner sized the table's | ||
| per-rank capacity by (`table_fanout`), and they have to agree -- a key | ||
| the bucketizer sends to bucket `b` has to be a key the table on rank | ||
| `b` of that node believes it owns. | ||
| """ | ||
| bucketized_features, _ = bucketize_kjt_before_all2all( | ||
| sparse_features, | ||
| num_buckets=self._local_size, | ||
| block_sizes=self._feature_block_sizes_tensor, | ||
| output_permute=False, | ||
| bucketize_pos=( | ||
| self._has_feature_processor | ||
| if sparse_features.weights_or_none() is None | ||
| else self._need_pos | ||
| ), | ||
| dist_type_per_feature=self._dist_type_tensor, | ||
| ) | ||
| bucketized_features = bucketized_features.permute( | ||
| self._sf_staggered_shuffle, | ||
| self._sf_staggered_shuffle_tensor, | ||
| ) | ||
| return self._dist(bucketized_features) |
There was a problem hiding this comment.
Distributed execution lacks coverage. The new table-row-wise input path bucketizes, permutes, and redistributes keys, but the added tests cover placement and cost arithmetic rather than a distributed pooled forward/backward pass. A multi-node test covering redistribution, lookup, output collection, and gradients would catch integration failures that the current tests cannot.
Knowledge Base Used: Dynamic embedding tables
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| > Branch: `feat/dynamicemb-table-row-wise` (on top of `main` @ `97062d9`). | ||
| > Goal: let a DynamicEmb table be sharded `TABLE_ROW_WISE` (TRW) instead of | ||
| > `ROW_WISE` (RW), for `EmbeddingBagCollection` (pooled) only. | ||
| > Status: **design only** — nothing in this document has been implemented. |
There was a problem hiding this comment.
Design status is outdated. This document says none of the table-row-wise work is implemented, although this PR adds placement and a pooled runtime. Readers cannot tell which parts are available and which limitations remain. Update the status to distinguish implemented behavior from pending work.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Every checkpoint path derived its shard from the global process group:
file names from the caller's rank in pg, the load-time key filter in
_iter_batches_from_files, the hashtable and the admission counter from
dist.get_rank() / get_world_size(), and the per-table barrier over the
world. A table-row-wise table has local_world_size shards on one node,
so all of those were wrong for it and dump/load refused.
The kernel now carries the table's shard geometry, read from the shard
placements TorchRec planned: shard_ranks, num_shards, shard_index and
the intra-node group the table-row-wise sharding hands it. Dump names
files rank_{shard_index}.world_size_{num_shards}, shard 0 writes the
meta JSON and records sharding_type, num_shards and shard_ranks, and
the per-table barrier runs over the shard group, so nodes holding
different numbers of tables no longer deadlock. Load picks this shard's
file when the counts match and otherwise reads every file and keeps the
keys the rule assigns to this shard, so a checkpoint loads into any
geometry: row-wise to table-row-wise and back, or a different shard
count. Row-wise is unchanged: num_shards is the world size.
Incremental dump and replay still refuse table-row-wise tables.
Verified with a two-node emulation (round trips in both directions,
unequal per-node table counts), the existing dump/load, incremental and
pooled suites, and a 2x8 run whose 58 GB checkpoint reloaded onto 8 GPUs
with exact key counts and bit-identical values.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
| shard_index=rank, | ||
| num_shards=world_size, |
There was a problem hiding this comment.
External storage loads break. When a table uses a custom
external_storage implementation, checkpoint loading now passes shard_index and num_shards to its load method. The existing Storage.load interface does not declare these arguments, and the repository's PyDictStorage implementation does not accept them. Loading a checkpoint with such an implementation therefore raises TypeError instead of restoring the table.
Knowledge Base Used: Dynamic embedding tables
Remove the table-row-wise refusal from incremental_dump and replay_increment. A given process group is mapped onto the kernel's shard group so a gather can never wait on ranks that do not hold the table; with no group each rank dumps only the rows it owns. Delta meta records shard_index and shard_ranks next to world_size (the shard count). Replay filters ownership by the rank's index inside the shard group instead of the global rank. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ble-row-wise-fixes
Comments Outside DiffThese findings could not be posted inline.
|
|
this PR is already addressed in #493 |
Description
Checklist