1use crate::{Error, Matrix, Result, Runtime};
6
7use super::{Embedding, Linear};
8
9use crate::ml::{Module, ModuleRegistry, Parameter, byte};
10
11pub struct ByteEmbedding {
15 inner: Embedding,
16}
17
18impl ByteEmbedding {
19 #[allow(clippy::too_many_arguments)]
20 pub fn new_with_seed(embedding_dim: usize, seed: u64) -> Result<Self> {
21 Self::new_with_seed_on(&Runtime::current()?, embedding_dim, seed)
22 }
23
24 pub fn new_with_seed_on(runtime: &Runtime, embedding_dim: usize, seed: u64) -> Result<Self> {
30 Ok(Self {
31 inner: Embedding::new_with_seed_on(runtime, byte::VOCAB_SIZE, embedding_dim, seed)?,
32 })
33 }
34
35 pub fn new_from_matrix(weight: Matrix) -> Result<Self> {
41 if weight.shape().first() != Some(&byte::VOCAB_SIZE) {
42 return Err(Error::invalid_argument(
43 "byte embedding weight must have shape [256, D]",
44 ));
45 }
46 Ok(Self {
47 inner: Embedding::new_from_matrix(weight)?,
48 })
49 }
50
51 pub fn forward(&self, byte_ids: &Matrix) -> Result<Matrix> {
57 self.inner.forward(byte_ids)
58 }
59
60 pub const fn embedding_dim(&self) -> usize {
62 self.inner.embedding_dim()
63 }
64
65 pub fn weight(&self) -> Parameter {
67 self.inner.weight()
68 }
69}
70
71impl Module for ByteEmbedding {
72 fn forward(&self, input: &Matrix) -> Result<Matrix> {
73 ByteEmbedding::forward(self, input)
74 }
75
76 fn registry(&self) -> &ModuleRegistry {
77 self.inner.registry()
78 }
79}
80
81pub struct ByteHead {
85 inner: Linear,
86}
87
88impl ByteHead {
89 #[allow(clippy::too_many_arguments)]
90 pub fn new_with_seed(input_features: usize, seed: u64) -> Result<Self> {
91 Self::new_with_seed_on(&Runtime::current()?, input_features, seed)
92 }
93
94 pub fn new_with_seed_on(runtime: &Runtime, input_features: usize, seed: u64) -> Result<Self> {
100 Ok(Self {
101 inner: Linear::new_with_seed_on(runtime, input_features, byte::VOCAB_SIZE, seed)?,
102 })
103 }
104
105 pub fn forward(&self, hidden: &Matrix) -> Result<Matrix> {
111 self.inner.forward(hidden)
112 }
113
114 pub const fn input_features(&self) -> usize {
116 self.inner.input_features()
117 }
118
119 pub fn weight(&self) -> Parameter {
121 self.inner.weight()
122 }
123
124 pub fn bias(&self) -> Parameter {
126 self
127 .inner
128 .bias()
129 .expect("byte head always constructs a trainable bias")
130 }
131}
132
133impl Module for ByteHead {
134 fn forward(&self, input: &Matrix) -> Result<Matrix> {
135 ByteHead::forward(self, input)
136 }
137
138 fn registry(&self) -> &ModuleRegistry {
139 self.inner.registry()
140 }
141}