Repository navigation
Conversation
Greptile OverviewGreptile SummaryThis PR unifies embedding lookup/pooling onto a single Main merge-blockers are around pooling/sequence contract changes: Confidence Score: 2/5
Important Files Changed
Sequence DiagramsequenceDiagram
participant Caller as BatchedDynamicEmbeddingTablesV2.forward
participant Fn as DynamicEmbeddingFunction.forward/backward
participant Ext as dynamicemb_extensions (C++/CUDA)
participant Reduce as LocalReduce (lookup_backward)
Caller->>Fn: apply(indices, offsets, caches, storages, ..., pooling_mode, total_D, batch_size, dims, max_D, D_offsets)
Fn->>Ext: segmented_unique_cuda(...) (optional)
Fn->>Ext: gather_embedding_pooled(...) or gather_embedding(...)
Note over Fn,Ext: pooling_mode != NONE => output [B,total_D]
Fn-->>Caller: output_embs
Caller->>Fn: backward(grads)
Fn->>Ext: reduce_grads(reverse_indices, grads, num_unique, batch_size, out_dim, offsets?, D_offsets?, combiner, total_D)
Ext->>Reduce: LocalReduce.local_reduce(..., offsets/D_offsets/B/F/total_D/combiner)
Reduce-->>Ext: unique_grads
Ext-->>Fn: unique_grads
Fn-->>Caller: None (optimizer update in backward)
|
Additional Comments (1)
|
jiashuy
left a comment
There was a problem hiding this comment.
LGTM
There is no more KeyValueTable anymore, maybe we can rename KeyValueTable(Caching)Function to DynamicEmbeddingTable(Caching)Function
09955bf to
737448a
Compare
I think KeyValueTable can represent the general idea that we are dealing with key-value pair so let's keep it for now. |
Additional Comments (1)
Do the multiplication in |
Additional Comments (1)
|
Additional Comments (1)
|
* fix-issue-469
* fix and add test files
* fix bug and update file
* fix bug
* fix
* refactor(dynamicemb): replace raw int combiner with PoolingMode enum
combiner was a bare int carrying SUM=0 / MEAN=1, with an inconsistent
sentinel for "no pooling": reduce_grads defaulted it to -1 while
local_reduce and multi_to_one_reduce defaulted it to 0, i.e. SUM. The
sequence path relies on never passing offsets rather than on the value
being meaningful, so the mismatch was harmless but unguarded.
The numbering already matched dynamicemb.DynamicEmbPoolingMode
(SUM=0, MEAN=1, NONE=2), so:
- add dyn_emb::PoolingMode with kSum/kMean/kNone and thread it through
scatter_combine, local_reduce, multi_to_one_reduce, reduce_grads and
gather_embedding_pooled;
- use kNone as the single "no pooling" default everywhere, which nothing
in C++ ever tested for under its old -1 spelling;
- rename the parameter itself from combiner to pooling_mode on both
sides, since it now carries exactly the caller's pooling mode. This
also renames the pybind keyword argument, so callers passing
combiner=... by keyword must switch to pooling_mode=...; every
in-tree caller passes it positionally;
- drop the intermediate combiner variable in Python entirely. The
pooling mode goes straight to the ops and the autograd ctx carries
only ctx.pooling_mode, instead of storing the same value twice.
DynamicEmbPoolingMode now takes its values from the bound enum, the same
way DynamicEmbEvictStrategy does for EvictStrategy, so the numbers are
written once in C++. It stays an IntEnum because the pooling mode is
handed straight to the kernels and compared as an integer. Python imports
the bound enum under the alias BagPoolingMode, because fbgemm exports a
PoolingMode of its own that is already used alongside it. The API doc's
listing of the enum is updated to match, and spells out that IntEnum
semantics are deliberately preserved.
py::implicitly_convertible<py::int_, PoolingMode> keeps plain ints
accepted at the pybind boundary.
Not compiled: no CUDA toolchain in the authoring environment.
Co-Authored-By: Claude Opus 5 <[email protected]>
* fix(dynamicemb): tighten and de-duplicate the pooling_weights guards
Follow-up to the weighted-pooling support, covering four things found
while reviewing it:
- reject pooling_weights together with frequency_counters. Both are fed
from the single KeyedJaggedTensor weights channel -- the sequence path
reads it as LFU frequency counters, the weighted-pooling path as
per-sample weights -- so a caller supplying both has routed something
wrong. Today the two compute kernels each pass only one, so this
cannot trigger; it exists to fail loudly if that ever changes.
- drop the pooling_weights validation duplicated inside
DynamicEmbeddingFunction.forward. Its sole caller,
BatchedDynamicEmbeddingTablesV2.forward, already checks pooling mode,
training mode, dtype and numel, and the ops check dtype and numel
again in C++. The training-mode check has no counterpart there and
stays where it is.
- make gather_embedding_pooled and reduce_grads reject weights unless
pooling_mode is SUM. MEAN divides the weighted sum by the pool size,
which is neither a weighted sum nor a weighted average; without this
the ops would silently produce it. The rule was previously enforced
only in Python, and both ops are exported through
dynamicemb_extensions, so callers bypassing the module were unguarded.
- remove the second, identical registration of reduce_grads and
gather_embedding_pooled. Both were already registered earlier in
bind_dyn_emb_op and updated in place to take weights; the appended
copies are dead overloads that can never be selected.
Not compiled: no CUDA toolchain in the authoring environment.
Co-Authored-By: Claude Opus 5 <[email protected]>
* feat(dynamicemb): support weighted SUM pooling in eval mode
Weighted pooling used to raise ValueError outside training mode. That was
not a limitation of the algorithm -- the eval forward simply never routed
the weights to the op, and refusing was preferable to silently dropping
them and returning an unweighted sum.
Eval is in fact the easier half: it derives reverse_indices from the same
segmented_unique as training, so the weights line up identically, and it
has no backward, so none of the weight sorting or segmented accumulation
in reduce_grads is involved. All that was missing was the plumbing:
dynamicemb_eval_forward now takes pooling_weights and passes it to
gather_embedding_pooled, and BatchedDynamicEmbeddingTablesV2.forward
hands it down instead of rejecting the call.
This matters because BatchedDynamicEmbeddingBag.forward passes
features.weights_or_none() unconditionally, so an is_weighted=True
EmbeddingBagCollection could not be run under model.eval() at all --
inference of a weighted model failed outright rather than degrading.
The pooling-mode, dtype and numel checks are unchanged; they apply just
as much in eval, and TORCH_CHECK in the op still backs them up.
Not compiled or run: no CUDA toolchain in the authoring environment.
Co-Authored-By: Claude Opus 5 <[email protected]>
* fix(dynamicemb): only read KJT weights as pooling weights when is_weighted
BatchedDynamicEmbeddingBag.forward passed features.weights_or_none()
straight through as pooling weights regardless of whether the collection
had declared itself weighted. The weights channel of a KJT is shared:
TorchRec also fills it with per-feature scores for virtual-table eviction
(may_collect_feature_scores), and the sequence path reads it as LFU
frequency counters. Keying off GroupedEmbeddingConfig.is_weighted is what
disambiguates them, and it matches what an unsharded
EmbeddingBagCollection does with per_sample_weights, so this aligns the
two rather than inventing a rule.
No in-tree configuration reaches the collision today -- TorchRec's auto
score collection requires use_virtual_table, which DynamicEmb never sets,
and it asserts the weights are empty before writing scores -- so this is
a guard against the two mechanisms meeting later, not a fix for a live
bug.
It does change one observable behaviour: attaching weights to a KJT for
an is_weighted=False collection now yields an unweighted sum instead of a
weighted one, silently. The API doc calls that out explicitly.
Also refreshes three comments that the preceding commits left stale: the
PoolingMode enum in utils.h is now the source the Python side reads from
rather than a copy of it, the validation list in DynamicEmbeddingFunction
no longer mentions the training-mode check that eval support removed, and
one more "supported in training" line in the API doc.
Not compiled or run: no CUDA toolchain in the authoring environment.
Co-Authored-By: Claude Opus 5 <[email protected]>
* test(dynamicemb): compare weighted pooling against TorchRec, not a hand oracle
The weighted-pooling tests checked their results against a Python formula
built on the DEBUG initializer's key % 100000. That oracle only holds
while every row still carries its initializer value, which backward()
stops being true the moment it updates a key, and it encoded the caller's
own reading of the slot layout rather than TorchRec's. Both tests now
drive a real TorchRec model with the same input and compare against it.
Module level (test_weighted_pooled_embedding_v2.py), rewritten around an
unsharded weighted EmbeddingBagCollection:
- the reference table is initialized first and every row inserted into
dynamicemb, mirroring init_embedding_tables in
test_batched_dynamic_embedding_tables_v2.py, so the two sides start
identical and then each run their own optimizer with no re-syncing;
- the dynamicemb tables get twice the reference's capacity so eviction
cannot perturb the comparison, and keys stay inside the reference's
row range;
- each test runs the batch twice, so the second pass sees keys that are
already resident and already updated, then finishes with an eval-mode
forward to cover the separate inference path;
- dims [8], [8,4], [9], [9,6] cover both the vec4 and the cta-per-ev
kernel in both the uniform and the multi-dim shape;
- tolerances tighten from 1e-4/1e-3 to 1e-6/1e-6 now that both sides
start from the same rows.
End to end, ConstructTwinModule learns is_weighted and test_twin_module
gains a weighted axis. That subsumes test_weighted_pooled_embedding_fw.py,
which is removed along with its launcher: the twin test covers the same
KJT -> input_dist -> all2all -> lookup path while also checking the
numbers against TorchRec, verifying backward instead of merely running
it, and sweeping optimizers, dedup settings and 10 iterations. The
weighted axis is pinned to exact_row_wise_adagrad, since which optimizer
consumes the reduced gradient is orthogonal to how the weights scale it.
Also fixes a gap the weighted axis exposed: multi_hot_sizes was 1
everywhere, so a bag never held more than one key and pooling never
actually reduced anything. It now travels with the pooling mode -- 1 for
sequence, 8 for SUM -- so the reduction under test really runs.
Not run: no GPU or torchrec in the authoring environment.
Co-Authored-By: Claude Opus 5 <[email protected]>
* refactor(dynamicemb): drop two dead parameters left over from #301
Both date from when pooled lookup was invoked once per table, each call
writing into its own column range of a shared [B, total_D] output and
receiving a view into the shared offsets array. #301 merged those into a
single scatter_combine and expressed mixed dims through D_offsets
instead, which left the two compensations behind with nothing to
compensate for.
- accum_D was the running column base for that per-table loop. Its only
caller has passed a literal 0 ever since, and lookup_forward.h even
documented it as "ignored (pass 0)". Removing it also drops the
accum_D % 4 term from the vec4 kernel-selection guard, which 0 always
satisfied.
- get_offset() subtracted offset_ptr[0] to rebase a sliced offsets view
onto the per-table, zero-based reverse-index array. The offsets now
always arrive whole, so it subtracted zero. It was also only half a
guard: generate_gather_ids_pooled_kernel indexes gather_ids, sized
num_keys, with the raw offsets[s], so a non-zero base would already
write out of bounds in the backward pass. Dropping the subtraction
makes every path assume the same thing.
Neither changes behaviour -- both were adding or subtracting a compile
time zero -- but the struct fields and signatures no longer suggest a
flexibility that is not there.
Not compiled: no CUDA toolchain in the authoring environment. The
accum_D removal changes scatter_combine's parameter list, so a missed
call site would be a build error rather than a silent one.
Co-Authored-By: Claude Opus 5 <[email protected]>
* refactor(dynamicemb): give the lookup layout one written-down definition
The shape rules of a batched lookup were spread across five places in two
languages, as arithmetic in Python, arithmetic in CUDA, and prose in the
comments of both, with no authoritative copy. Working out which of two
bag numberings a bare int held meant reading the kernels.
dynamicemb/lookup_layout.py is now that copy. Its module docstring is the
spec: the input (offsets) numbers bags feature-major as s = f*B + b, the
pooled output numbers them batch-major as r = b*F + f, the two are
transposes, and a worked example pins the mapping down bag by bag. It
also records what total_D sums over, why the dedup buffer is always
max(dims) wide, and the invariants the kernels rely on.
EmbeddingLayout carries that for one call and src/pooled_layout.cuh
mirrors its pooled half device-side, member for member. The four places
that hand-wrote a numbering conversion -- f = s/B, b = i%B, f = id%F,
slot = f*B + b -- now go through named accessors, and __post_init__
enforces the two invariants the docstring states.
Threading the layout through shrank the signatures it passed as loose
integers:
- DynamicEmbeddingFunction.apply takes 13 arguments instead of 18, and
the autograd ctx carries one layout instead of eleven fields, two of
which nothing read;
- scatter_combine takes 9 instead of 15 and became a template, so the
three DataType tags and the void* pointers are gone, and it moved to
the header with its descriptor;
- local_reduce, multi_to_one_reduce and the two stage-1 kernels lost
their D_offsets/total_D/F/B parameters;
- the descriptor lost four fields that were all derivable: accum_D
(dead since #301), ev_size (== layout.max_D, the caller passed the
same value twice), num_vec_ (== layout.num_bags()) and the separate
batch_size/total_D/D_offsets_ptr trio.
Two identities found while doing this turned out to be exact, so the
code that branched on them is gone: out_dim was always emb_dim, because
Storage.max_embedding_dim() is max(dims); and gather_embedding_pooled's
dim argument equals max_D on both sides of its ternary. The remaining
slice of unique_values is still needed, but for a different reason than
its name suggested -- it strips the optimizer state -- which the comment
now says.
Also fixes a latent misalignment. Vec4T does a real 16-byte access when
it has four elements to move, so every address it touches must be
4-element aligned. The guards checked max_D and total_D but not each
feature's starting column, which under mixed dims comes from D_offsets.
dims = [2, 4, 2] passes both checks yet puts a 4-wide feature at column
2, and the vec4 kernels would fault on it; the backward guard did not
even check total_D. Whether every feature dim is a multiple of 4 cannot
be worked out on the host, since D_offsets is on the device, so it
travels as feature_dims_vec4 from EmbeddingLayout down to the two places
that choose a kernel. A regression test covers exactly that shape.
Renames at the pybind boundary, none of which any in-tree caller passes
by keyword: combiner -> pooling_mode, index -> inverse_index, and
reverse_indices -> inverse_index, the last two matching what
torch.unique calls the mapping.
Not compiled or run: no CUDA toolchain in the authoring environment.
Signatures, call sites and aggregate initializers were checked by hand
against each other, which catches argument mismatches but not type
deduction or template instantiation.
Co-Authored-By: Claude Opus 5 <[email protected]>
* perf(dynamicemb): carry the pooling weight through the wgrad sort
The weighted backward sorted twice over the same keys: once to bring
(inverse_index, gather_id) into unique-row order, and again to permute the
weights the same way. The second sort existed only because the weight lived in
a separate array; it was correct solely because radix sort is stable, so the two
passes produced the identical permutation -- an argument that had to be made
rather than a property of the code.
Pack both into the sort's value instead:
struct alignas(8) GradInfo { int32_t grad_index; float weight; };
The value used to be a bare gather id typed like the inverse indices, which
segmented_unique emits as int64, so it was 8 bytes already: sequence and
unweighted-pooled lookups move exactly as many bytes as before. Unweighted
keys store 1.0f and multiplying by it is exact in fp32, so the weight applies
unconditionally in the reduce kernels and no second instantiation of them is
needed -- the alternative, templating stage 1 on "is weighted", would have
doubled an already large instantiation matrix to buy the same thing.
cub's radix sort handles the struct exactly like a uint64_t: its downsweep
policies use BLOCK_LOAD_TRANSPOSE / WARP_TRANSPOSE / DIRECT and never
BLOCK_LOAD_VECTORIZE, so the "not a built-in primitive" fallback that would
have penalised a POD value type is unreachable here. alignas(8) matches the
uint64_t case exactly.
grad_index is int32, so reduce_grads now bounds both numbering schemes up
front: the key count (the sequence path's row is the key's own index) and the
bag count (the pooled path's row is a bag number).
Also folded in:
- the weights validation moves ahead of the grad-info kernel, which is now
the first thing to read them; same five checks, strictly earlier
- LocalReduce loses its weights argument, and gather_id is spelled
grad_index everywhere the name survived
Not yet compiled or run.
Co-Authored-By: Claude Opus 5 <[email protected]>
* refactor(dynamicemb): type the wgrad reduce on one index type
GradInfo::grad_index was int32, which bought a smaller sort value at the
price of two range checks -- one per numbering scheme -- that only fire
above two billion keys or bags. A check that can only be exercised at a
scale nobody runs is a check nobody will notice going stale. Type the row
as IndexType instead, and let the sort carry whatever the caller's indices
can express.
The index type now runs through the whole reduce unbroken:
- GradInfo is a template on it, so grad_index cannot be truncated.
- The offsets share it. reduce_grads converts them when the caller's
disagree; that is F*B+1 elements against num_keys of everything else,
and it retires offset_t as a separate template parameter, halving the
reduce's instantiations.
- LocalReduce is a class template on it, so partial_unique_ids is typed
by construction rather than by a DataType argument that had to agree
with the dispatch. The dead key_type_ goes with it. Explicit
instantiations for the two types DISPATCH_INTEGER_DATATYPE_FUNCTION
can produce keep the reduce kernels in one translation unit.
- reduce_grads collapses to a single dispatch spanning the grad_infos
build, the sort and the reduce, where it used to dispatch three times.
Since the index type is 64-bit throughout this codebase, GradInfo would
otherwise carry four bytes of tail padding, so it is packed to 4: 12 bytes
at alignment 4. That is +50% on the sort's value traffic against the old
int32 row, which a bandwidth model puts at roughly +3% on reduce_grads for
a 128-wide table and +11% for a 16-wide one -- the reduce itself moves a
D-wide vector per key, so the sort is the minority term. pack(1) is
avoided deliberately; it would degrade cub's shared-memory exchange to
byte granularity.
Two bounds survive, both narrowed to what actually constrains them. The
bag count must still fit an int, because PooledLayout numbers bags with
ints -- the message now says so instead of blaming GradInfo. The key
count is unbounded again, which is the point: a sequence reduce addresses
grads by the key's own index.
Also: id_t and io_t are spelled index_t and grad_t, matching the names
their callers already use; local_reduce no longer re-validates
sorted_grad_infos, nor multi_to_one_reduce the index dtypes, both of which
the types now guarantee.
Not compiled or run. The packed struct's effect on cub and on 8-byte
member access in device code is reasoned about, not measured.
Co-Authored-By: Claude Opus 5 <[email protected]>
* fix(dynamicemb): reject differentiable pooling weights instead of dropping their gradient
The backward returns None for every input, pooling_weights included.
Autograd reads a None gradient as zero, not as an error, so a module
producing learned per-position weights would train as though its output
were detached: no warning, no exception, just weights that never move.
That is worse than the feature being absent, because it looks like it
works.
Refuse the input rather than compute a gradient for it. Computing one is
a real piece of work -- it needs the forward embeddings kept alive past
the optimizer update, which differs per storage path -- and it belongs in
its own change, not smuggled in beside a reduce refactor.
The guard is on grad mode, not on requires_grad alone. Under no_grad()
there is no backward to lose anything to, and eval callers routinely pass
tensors that merely happen to carry the flag; rejecting those would break
weighted pooling in eval, which this branch deliberately supports.
Documented in DynamicEmb_APIs.md, and both halves pinned by tests: the
rejection, and the no_grad() carve-out that keeps eval working.
Co-Authored-By: Claude Opus 5 <[email protected]>
* fix(dynamicemb): check the forward's offsets and inverse indices agree in dtype
gather_embedding_pooled derives one index type from the offsets and then
reads the inverse indices through it too -- ForwardMultiToOneFMLayoutDesc
requires the two to have the same width. Nothing enforced that. A
mismatch would reinterpret the inverse indices rather than convert them;
it has stayed latent only because both are 64-bit here, where int64 and
uint64 alias harmlessly for non-negative values.
reduce_grads now converts the offsets when the caller's types disagree,
which left the two halves inconsistent. The forward has no natural point
to allocate a conversion, so it checks instead.
Not compiled or run.
Co-Authored-By: Claude Opus 5 <[email protected]>
---------
Co-authored-by: linjiangxian <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
Description
Checklist
CI