Skip to main content

oa/ml/nn/
unflatten.rs

1//! Unflatten (`nn.Unflatten`): expand one axis into several dimensions.
2
3use crate::{Error, Matrix, Result};
4
5use super::super::{Module, ModuleRegistry};
6
7/// Expand one input axis into the configured extent list.
8pub struct Unflatten {
9	dim: i32,
10	sizes: Vec<usize>,
11	registry: ModuleRegistry,
12}
13
14impl Unflatten {
15	/// Construct an unflatten expanding `dim` into `sizes`.
16	///
17	/// `sizes` may contain one `-1` entry, resolved from the axis extent at
18	/// call time (stored as `usize::MAX` internally).
19	///
20	/// # Errors
21	///
22	/// Returns an error when `sizes` is empty or holds more than one `-1`.
23	pub fn new(dim: i32, sizes: &[i64]) -> Result<Self> {
24		if sizes.is_empty() {
25			return Err(Error::invalid_argument(
26				"Unflatten requires a nonempty size list",
27			));
28		}
29		if sizes.iter().filter(|extent| **extent < -1).count() > 0
30			|| sizes.iter().filter(|extent| **extent == -1).count() > 1
31		{
32			return Err(Error::invalid_argument(
33				"Unflatten sizes must be nonnegative with at most one -1",
34			));
35		}
36		Ok(Self {
37			dim,
38			sizes: sizes
39				.iter()
40				.map(|extent| {
41					if *extent == -1 {
42						usize::MAX
43					} else {
44						*extent as usize
45					}
46				})
47				.collect(),
48			registry: ModuleRegistry::new(),
49		})
50	}
51
52	/// Return the configured axis.
53	pub const fn dim(&self) -> i32 {
54		self.dim
55	}
56
57	/// Expand `dim` of `input` into the configured extents.
58	///
59	/// # Errors
60	///
61	/// Returns an error when the axis is out of range, the extents do not
62	/// multiply to the axis extent, or the reshape fails.
63	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
64		let operation = "Unflatten";
65		let rank = input.shape().len();
66		let dim = if self.dim < 0 {
67			self.dim + rank as i32
68		} else {
69			self.dim
70		};
71		if dim < 0 || dim as usize >= rank {
72			return Err(Error::invalid_argument(format!(
73				"{operation} dim {} is outside rank {rank}",
74				self.dim
75			)));
76		}
77		let extent = input.shape()[dim as usize];
78		let mut sizes = self.sizes.clone();
79		if let Some(index) = sizes.iter().position(|extent| *extent == usize::MAX) {
80			let product: usize = sizes
81				.iter()
82				.filter(|extent| **extent != usize::MAX)
83				.product();
84			if product == 0 || !extent.is_multiple_of(product) {
85				return Err(Error::invalid_argument(format!(
86					"{operation} cannot infer the -1 extent for axis size {extent}"
87				)));
88			}
89			sizes[index] = extent / product;
90		} else if sizes.iter().product::<usize>() != extent {
91			return Err(Error::invalid_argument(format!(
92				"{operation} sizes must multiply to the axis extent {extent}"
93			)));
94		}
95		let mut shape = Vec::with_capacity(rank - 1 + sizes.len());
96		shape.extend_from_slice(&input.shape()[..dim as usize]);
97		shape.extend_from_slice(&sizes);
98		shape.extend_from_slice(&input.shape()[dim as usize + 1..]);
99		input.reshape(shape)
100	}
101}
102
103impl Module for Unflatten {
104	fn forward(&self, input: &Matrix) -> Result<Matrix> {
105		Unflatten::forward(self, input)
106	}
107
108	fn registry(&self) -> &ModuleRegistry {
109		&self.registry
110	}
111}