1use std::{cell::Cell, rc::Rc};
6
7use crate::{DType, Error, Matrix, Result, Runtime, matrix};
8
9use super::super::{Module, ModuleRegistry, matrix::gelu};
10
11use super::{AttentionCache, AttentionMode, LayerNorm, Linear, Moe, MultiHeadAttention};
12
13#[derive(Clone, Copy)]
16enum FeedForwardConfig {
17 Dense,
18 Moe {
19 num_experts: usize,
20 experts_per_token: usize,
21 },
22}
23
24enum FeedForward {
25 Dense {
26 norm: Rc<LayerNorm>,
27 input: Rc<Linear>,
28 output: Rc<Linear>,
29 },
30 Moe(Rc<Moe>),
31}
32
33pub struct TransformerBlock {
35 model_width: usize,
36 hidden_width: usize,
37 sequence_length: Cell<usize>,
38 num_heads: usize,
39 norm_attention: Rc<LayerNorm>,
40 attention: Rc<MultiHeadAttention>,
41 feed_forward: FeedForward,
42 adaptive_modulation: Option<Rc<Linear>>,
43 condition_dim: Option<usize>,
44 registry: ModuleRegistry,
45}
46
47impl TransformerBlock {
48 pub fn new_with_seed(
49 model_width: usize,
50 hidden_width: usize,
51 sequence_length: usize,
52 num_heads: usize,
53 epsilon: f32,
54 seed: u64,
55 ) -> Result<Self> {
56 Self::new_with_seed_on(
57 &Runtime::current()?,
58 model_width,
59 hidden_width,
60 sequence_length,
61 num_heads,
62 epsilon,
63 seed,
64 )
65 }
66
67 #[allow(clippy::too_many_arguments)]
73 pub fn new_with_seed_on(
74 runtime: &Runtime,
75 model_width: usize,
76 hidden_width: usize,
77 sequence_length: usize,
78 num_heads: usize,
79 epsilon: f32,
80 seed: u64,
81 ) -> Result<Self> {
82 Self::new_with_seed_config(
83 runtime,
84 model_width,
85 hidden_width,
86 sequence_length,
87 num_heads,
88 num_heads,
89 epsilon,
90 seed,
91 FeedForwardConfig::Dense,
92 )
93 }
94
95 #[allow(
107 clippy::too_many_arguments,
108 reason = "the constructor preserves the donor block and conditioning dimensions"
109 )]
110 pub fn new_with_seed_conditioned(
111 model_width: usize,
112 hidden_width: usize,
113 sequence_length: usize,
114 num_heads: usize,
115 condition_dim: usize,
116 epsilon: f32,
117 seed: u64,
118 ) -> Result<Self> {
119 Self::new_with_seed_conditioned_on(
120 &Runtime::current()?,
121 model_width,
122 hidden_width,
123 sequence_length,
124 num_heads,
125 condition_dim,
126 epsilon,
127 seed,
128 )
129 }
130
131 #[allow(clippy::too_many_arguments)]
132 pub fn new_with_seed_conditioned_on(
133 runtime: &Runtime,
134 model_width: usize,
135 hidden_width: usize,
136 sequence_length: usize,
137 num_heads: usize,
138 condition_dim: usize,
139 epsilon: f32,
140 seed: u64,
141 ) -> Result<Self> {
142 Self::new_with_seed_on(
143 runtime,
144 model_width,
145 hidden_width,
146 sequence_length,
147 num_heads,
148 epsilon,
149 seed,
150 )?
151 .with_adaptive_conditioning(runtime, condition_dim)
152 }
153
154 #[allow(
164 clippy::too_many_arguments,
165 reason = "the constructor preserves the donor attention and MoE dimensions"
166 )]
167 pub fn new_with_seed_moe(
168 model_width: usize,
169 expert_hidden_width: usize,
170 sequence_length: usize,
171 num_heads: usize,
172 num_experts: usize,
173 experts_per_token: usize,
174 epsilon: f32,
175 seed: u64,
176 ) -> Result<Self> {
177 Self::new_with_seed_moe_on(
178 &Runtime::current()?,
179 model_width,
180 expert_hidden_width,
181 sequence_length,
182 num_heads,
183 num_experts,
184 experts_per_token,
185 epsilon,
186 seed,
187 )
188 }
189
190 #[allow(clippy::too_many_arguments)]
191 pub fn new_with_seed_moe_on(
192 runtime: &Runtime,
193 model_width: usize,
194 expert_hidden_width: usize,
195 sequence_length: usize,
196 num_heads: usize,
197 num_experts: usize,
198 experts_per_token: usize,
199 epsilon: f32,
200 seed: u64,
201 ) -> Result<Self> {
202 Self::new_with_seed_config(
203 runtime,
204 model_width,
205 expert_hidden_width,
206 sequence_length,
207 num_heads,
208 num_heads,
209 epsilon,
210 seed,
211 FeedForwardConfig::Moe {
212 num_experts,
213 experts_per_token,
214 },
215 )
216 }
217
218 #[allow(
225 clippy::too_many_arguments,
226 reason = "the constructor preserves the donor attention, MoE, and conditioning dimensions"
227 )]
228 pub fn new_with_seed_moe_conditioned(
229 model_width: usize,
230 expert_hidden_width: usize,
231 sequence_length: usize,
232 num_heads: usize,
233 num_experts: usize,
234 experts_per_token: usize,
235 condition_dim: usize,
236 epsilon: f32,
237 seed: u64,
238 ) -> Result<Self> {
239 Self::new_with_seed_moe_conditioned_on(
240 &Runtime::current()?,
241 model_width,
242 expert_hidden_width,
243 sequence_length,
244 num_heads,
245 num_experts,
246 experts_per_token,
247 condition_dim,
248 epsilon,
249 seed,
250 )
251 }
252
253 #[allow(clippy::too_many_arguments)]
254 pub fn new_with_seed_moe_conditioned_on(
255 runtime: &Runtime,
256 model_width: usize,
257 expert_hidden_width: usize,
258 sequence_length: usize,
259 num_heads: usize,
260 num_experts: usize,
261 experts_per_token: usize,
262 condition_dim: usize,
263 epsilon: f32,
264 seed: u64,
265 ) -> Result<Self> {
266 Self::new_with_seed_moe_on(
267 runtime,
268 model_width,
269 expert_hidden_width,
270 sequence_length,
271 num_heads,
272 num_experts,
273 experts_per_token,
274 epsilon,
275 seed,
276 )?
277 .with_adaptive_conditioning(runtime, condition_dim)
278 }
279
280 #[allow(clippy::too_many_arguments)]
290 pub fn new_with_seed_gqa_on(
291 runtime: &Runtime,
292 model_width: usize,
293 hidden_width: usize,
294 sequence_length: usize,
295 num_heads: usize,
296 num_kv_heads: usize,
297 epsilon: f32,
298 seed: u64,
299 ) -> Result<Self> {
300 Self::new_with_seed_config(
301 runtime,
302 model_width,
303 hidden_width,
304 sequence_length,
305 num_heads,
306 num_kv_heads,
307 epsilon,
308 seed,
309 FeedForwardConfig::Dense,
310 )
311 }
312
313 #[allow(
315 clippy::too_many_arguments,
316 reason = "shared constructor preserves public block recipes"
317 )]
318 fn new_with_seed_config(
319 runtime: &Runtime,
320 model_width: usize,
321 hidden_width: usize,
322 sequence_length: usize,
323 num_heads: usize,
324 num_kv_heads: usize,
325 epsilon: f32,
326 seed: u64,
327 config: FeedForwardConfig,
328 ) -> Result<Self> {
329 if matches!(config, FeedForwardConfig::Dense) && hidden_width == 0 {
330 return Err(Error::invalid_argument(
331 "Transformer FFN width must be nonzero",
332 ));
333 }
334 if num_kv_heads == 0 || !num_heads.is_multiple_of(num_kv_heads) {
335 return Err(Error::invalid_argument(
336 "Transformer requires a nonzero key/value head count dividing num_heads",
337 ));
338 }
339 let norm_attention = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
340 let attention = if num_kv_heads == num_heads {
341 Rc::new(MultiHeadAttention::new_with_seed_on(
342 runtime,
343 model_width,
344 num_heads,
345 sequence_length,
346 seed,
347 )?)
348 } else {
349 Rc::new(MultiHeadAttention::new_with_seed_and_options_grouped_on(
350 runtime,
351 model_width,
352 num_heads,
353 num_kv_heads,
354 sequence_length,
355 0.0,
356 true,
357 seed,
358 )?)
359 };
360 let mut registry = ModuleRegistry::new();
361 registry.register_module("ln_attn", norm_attention.clone())?;
362 registry.register_module("attention", attention.clone())?;
363 let feed_forward = match config {
364 FeedForwardConfig::Dense => {
365 let norm = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
366 let input = Rc::new(Linear::new_with_seed_on(
367 runtime,
368 model_width,
369 hidden_width,
370 seed.wrapping_add(4),
371 )?);
372 let output = Rc::new(Linear::new_with_seed_on(
373 runtime,
374 hidden_width,
375 model_width,
376 seed.wrapping_add(5),
377 )?);
378 registry.register_module("ln_ffn", norm.clone())?;
379 registry.register_module("ffn1", input.clone())?;
380 registry.register_module("ffn2", output.clone())?;
381 FeedForward::Dense {
382 norm,
383 input,
384 output,
385 }
386 }
387 FeedForwardConfig::Moe {
388 num_experts,
389 experts_per_token,
390 } => {
391 let moe = Rc::new(Moe::new_with_seed_on(
392 runtime,
393 model_width,
394 hidden_width,
395 num_experts,
396 experts_per_token,
397 epsilon,
398 seed.wrapping_add(4),
399 )?);
400 registry.register_module("moe", moe.clone())?;
401 FeedForward::Moe(moe)
402 }
403 };
404 Ok(Self {
405 model_width,
406 hidden_width,
407 sequence_length: Cell::new(sequence_length),
408 num_heads,
409 norm_attention,
410 attention,
411 feed_forward,
412 adaptive_modulation: None,
413 condition_dim: None,
414 registry,
415 })
416 }
417
418 fn with_adaptive_conditioning(mut self, runtime: &Runtime, condition_dim: usize) -> Result<Self> {
419 if condition_dim == 0 {
420 return Err(Error::invalid_argument(
421 "Transformer adaptive condition width must be nonzero",
422 ));
423 }
424 let modulation_width = self
425 .model_width
426 .checked_mul(6)
427 .ok_or_else(|| Error::invalid_argument("Transformer modulation width overflows usize"))?;
428 let weight_count = condition_dim
429 .checked_mul(modulation_width)
430 .ok_or_else(|| Error::invalid_argument("Transformer modulation size overflows usize"))?;
431 let weight = Matrix::new_from_f32_on(
432 runtime,
433 [modulation_width, condition_dim],
434 &vec![0.0; weight_count],
435 )?;
436 let bias = Matrix::new_from_f32_on(runtime, [modulation_width], &vec![0.0; modulation_width])?;
437 let adaptive_modulation = Rc::new(Linear::new_from_matrices(weight, bias)?);
438 self
439 .registry
440 .register_module("adaptive_modulation", adaptive_modulation.clone())?;
441 self.adaptive_modulation = Some(adaptive_modulation);
442 self.condition_dim = Some(condition_dim);
443 Ok(self)
444 }
445
446 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
452 self.forward_impl(input, None)
453 }
454
455 pub fn forward_masked(&self, input: &Matrix, additive_mask: &Matrix) -> Result<Matrix> {
462 self.forward_impl(input, Some(additive_mask))
463 }
464
465 pub fn forward_conditioned(&self, input: &Matrix, condition: &Matrix) -> Result<Matrix> {
473 self.forward_conditioned_impl(input, condition, None)
474 }
475
476 pub fn forward_conditioned_masked(
483 &self,
484 input: &Matrix,
485 condition: &Matrix,
486 additive_mask: &Matrix,
487 ) -> Result<Matrix> {
488 self.forward_conditioned_impl(input, condition, Some(additive_mask))
489 }
490
491 fn forward_conditioned_impl(
492 &self,
493 input: &Matrix,
494 condition: &Matrix,
495 additive_mask: Option<&Matrix>,
496 ) -> Result<Matrix> {
497 let Some(adaptive_modulation) = &self.adaptive_modulation else {
498 return Err(Error::failed_precondition(
499 "Transformer block was not constructed with adaptive conditioning",
500 ));
501 };
502 let condition_dim = self
503 .condition_dim
504 .expect("adaptive modulation and condition width are constructed together");
505 let [rows, features] = input.shape() else {
506 return Err(Error::invalid_argument(
507 "conditioned Transformer input must have shape [B*S, D]",
508 ));
509 };
510 let [condition_batch, condition_features] = condition.shape() else {
511 return Err(Error::invalid_argument(
512 "Transformer condition must have shape [B, C]",
513 ));
514 };
515 if input.dtype() != DType::F32
516 || condition.dtype() != DType::F32
517 || *features != self.model_width
518 || *rows == 0
519 || !rows.is_multiple_of(self.sequence_length.get())
520 || *condition_batch != rows / self.sequence_length.get()
521 || *condition_features != condition_dim
522 || !input.runtime().same_as(condition.runtime())
523 {
524 return Err(Error::invalid_argument(
525 "conditioned Transformer requires same-runtime F32 [B*S, D] input and [B, C] condition",
526 ));
527 }
528
529 let modulation = adaptive_modulation.forward(condition)?;
530 let modulation = matrix::repeat_interleave(&modulation, self.sequence_length.get(), 0)?;
531 let mut parts = Vec::with_capacity(6);
532 for index in 0..6 {
533 let start = index * self.model_width;
534 parts.push(matrix::slice(
535 &modulation,
536 1,
537 start as i64,
538 (start + self.model_width) as i64,
539 )?);
540 }
541
542 let attention_scale = matrix::add_scalar(&parts[1], 1.0)?;
543 let attention_normalized = self.norm_attention.forward(input)?;
544 let attention_normalized = matrix::mul(&attention_normalized, &attention_scale)?;
545 let attention_normalized = matrix::add(&attention_normalized, &parts[0])?;
546 let attention_delta = match additive_mask {
547 Some(mask) => self.attention.forward_masked(&attention_normalized, mask)?,
548 None => self.attention.forward(&attention_normalized)?,
549 };
550 let attention_delta = matrix::mul(&attention_delta, &parts[2])?;
551 let residual = matrix::add(input, &attention_delta)?;
552
553 let feed_forward_normalized = match &self.feed_forward {
554 FeedForward::Dense { norm, .. } => norm.forward(&residual)?,
555 FeedForward::Moe(_) => residual.clone(),
556 };
557 let feed_forward_scale = matrix::add_scalar(&parts[4], 1.0)?;
558 let feed_forward_normalized = matrix::mul(&feed_forward_normalized, &feed_forward_scale)?;
559 let feed_forward_normalized = matrix::add(&feed_forward_normalized, &parts[3])?;
560 let feed_forward_delta = match &self.feed_forward {
561 FeedForward::Dense { input, output, .. } => {
562 let hidden = gelu(&input.forward(&feed_forward_normalized)?)?;
563 output.forward(&hidden)?
564 }
565 FeedForward::Moe(moe) => moe.forward(&feed_forward_normalized)?,
566 };
567 let feed_forward_delta = matrix::mul(&feed_forward_delta, &parts[5])?;
568 matrix::add(&residual, &feed_forward_delta)
569 }
570
571 pub fn step(&self, input: &Matrix, cache: &mut AttentionCache) -> Result<Matrix> {
586 if self.is_adaptively_conditioned() {
587 return Err(Error::failed_precondition(
588 "TransformerBlock incremental decode does not admit adaptive conditioning",
589 ));
590 }
591 let normalized = self.norm_attention.forward(input)?;
592 let attended = self.attention.step(&normalized, cache)?;
593 let residual = matrix::add(input, &attended)?;
594 match &self.feed_forward {
595 FeedForward::Dense {
596 norm,
597 input,
598 output,
599 } => {
600 let normalized = norm.forward(&residual)?;
601 let hidden = gelu(&input.forward(&normalized)?)?;
602 let projected = output.forward(&hidden)?;
603 matrix::add(&residual, &projected)
604 }
605 FeedForward::Moe(moe) => moe.forward(&residual),
606 }
607 }
608
609 fn forward_impl(&self, input: &Matrix, additive_mask: Option<&Matrix>) -> Result<Matrix> {
610 let normalized = self.norm_attention.forward(input)?;
611 let attended = match additive_mask {
612 Some(mask) => self.attention.forward_masked(&normalized, mask)?,
613 None => self.attention.forward(&normalized)?,
614 };
615 let residual = matrix::add(input, &attended)?;
616 match &self.feed_forward {
617 FeedForward::Dense {
618 norm,
619 input,
620 output,
621 } => {
622 let normalized = norm.forward(&residual)?;
623 let hidden = gelu(&input.forward(&normalized)?)?;
624 let projected = output.forward(&hidden)?;
625 matrix::add(&residual, &projected)
626 }
627 FeedForward::Moe(moe) => moe.forward(&residual),
628 }
629 }
630
631 pub const fn model_width(&self) -> usize {
632 self.model_width
633 }
634 pub const fn hidden_width(&self) -> usize {
635 self.hidden_width
636 }
637 pub fn sequence_length(&self) -> usize {
638 self.sequence_length.get()
639 }
640 pub const fn num_heads(&self) -> usize {
641 self.num_heads
642 }
643
644 pub fn is_moe(&self) -> bool {
646 matches!(&self.feed_forward, FeedForward::Moe(_))
647 }
648
649 pub fn moe(&self) -> Option<&Moe> {
651 match &self.feed_forward {
652 FeedForward::Moe(moe) => Some(moe),
653 FeedForward::Dense { .. } => None,
654 }
655 }
656
657 pub fn is_adaptively_conditioned(&self) -> bool {
659 self.adaptive_modulation.is_some()
660 }
661
662 pub const fn condition_dim(&self) -> Option<usize> {
664 self.condition_dim
665 }
666
667 pub fn set_attention_mode(&self, mode: AttentionMode) {
669 self.attention.set_mode(mode);
670 }
671
672 pub fn attention_mode(&self) -> AttentionMode {
674 self.attention.mode()
675 }
676
677 pub fn set_sequence_length(&self, sequence_length: usize) -> Result<()> {
683 self.attention.set_sequence_length(sequence_length)?;
684 self.sequence_length.set(sequence_length);
685 Ok(())
686 }
687}
688
689impl Module for TransformerBlock {
690 fn forward(&self, input: &Matrix) -> Result<Matrix> {
691 TransformerBlock::forward(self, input)
692 }
693 fn registry(&self) -> &ModuleRegistry {
694 &self.registry
695 }
696}
697
698pub struct Transformer {
704 vocab_size: usize,
705 context_length: usize,
706 model_width: usize,
707 hidden_width: usize,
708 num_heads: usize,
709 num_kv_heads: usize,
710 token_embedding: Rc<super::Embedding>,
711 position_embedding: Rc<super::Embedding>,
712 blocks: Vec<Rc<TransformerBlock>>,
713 final_norm: Rc<LayerNorm>,
714 head: Rc<Linear>,
715 registry: ModuleRegistry,
716}
717
718impl Transformer {
719 #[allow(clippy::too_many_arguments)]
727 pub fn new_with_seed(
728 vocab_size: usize,
729 context_length: usize,
730 model_width: usize,
731 hidden_width: usize,
732 num_layers: usize,
733 num_heads: usize,
734 epsilon: f32,
735 seed: u64,
736 ) -> Result<Self> {
737 Self::new_with_seed_on(
738 &Runtime::current()?,
739 vocab_size,
740 context_length,
741 model_width,
742 hidden_width,
743 num_layers,
744 num_heads,
745 epsilon,
746 seed,
747 )
748 }
749
750 #[allow(clippy::too_many_arguments)]
751 pub fn new_with_seed_on(
752 runtime: &Runtime,
753 vocab_size: usize,
754 context_length: usize,
755 model_width: usize,
756 hidden_width: usize,
757 num_layers: usize,
758 num_heads: usize,
759 epsilon: f32,
760 seed: u64,
761 ) -> Result<Self> {
762 Self::new_with_seed_config(
763 runtime,
764 vocab_size,
765 context_length,
766 model_width,
767 hidden_width,
768 num_layers,
769 num_heads,
770 num_heads,
771 epsilon,
772 seed,
773 FeedForwardConfig::Dense,
774 )
775 }
776
777 #[allow(
787 clippy::too_many_arguments,
788 reason = "the constructor preserves the complete Transformer and MoE recipe"
789 )]
790 pub fn new_with_seed_moe(
791 vocab_size: usize,
792 context_length: usize,
793 model_width: usize,
794 expert_hidden_width: usize,
795 num_layers: usize,
796 num_heads: usize,
797 num_experts: usize,
798 experts_per_token: usize,
799 epsilon: f32,
800 seed: u64,
801 ) -> Result<Self> {
802 Self::new_with_seed_moe_on(
803 &Runtime::current()?,
804 vocab_size,
805 context_length,
806 model_width,
807 expert_hidden_width,
808 num_layers,
809 num_heads,
810 num_experts,
811 experts_per_token,
812 epsilon,
813 seed,
814 )
815 }
816
817 #[allow(clippy::too_many_arguments)]
818 pub fn new_with_seed_moe_on(
819 runtime: &Runtime,
820 vocab_size: usize,
821 context_length: usize,
822 model_width: usize,
823 expert_hidden_width: usize,
824 num_layers: usize,
825 num_heads: usize,
826 num_experts: usize,
827 experts_per_token: usize,
828 epsilon: f32,
829 seed: u64,
830 ) -> Result<Self> {
831 Self::new_with_seed_config(
832 runtime,
833 vocab_size,
834 context_length,
835 model_width,
836 expert_hidden_width,
837 num_layers,
838 num_heads,
839 num_heads,
840 epsilon,
841 seed,
842 FeedForwardConfig::Moe {
843 num_experts,
844 experts_per_token,
845 },
846 )
847 }
848
849 #[allow(clippy::too_many_arguments)]
860 pub fn new_with_seed_gqa(
861 vocab_size: usize,
862 context_length: usize,
863 model_width: usize,
864 hidden_width: usize,
865 num_layers: usize,
866 num_heads: usize,
867 num_kv_heads: usize,
868 epsilon: f32,
869 seed: u64,
870 ) -> Result<Self> {
871 Self::new_with_seed_gqa_on(
872 &Runtime::current()?,
873 vocab_size,
874 context_length,
875 model_width,
876 hidden_width,
877 num_layers,
878 num_heads,
879 num_kv_heads,
880 epsilon,
881 seed,
882 )
883 }
884
885 #[allow(clippy::too_many_arguments)]
886 pub fn new_with_seed_gqa_on(
887 runtime: &Runtime,
888 vocab_size: usize,
889 context_length: usize,
890 model_width: usize,
891 hidden_width: usize,
892 num_layers: usize,
893 num_heads: usize,
894 num_kv_heads: usize,
895 epsilon: f32,
896 seed: u64,
897 ) -> Result<Self> {
898 Self::new_with_seed_config(
899 runtime,
900 vocab_size,
901 context_length,
902 model_width,
903 hidden_width,
904 num_layers,
905 num_heads,
906 num_kv_heads,
907 epsilon,
908 seed,
909 FeedForwardConfig::Dense,
910 )
911 }
912
913 #[allow(
915 clippy::too_many_arguments,
916 reason = "shared constructor preserves public model recipes"
917 )]
918 fn new_with_seed_config(
919 runtime: &Runtime,
920 vocab_size: usize,
921 context_length: usize,
922 model_width: usize,
923 hidden_width: usize,
924 num_layers: usize,
925 num_heads: usize,
926 num_kv_heads: usize,
927 epsilon: f32,
928 seed: u64,
929 config: FeedForwardConfig,
930 ) -> Result<Self> {
931 let (seed_stride, valid_experts, dimension_error) = match config {
932 FeedForwardConfig::Dense => (
933 6,
934 true,
935 "Transformer requires positive dimensions, D divisible by H, and U32 positions",
936 ),
937 FeedForwardConfig::Moe { num_experts, .. } => (
938 8,
939 num_experts != 0,
940 "MoE Transformer requires positive dimensions, D divisible by H, and U32 positions",
941 ),
942 };
943 if vocab_size == 0
944 || context_length == 0
945 || model_width == 0
946 || hidden_width == 0
947 || num_layers == 0
948 || num_heads == 0
949 || num_kv_heads == 0
950 || !valid_experts
951 || !model_width.is_multiple_of(num_heads)
952 || !num_heads.is_multiple_of(num_kv_heads)
953 || u32::try_from(context_length - 1).is_err()
954 {
955 return Err(Error::invalid_argument(dimension_error));
956 }
957 let token_embedding = Rc::new(super::Embedding::new_with_seed_on(
958 runtime,
959 vocab_size,
960 model_width,
961 seed,
962 )?);
963 let position_embedding = Rc::new(super::Embedding::new_with_seed_on(
964 runtime,
965 context_length,
966 model_width,
967 seed.wrapping_add(1),
968 )?);
969 let mut registry = ModuleRegistry::new();
970 registry.register_module("token_embedding", token_embedding.clone())?;
971 registry.register_module("position_embedding", position_embedding.clone())?;
972 let mut blocks = Vec::with_capacity(num_layers);
973 for index in 0..num_layers {
974 let seed_offset = (index as u64).wrapping_mul(seed_stride).wrapping_add(2);
975 let block = Rc::new(TransformerBlock::new_with_seed_config(
976 runtime,
977 model_width,
978 hidden_width,
979 context_length,
980 num_heads,
981 num_kv_heads,
982 epsilon,
983 seed.wrapping_add(seed_offset),
984 config,
985 )?);
986 registry.register_module(format!("block_{index}"), block.clone())?;
987 blocks.push(block);
988 }
989 let final_norm = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
990 let head_seed = seed.wrapping_add(
991 (num_layers as u64)
992 .wrapping_mul(seed_stride)
993 .wrapping_add(2),
994 );
995 let head = Rc::new(Linear::new_with_seed_on(
996 runtime,
997 model_width,
998 vocab_size,
999 head_seed,
1000 )?);
1001 registry.register_module("final_norm", final_norm.clone())?;
1002 registry.register_module("head", head.clone())?;
1003 Ok(Self {
1004 vocab_size,
1005 context_length,
1006 model_width,
1007 hidden_width,
1008 num_heads,
1009 num_kv_heads,
1010 token_embedding,
1011 position_embedding,
1012 blocks,
1013 final_norm,
1014 head,
1015 registry,
1016 })
1017 }
1018
1019 pub fn forward(&self, tokens: &Matrix) -> Result<Matrix> {
1026 let [batch, sequence] = tokens.shape() else {
1027 return Err(Error::invalid_argument(
1028 "Transformer tokens must have shape [batch, context_length]",
1029 ));
1030 };
1031 if *batch == 0
1032 || *sequence != self.context_length
1033 || !matches!(tokens.dtype(), DType::U8 | DType::U32)
1034 {
1035 return Err(Error::invalid_argument(
1036 "Transformer tokens must be nonempty U8 or U32 [batch, context_length]",
1037 ));
1038 }
1039 let rows = batch
1040 .checked_mul(*sequence)
1041 .ok_or_else(|| Error::invalid_argument("Transformer row count overflows usize"))?;
1042 let position_values = (0..rows)
1043 .map(|index| (index % self.context_length) as u32)
1044 .collect::<Vec<_>>();
1045 let position_ids =
1046 Matrix::new_from_slice_handle(tokens.runtime(), vec![rows], &position_values)?;
1047 let token_values = self
1048 .token_embedding
1049 .forward(tokens)?
1050 .reshape([rows, self.model_width])?;
1051 let position_values = self.position_embedding.forward(&position_ids)?;
1052 let mut value = matrix::add(&token_values, &position_values)?;
1053 for block in &self.blocks {
1054 value = block.forward(&value)?;
1055 }
1056 self.head.forward(&self.final_norm.forward(&value)?)
1057 }
1058
1059 pub const fn vocab_size(&self) -> usize {
1060 self.vocab_size
1061 }
1062
1063 pub const fn context_length(&self) -> usize {
1064 self.context_length
1065 }
1066
1067 pub const fn model_width(&self) -> usize {
1068 self.model_width
1069 }
1070
1071 pub const fn hidden_width(&self) -> usize {
1072 self.hidden_width
1073 }
1074
1075 pub fn num_layers(&self) -> usize {
1076 self.blocks.len()
1077 }
1078
1079 pub const fn num_heads(&self) -> usize {
1080 self.num_heads
1081 }
1082
1083 pub const fn num_kv_heads(&self) -> usize {
1085 self.num_kv_heads
1086 }
1087
1088 pub fn is_moe(&self) -> bool {
1090 self.blocks.iter().all(|block| block.is_moe())
1091 }
1092
1093 pub fn block(&self, index: usize) -> Option<&TransformerBlock> {
1095 self.blocks.get(index).map(Rc::as_ref)
1096 }
1097
1098 pub fn new_cache(&self, batch_size: usize) -> Result<TransformerCache> {
1105 let mut caches = Vec::with_capacity(self.blocks.len());
1106 for block in &self.blocks {
1107 caches.push(block.attention.new_cache(batch_size)?);
1108 }
1109 Ok(TransformerCache {
1110 caches,
1111 position: 0,
1112 })
1113 }
1114
1115 pub fn step(&self, token: &Matrix, cache: &mut TransformerCache) -> Result<Matrix> {
1130 if cache.caches.len() != self.blocks.len() {
1131 return Err(Error::invalid_argument(
1132 "Transformer decode cache does not match the layer count",
1133 ));
1134 }
1135 let batch_size = cache
1136 .caches
1137 .first()
1138 .map(|entry| entry.batch_size())
1139 .unwrap_or(0);
1140 if token.shape() != [batch_size] || !matches!(token.dtype(), DType::U8 | DType::U32) {
1141 return Err(Error::invalid_argument(format!(
1142 "Transformer step requires a nonempty U8 or U32 token [{batch_size}]"
1143 )));
1144 }
1145 if cache.position >= self.context_length {
1146 return Err(Error::failed_precondition(
1147 "Transformer decode cache exhausted the context length",
1148 ));
1149 }
1150 let token_values = self.token_embedding.forward(token)?;
1151 let position_ids = Matrix::new_from_slice_handle(
1152 token.runtime(),
1153 vec![batch_size],
1154 &vec![cache.position as u32; batch_size],
1155 )?;
1156 let position_values = self.position_embedding.forward(&position_ids)?;
1157 let mut value = matrix::add(&token_values, &position_values)?;
1158 for (block, entry) in self.blocks.iter().zip(cache.caches.iter_mut()) {
1159 value = block.step(&value, entry)?;
1160 }
1161 cache.position += 1;
1162 self.head.forward(&self.final_norm.forward(&value)?)
1163 }
1164}
1165
1166pub struct TransformerCache {
1173 caches: Vec<AttentionCache>,
1174 position: usize,
1175}
1176
1177impl TransformerCache {
1178 pub const fn len(&self) -> usize {
1180 self.position
1181 }
1182
1183 pub const fn is_empty(&self) -> bool {
1185 self.position == 0
1186 }
1187}
1188
1189impl Module for Transformer {
1190 fn forward(&self, input: &Matrix) -> Result<Matrix> {
1191 Transformer::forward(self, input)
1192 }
1193
1194 fn registry(&self) -> &ModuleRegistry {
1195 &self.registry
1196 }
1197}