Skip to main content

oa/ml/nn/
channel_shuffle.rs

1//! Channel shuffle (`nn.ChannelShuffle`): interleave channel groups.
2
3use crate::{Error, Matrix, Result, matrix};
4
5use super::super::{Module, ModuleRegistry};
6
7/// Shuffle channels between `groups` equal-sized groups.
8///
9/// Input `[N, C, *]` is flattened to `[N, C, S]`, transposed to rows of
10/// channels, gathered by the interleave index `c * groups + g`, and mapped
11/// back — matching the donor channel order with a differentiable adjoint.
12pub struct ChannelShuffle {
13	groups: usize,
14	registry: ModuleRegistry,
15}
16
17impl ChannelShuffle {
18	/// Construct a channel shuffle with `groups` groups.
19	///
20	/// # Errors
21	///
22	/// Returns an error when `groups` is zero.
23	pub fn new(groups: usize) -> Result<Self> {
24		if groups == 0 {
25			return Err(Error::invalid_argument(
26				"channel shuffle requires at least one group",
27			));
28		}
29		Ok(Self {
30			groups,
31			registry: ModuleRegistry::new(),
32		})
33	}
34
35	/// Return the configured group count.
36	pub const fn groups(&self) -> usize {
37		self.groups
38	}
39
40	/// Interleave the channels of a `[N, C, *]` input.
41	///
42	/// # Errors
43	///
44	/// Returns an error for a rank-below-two input, a channel count not
45	/// divisible by `groups`, or a composed dispatch failure.
46	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
47		let operation = "ChannelShuffle";
48		let shape = input.shape();
49		if shape.len() < 2 {
50			return Err(Error::invalid_argument(format!(
51				"{operation} requires an input of rank at least two"
52			)));
53		}
54		let (batch, channels) = (shape[0], shape[1]);
55		if !channels.is_multiple_of(self.groups) {
56			return Err(Error::invalid_argument(format!(
57				"{operation} channel count {channels} is not divisible by {}",
58				self.groups
59			)));
60		}
61		let per_group = channels / self.groups;
62		let spatial: usize = shape[2..].iter().product();
63		let flattened = input.reshape([batch, channels, spatial])?;
64		let rows = matrix::transpose(
65			&matrix::transpose(&flattened, 1, 2)?.reshape([batch * spatial, channels])?,
66			0,
67			1,
68		)?;
69		let indices: Vec<i32> = (0..per_group)
70			.flat_map(|within| (0..self.groups).map(move |group| (group * per_group + within) as i32))
71			.collect();
72		let index = Matrix::new_from_slice_handle(input.runtime(), vec![channels], &indices)?;
73		let shuffled = matrix::transpose(&matrix::gather(&rows, &index)?, 0, 1)?
74			.reshape([batch, spatial, channels])?;
75		matrix::transpose(&shuffled, 1, 2)?.reshape(shape.to_vec())
76	}
77}
78
79impl Module for ChannelShuffle {
80	fn forward(&self, input: &Matrix) -> Result<Matrix> {
81		ChannelShuffle::forward(self, input)
82	}
83
84	fn registry(&self) -> &ModuleRegistry {
85		&self.registry
86	}
87}