Skip to content
class

EmbeddingBagBackward

EmbeddingBagBackward

Python wrappers

Public Python APIs implemented by this engine symbols.

Pooled embedding lookup with per-bag reduction.

Fuses a row gather and a reduction over bags into a single backend call, avoiding the intermediate (B,L,D)(B, L, D) tensor that embedding followed by sum/mean/max would materialize. Variable-length bags are encoded as a flat indices tensor plus an offsets tensor that marks the start of each bag — bag bb consists of indices[offsets[b] : offsets[b+1]] (the last bag runs to the end of indices when include_last_offset=false).

No autograd node is currently wired for this op (sparse gradients are not yet supported on the Lucid backends), so the returned tensor is not differentiable with respect to weight.

Math

\begin{cases} \displaystyle\sum_{j\in\mathcal{B}_b} W[j] & \text{mode}=0\\[6pt] \displaystyle\frac{1}{|\mathcal{B}_b|}\sum_{j\in\mathcal{B}_b} W[j] & \text{mode}=1\\[6pt] \displaystyle\max_{j\in\mathcal{B}_b} W[j] & \text{mode}=2 \end{cases}$$ **See Also** embedding_op : Per-token lookup without reduction. Backward for `embedding_bag_op`. The op had none. `embedding` beside it wires one and this did not, which meant an `nn.EmbeddingBag` layer produced correct activations and no gradient at all — `weight.grad` stayed `None` and the layer never trained, with nothing raised to say so. The weight is saved only in `mode="max"`, which `EmbeddingBackward` does not need: `mode="max"` sends the incoming gradient only to the row that won each column, and the forward records no argmax, so the backward recomputes it from the weight it was given — kept by value in `saved_inputs_[0]`, `(num_embeddings, embed_dim)`. `sum` and `mean` read the indices alone, so they leave `saved_inputs_[0]` empty and a write into the weight after forward is not refused.

Parameters

weightTensorImplPtr
Embedding matrix of shape (V, D).
indicesTensorImplPtr
Flat 1-D integer tensor of all bag contents concatenated.
offsetsTensorImplPtr
1-D integer tensor of shape (B,) marking the start of each bag.
modeint
Reduction selector — 0 = sum, 1 = mean, 2 = max.
padding_idxint
Index that contributes zero to the reduction; negative disables.
include_last_offsetbool
If true, offsets is treated as (B+1,) so the last bag also has an explicit upper bound.

Instance methods

3
fn

apply

int apply(int grad_out)

Accumulate grad_out back onto the rows each bag gathered.

fn

apply_for_graph

int apply_for_graph(const int & grad_out)

Graph-mode backward: the rows each bag drew from are read on the host, as the eager backward reads them, and the gradient is a scatter-add of the bag gradients onto them — differentiable again in the gradient.

fn

release_own_saved

void release_own_saved()