oa/ml/nn/
channel_shuffle.rs1use crate::{Error, Matrix, Result, matrix};
4
5use super::super::{Module, ModuleRegistry};
6
7pub struct ChannelShuffle {
13 groups: usize,
14 registry: ModuleRegistry,
15}
16
17impl ChannelShuffle {
18 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 pub const fn groups(&self) -> usize {
37 self.groups
38 }
39
40 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}