Skip to main content

oa/ml/nn/
embedding.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_embedding.json
3// generator_version=8; schema_sha256=87804732b56f70b745d1122e270cac1b193bbc8e2ca2d750c0415108a4a3598d
4
5use crate::{DType, Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix, random};
8
9// OA donor: oacpp/source/cpp/lib/oa/ml/nn/embedding/embedding.cpp
10// Adaptation: Preserve existing Rust initialization, parameter versions and autograd; adapt donor structure to ModuleRegistry ownership
11/// Trainable FP32 lookup table indexed by an arbitrary-shape U8, U32, or I32 matrix.
12pub struct Embedding {
13	num_embeddings: usize,
14	embedding_dim: usize,
15	weight: Parameter,
16	registry: ModuleRegistry,
17}
18
19impl Embedding {
20	#[allow(clippy::too_many_arguments)]
21	pub fn new_with_seed(num_embeddings: usize, embedding_dim: usize, seed: u64) -> Result<Self> {
22		Self::new_with_seed_on(&Runtime::current()?, num_embeddings, embedding_dim, seed)
23	}
24
25	/// Construct a deterministically initialized embedding table.
26	///
27	/// # Errors
28	///
29	/// Returns an error when either dimension is zero, shape arithmetic overflows,
30	/// or allocation/upload fails.
31	pub fn new_with_seed_on(
32		runtime: &Runtime,
33		num_embeddings: usize,
34		embedding_dim: usize,
35		seed: u64,
36	) -> Result<Self> {
37		if num_embeddings == 0 || embedding_dim == 0 {
38			return Err(Error::invalid_argument(
39				"embedding dimensions must be nonzero",
40			));
41		}
42		let count = num_embeddings
43			.checked_mul(embedding_dim)
44			.ok_or_else(|| Error::invalid_argument("embedding weight size overflows usize"))?;
45		let limit = 1.0_f32 / (embedding_dim as f32).sqrt();
46		let values = random::symmetric_uniform(count, limit, seed);
47		let weight = Matrix::new_from_f32_on(runtime, [num_embeddings, embedding_dim], &values)?;
48		Self::new_from_matrix(weight)
49	}
50
51	/// Construct an embedding from an exact FP32 table shaped `[V, D]`.
52	///
53	/// # Errors
54	///
55	/// Returns an error unless `weight` is a nonempty rank-two FP32 matrix.
56	pub fn new_from_matrix(weight: Matrix) -> Result<Self> {
57		let [num_embeddings, embedding_dim] = weight.shape() else {
58			return Err(Error::invalid_argument(
59				"embedding weight must have rank two",
60			));
61		};
62		if *num_embeddings == 0 || *embedding_dim == 0 || weight.dtype() != DType::F32 {
63			return Err(Error::invalid_argument(
64				"embedding requires a nonempty FP32 weight [V, D]",
65			));
66		}
67		let num_embeddings = *num_embeddings;
68		let embedding_dim = *embedding_dim;
69		let weight = Parameter::new("weight", weight)?;
70		let mut registry = ModuleRegistry::new();
71		registry.register_parameter("weight", weight.clone())?;
72		Ok(Self {
73			num_embeddings,
74			embedding_dim,
75			weight,
76			registry,
77		})
78	}
79
80	/// Gather one embedding row per U8, U32, or non-negative I32 index.
81	///
82	/// The output shape is the complete index shape followed by `embedding_dim`.
83	/// Out-of-range indices produce NaN rows without reading outside the table.
84	///
85	/// # Errors
86	///
87	/// Returns an error when indices are not U8/U32/I32, the runtimes differ, shape
88	/// or ABI arithmetic overflows, or runtime recording fails. Negative I32 and
89	/// other out-of-range indices produce NaN rows without an out-of-bounds read.
90	pub fn forward(&self, indices: &Matrix) -> Result<Matrix> {
91		let (weight, version, requires_grad) = self.weight.snapshot();
92		let output = matrix::embedding(&weight, indices)?;
93		if requires_grad {
94			autograd::record_embedding(indices, &output, self.weight.clone(), weight, version)?;
95		}
96		Ok(output)
97	}
98
99	pub const fn num_embeddings(&self) -> usize {
100		self.num_embeddings
101	}
102
103	pub const fn embedding_dim(&self) -> usize {
104		self.embedding_dim
105	}
106
107	pub fn weight(&self) -> Parameter {
108		self.weight.clone()
109	}
110
111	pub fn parameters(&self) -> [Parameter; 1] {
112		[self.weight.clone()]
113	}
114}
115
116impl Module for Embedding {
117	fn forward(&self, input: &Matrix) -> Result<Matrix> {
118		Embedding::forward(self, input)
119	}
120
121	fn registry(&self) -> &ModuleRegistry {
122		&self.registry
123	}
124}