1use crate::{Error, Matrix, Result, matrix};
5
6use super::super::{Module, ModuleRegistry, matrix as ml_matrix};
7
8pub struct Glu {
10 dim: i32,
11 registry: ModuleRegistry,
12}
13
14impl Glu {
15 pub const fn new() -> Self {
17 Self::new_with_dim(-1)
18 }
19
20 pub const fn new_with_dim(dim: i32) -> Self {
22 Self {
23 dim,
24 registry: ModuleRegistry::new(),
25 }
26 }
27
28 pub const fn dim(&self) -> i32 {
30 self.dim
31 }
32
33 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
40 let rank = input.shape().len();
41 let dim = if self.dim < 0 {
42 self.dim + rank as i32
43 } else {
44 self.dim
45 };
46 if dim < 0 || dim as usize >= rank {
47 return Err(Error::invalid_argument(format!(
48 "Glu dim {} is outside rank {rank}",
49 self.dim
50 )));
51 }
52 let extent = input.shape()[dim as usize];
53 if !extent.is_multiple_of(2) {
54 return Err(Error::invalid_argument(format!(
55 "Glu requires an even extent on the split axis; found {extent}"
56 )));
57 }
58 let half = extent as i64 / 2;
59 let gate = matrix::slice(input, dim, 0, half)?;
60 let value = matrix::slice(input, dim, half, extent as i64)?;
61 matrix::mul(&gate, &ml_matrix::sigmoid(&value)?)
62 }
63}
64
65impl Default for Glu {
66 fn default() -> Self {
67 Self::new()
68 }
69}
70
71impl Module for Glu {
72 fn forward(&self, input: &Matrix) -> Result<Matrix> {
73 Glu::forward(self, input)
74 }
75
76 fn registry(&self) -> &ModuleRegistry {
77 &self.registry
78 }
79}