oa/ml/nn/
pixel_shuffle.rs1use crate::{Error, Matrix, Result, matrix};
4
5use super::super::{Module, ModuleRegistry};
6
7pub struct PixelShuffle {
17 upscale_factor: usize,
18 registry: ModuleRegistry,
19}
20
21impl PixelShuffle {
22 pub fn new(upscale_factor: usize) -> Result<Self> {
28 if upscale_factor < 2 {
29 return Err(Error::invalid_argument(
30 "pixel shuffle requires an upscale factor of at least 2",
31 ));
32 }
33 Ok(Self {
34 upscale_factor,
35 registry: ModuleRegistry::new(),
36 })
37 }
38
39 pub const fn upscale_factor(&self) -> usize {
41 self.upscale_factor
42 }
43
44 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
51 let r = self.upscale_factor;
52 let &[batch, packed, height, width] = input.shape() else {
53 return Err(Error::invalid_argument(format!(
54 "pixel shuffle requires [N, C*r^2, H, W]; found {:?}",
55 input.shape(),
56 )));
57 };
58 let squared = r
59 .checked_mul(r)
60 .ok_or_else(|| Error::invalid_argument("pixel shuffle factor overflows usize"))?;
61 if packed == 0 || !packed.is_multiple_of(squared) {
62 return Err(Error::invalid_argument(format!(
63 "pixel shuffle channels {packed} must be a nonzero multiple of r^2 = {squared}"
64 )));
65 }
66 let channels = packed / squared;
67 let out_height = height * r;
68 let out_width = width * r;
69 let mut indices = Vec::with_capacity(batch * channels * out_height * out_width);
71 for _ in 0..batch {
72 for c in 0..channels {
73 for h_out in 0..out_height {
74 for w_out in 0..out_width {
75 let channel = c * squared + (h_out % r) * r + (w_out % r);
76 indices.push((channel * height + h_out / r) as i32 * width as i32 + (w_out / r) as i32);
77 }
78 }
79 }
80 }
81 let flat = input.reshape([batch, packed * height * width])?;
82 let index_matrix = Matrix::new_from_slice_handle(
83 input.runtime(),
84 vec![batch, channels * out_height * out_width],
85 &indices,
86 )?;
87 let gathered = matrix::gather_last_dim(&flat, &index_matrix)?;
88 gathered.reshape([batch, channels, out_height, out_width])
89 }
90}
91
92impl Module for PixelShuffle {
93 fn forward(&self, input: &Matrix) -> Result<Matrix> {
94 PixelShuffle::forward(self, input)
95 }
96
97 fn registry(&self) -> &ModuleRegistry {
98 &self.registry
99 }
100}
101
102pub struct PixelUnshuffle {
110 downscale_factor: usize,
111 registry: ModuleRegistry,
112}
113
114impl PixelUnshuffle {
115 pub fn new(downscale_factor: usize) -> Result<Self> {
122 if downscale_factor < 2 {
123 return Err(Error::invalid_argument(
124 "pixel unshuffle requires a downscale factor of at least 2",
125 ));
126 }
127 Ok(Self {
128 downscale_factor,
129 registry: ModuleRegistry::new(),
130 })
131 }
132
133 pub const fn downscale_factor(&self) -> usize {
135 self.downscale_factor
136 }
137
138 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
145 let r = self.downscale_factor;
146 let &[batch, channels, height, width] = input.shape() else {
147 return Err(Error::invalid_argument(format!(
148 "pixel unshuffle requires [N, C, H, W]; found {:?}",
149 input.shape(),
150 )));
151 };
152 if height == 0 || !height.is_multiple_of(r) || width == 0 || !width.is_multiple_of(r) {
153 return Err(Error::invalid_argument(format!(
154 "pixel unshuffle spatial extents {height}x{width} must be nonzero multiples of r = {r}"
155 )));
156 }
157 let squared = r
158 .checked_mul(r)
159 .ok_or_else(|| Error::invalid_argument("pixel unshuffle factor overflows usize"))?;
160 let out_height = height / r;
161 let out_width = width / r;
162 let mut indices = Vec::with_capacity(batch * channels * squared * out_height * out_width);
164 for _ in 0..batch {
165 for c in 0..channels {
166 for i in 0..r {
167 for j in 0..r {
168 for h in 0..out_height {
169 for w in 0..out_width {
170 indices.push((c * height + h * r + i) as i32 * width as i32 + (w * r + j) as i32);
171 }
172 }
173 }
174 }
175 }
176 }
177 let flat = input.reshape([batch, channels * height * width])?;
178 let index_matrix = Matrix::new_from_slice_handle(
179 input.runtime(),
180 vec![batch, channels * squared * out_height * out_width],
181 &indices,
182 )?;
183 let gathered = matrix::gather_last_dim(&flat, &index_matrix)?;
184 gathered.reshape([batch, channels * squared, out_height, out_width])
185 }
186}
187
188impl Module for PixelUnshuffle {
189 fn forward(&self, input: &Matrix) -> Result<Matrix> {
190 PixelUnshuffle::forward(self, input)
191 }
192
193 fn registry(&self) -> &ModuleRegistry {
194 &self.registry
195 }
196}