Skip to main content

oa/ml/nn/
rope.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_rope.json
3// generator_version=8; schema_sha256=ad31cadd74a43cd80eff08346285c2feba4708a65ac92fae380b49669120d64e
4
5use crate::{Error, Matrix, Result};
6
7use super::super::{Module, ModuleRegistry, matrix};
8
9// OA donor: oacpp/source/cpp/lib/oa/ml/nn/rope/rope.cpp
10// Adaptation: Preserved checked head geometry, finite positive theta and zero position offset; existing Matrix provider owns donor split-half rotation and adjoint
11/// Llama-style split-half rotary position embedding module.
12pub struct Rope {
13	num_heads: usize,
14	head_dim: usize,
15	theta_base: f32,
16	registry: ModuleRegistry,
17}
18
19impl Rope {
20	/// Construct a parameterless rotary-position module.
21	///
22	/// # Errors
23	///
24	/// Returns an error unless both dimensions are nonzero, `head_dim` is even,
25	/// their product fits `usize`, and `theta_base` is finite and positive.
26	pub fn new(num_heads: usize, head_dim: usize, theta_base: f32) -> Result<Self> {
27		if num_heads == 0
28			|| head_dim == 0
29			|| !head_dim.is_multiple_of(2)
30			|| !theta_base.is_finite()
31			|| theta_base <= 0.0
32			|| num_heads.checked_mul(head_dim).is_none()
33		{
34			return Err(Error::invalid_argument(
35				"RoPE requires nonzero heads, an even head dimension, and a finite positive theta base",
36			));
37		}
38		Ok(Self {
39			num_heads,
40			head_dim,
41			theta_base,
42			registry: ModuleRegistry::new(),
43		})
44	}
45
46	/// Rotate a sequence beginning at absolute position zero.
47	///
48	/// # Errors
49	///
50	/// Returns an error unless input is compatible F32 `[T, H * D]`, or runtime
51	/// recording fails.
52	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
53		matrix::rope(input, self.num_heads, self.head_dim, self.theta_base, 0)
54	}
55
56	/// Return the number of independently rotated heads.
57	pub const fn num_heads(&self) -> usize {
58		self.num_heads
59	}
60
61	/// Return the even dimension of each head.
62	pub const fn head_dim(&self) -> usize {
63		self.head_dim
64	}
65
66	/// Return the rotary frequency base.
67	pub const fn theta_base(&self) -> f32 {
68		self.theta_base
69	}
70}
71
72impl Module for Rope {
73	fn forward(&self, input: &Matrix) -> Result<Matrix> {
74		Rope::forward(self, input)
75	}
76
77	fn registry(&self) -> &ModuleRegistry {
78		&self.registry
79	}
80}