Skip to main content

oa/ml/nn/
embedding_bag.rs

1//! Inference-and-training bag-of-embeddings lookup over per-bag offsets.
2
3use std::rc::Rc;
4
5use crate::{DType, Error, Matrix, Result, Runtime, matrix};
6
7use super::super::random;
8use super::super::{Module, ModuleRegistry};
9use super::Embedding;
10
11/// Reduction applied to each bag of looked-up embeddings.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13pub enum EmbeddingBagMode {
14	/// Elementwise mean of each bag's embeddings (`nn.EmbeddingBag` default).
15	#[default]
16	Mean,
17	/// Elementwise sum of each bag's embeddings.
18	Sum,
19}
20
21/// Bag-of-embeddings lookup: `embedding` lookup followed by a per-bag
22/// reduction, covering the `nn.EmbeddingBag` contract.
23///
24/// `forward` takes the flattened index matrix plus host `offsets` delimiting
25/// bags — the same boundary choice as `torch.nn.EmbeddingBag(mode='mean'|'sum')`,
26/// with offsets kept on the host side of the CPU/GPU contract because bag
27/// boundaries are data-shaping metadata, not device state.
28///
29/// The bag loop composes `slice` + `sum`/`mean` + `concat`, so gradients flow
30/// through `Embedding`'s own adjoint into the shared weight — a composed
31/// contract, not a fused kernel.
32pub struct EmbeddingBag {
33	embedding: Rc<Embedding>,
34	mode: EmbeddingBagMode,
35	registry: ModuleRegistry,
36}
37
38impl EmbeddingBag {
39	/// Construct with a uniformly initialized `[V, D]` table matching
40	/// [`Embedding::new_with_seed_on`].
41	///
42	/// # Errors
43	///
44	/// Returns an error for zero dimensions or table allocation failure.
45	pub fn new_with_seed_on(
46		runtime: &Runtime,
47		num_embeddings: usize,
48		embedding_dim: usize,
49		mode: EmbeddingBagMode,
50		seed: u64,
51	) -> Result<Self> {
52		let embedding = Embedding::new_with_seed_on(runtime, num_embeddings, embedding_dim, seed)?;
53		Self::new_from_embedding(embedding, mode)
54	}
55
56	/// Construct with a standard-normal table scaled by `stddev`.
57	///
58	/// # Errors
59	///
60	/// Returns an error for zero dimensions, non-finite or negative `stddev`,
61	/// or table allocation failure.
62	pub fn new_with_seed_normal_on(
63		runtime: &Runtime,
64		num_embeddings: usize,
65		embedding_dim: usize,
66		stddev: f32,
67		mode: EmbeddingBagMode,
68		seed: u64,
69	) -> Result<Self> {
70		if !stddev.is_finite() || stddev < 0.0 {
71			return Err(Error::invalid_argument(
72				"embedding bag stddev must be finite and non-negative",
73			));
74		}
75		let count = num_embeddings
76			.checked_mul(embedding_dim)
77			.ok_or_else(|| Error::invalid_argument("embedding bag weight size overflows usize"))?;
78		if count == 0 {
79			return Err(Error::invalid_argument(
80				"embedding bag dimensions must be nonzero",
81			));
82		}
83		let values = random::normal(count, stddev, seed);
84		let weight = Matrix::new_from_f32_on(runtime, [num_embeddings, embedding_dim], &values)?;
85		Self::new_from_embedding(Embedding::new_from_matrix(weight)?, mode)
86	}
87
88	/// Wrap an existing embedding table.
89	///
90	/// # Errors
91	///
92	/// Returns an error when child registration fails.
93	pub fn new_from_embedding(embedding: Embedding, mode: EmbeddingBagMode) -> Result<Self> {
94		let mut registry = ModuleRegistry::new();
95		let embedding = Rc::new(embedding);
96		registry.register_module("embedding", Rc::clone(&embedding) as Rc<dyn Module>)?;
97		Ok(Self {
98			embedding,
99			mode,
100			registry,
101		})
102	}
103
104	/// Wrap an exact FP32 `[V, D]` table.
105	///
106	/// # Errors
107	///
108	/// Returns an error unless `weight` passes [`Embedding::new_from_matrix`].
109	pub fn new_from_matrix(weight: Matrix, mode: EmbeddingBagMode) -> Result<Self> {
110		Self::new_from_embedding(Embedding::new_from_matrix(weight)?, mode)
111	}
112
113	/// Return the configured per-bag reduction.
114	pub const fn mode(&self) -> EmbeddingBagMode {
115		self.mode
116	}
117
118	/// Return the wrapped lookup table module.
119	pub fn embedding(&self) -> &Embedding {
120		&self.embedding
121	}
122
123	/// Look up `indices` and reduce each `[offsets[b], offsets[b+1])` bag.
124	///
125	/// `offsets` holds `num_bags + 1` boundaries over the flattened index
126	/// stream. Empty bags (`offsets[b] == offsets[b+1]`) are rejected rather
127	/// than silently producing NaN under `Mean`; empty output requires
128	/// `num_bags > 0`.
129	///
130	/// # Errors
131	///
132	/// Returns an error when `indices` is empty, `offsets` is malformed
133	/// (fewer than two entries, non-monotonic, or not ending at the index
134	/// count), any bag is empty, or the lookup/reduction dispatch fails.
135	pub fn forward(&self, indices: &Matrix, offsets: &[usize]) -> Result<Matrix> {
136		let index_count = indices.num_elements();
137		if matches!(indices.dtype(), DType::F32 | DType::F16) {
138			return Err(Error::invalid_argument(format!(
139				"embedding bag indices must be integer; found {}",
140				indices.dtype().token(),
141			)));
142		}
143		if index_count == 0 {
144			return Err(Error::invalid_argument("embedding bag requires indices"));
145		}
146		if offsets.len() < 2 {
147			return Err(Error::invalid_argument(
148				"embedding bag offsets must carry num_bags + 1 boundaries",
149			));
150		}
151		if offsets[0] != 0
152			|| !offsets.windows(2).all(|pair| pair[0] <= pair[1])
153			|| *offsets.last().unwrap_or(&0) != index_count
154		{
155			return Err(Error::invalid_argument(format!(
156				"embedding bag offsets must start at 0, be non-decreasing, and end at the index count {index_count}"
157			)));
158		}
159		if offsets.windows(2).any(|pair| pair[0] == pair[1]) {
160			return Err(Error::invalid_argument(
161				"embedding bag does not admit empty bags",
162			));
163		}
164		let embeddings = self.embedding.forward(indices)?;
165		let mut rows = Vec::with_capacity(offsets.len() - 1);
166		for pair in offsets.windows(2) {
167			let bag = matrix::slice(&embeddings, 0, pair[0] as i64, pair[1] as i64)?;
168			let reduced = match self.mode {
169				EmbeddingBagMode::Mean => matrix::mean(&bag, 0)?,
170				EmbeddingBagMode::Sum => matrix::sum(&bag, 0)?,
171			};
172			// The reduce ops keep the bag axis as a size-1 row.
173			rows.push(reduced);
174		}
175		matrix::concat(&rows, 0)
176	}
177}
178
179impl Module for EmbeddingBag {
180	fn forward(&self, input: &Matrix) -> Result<Matrix> {
181		let _ = input;
182		Err(Error::invalid_argument(
183			"EmbeddingBag requires indices plus host offsets; call EmbeddingBag::forward(indices, offsets)",
184		))
185	}
186
187	fn registry(&self) -> &ModuleRegistry {
188		&self.registry
189	}
190}