oa/ml/nn/
embedding.gen.rs1use crate::{DType, Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix, random};
8
9pub 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 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 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 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}