oa/ml/nn/
embedding_bag.rs1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13pub enum EmbeddingBagMode {
14 #[default]
16 Mean,
17 Sum,
19}
20
21pub struct EmbeddingBag {
33 embedding: Rc<Embedding>,
34 mode: EmbeddingBagMode,
35 registry: ModuleRegistry,
36}
37
38impl EmbeddingBag {
39 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 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 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 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 pub const fn mode(&self) -> EmbeddingBagMode {
115 self.mode
116 }
117
118 pub fn embedding(&self) -> &Embedding {
120 &self.embedding
121 }
122
123 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 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}