Skip to main content

oa/ml/nn/
pixel_shuffle.rs

1//! Pixel-shuffle (`nn.PixelShuffle`) over a last-axis gather remap.
2
3use crate::{Error, Matrix, Result, matrix};
4
5use super::super::{Module, ModuleRegistry};
6
7/// Rearrange `[N, C*r^2, H, W]` to `[N, C, H*r, W*r]`.
8///
9/// The composed contract flattens each sample and remaps elements with a
10/// single [`matrix::gather_last_dim`] using a host-built I32 index plane —
11/// the same channel ordering as `nn.PixelShuffle`
12/// (`out[.., c, h*r+i, w*r+j] = in[.., c*r^2 + i*r + j, h, w]`). The index
13/// plane is rebuilt per forward, matching the explicit host-observation
14/// boundary used elsewhere for data-shaping metadata. Parameterless;
15/// gradients flow through the gather adjoint.
16pub struct PixelShuffle {
17	upscale_factor: usize,
18	registry: ModuleRegistry,
19}
20
21impl PixelShuffle {
22	/// Construct with the integer `upscale_factor` (`r` in `nn.PixelShuffle`).
23	///
24	/// # Errors
25	///
26	/// Returns an error when `upscale_factor` is less than two.
27	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	/// Return the configured upscale factor.
40	pub const fn upscale_factor(&self) -> usize {
41		self.upscale_factor
42	}
43
44	/// Rearrange `[N, C*r^2, H, W]` into `[N, C, H*r, W*r]`.
45	///
46	/// # Errors
47	///
48	/// Returns an error unless `input` is rank four F32 with a channel count
49	/// divisible by `r^2`, or the gather dispatch fails.
50	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		// out[.., c, h_out, w_out] = in[.., c*r^2 + (h_out%r)*r + (w_out%r), h_out/r, w_out/r]
70		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
102/// Rearrange `[N, C, H, W]` to `[N, C*r^2, H/r, W/r]` — the exact inverse of
103/// [`PixelShuffle`].
104///
105/// Uses the same composed contract as `PixelShuffle`: flatten each sample and
106/// remap elements with one [`matrix::gather_last_dim`] over a host-built I32
107/// index plane (`out[.., c*r^2 + i*r + j, h, w] = in[.., c, h*r + i, w*r +
108/// j]`). Parameterless; gradients flow through the gather adjoint.
109pub struct PixelUnshuffle {
110	downscale_factor: usize,
111	registry: ModuleRegistry,
112}
113
114impl PixelUnshuffle {
115	/// Construct with the integer `downscale_factor` (`r` in
116	/// `nn.PixelUnshuffle`).
117	///
118	/// # Errors
119	///
120	/// Returns an error when `downscale_factor` is less than two.
121	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	/// Return the configured downscale factor.
134	pub const fn downscale_factor(&self) -> usize {
135		self.downscale_factor
136	}
137
138	/// Rearrange `[N, C, H, W]` into `[N, C*r^2, H/r, W/r]`.
139	///
140	/// # Errors
141	///
142	/// Returns an error unless `input` is rank four F32 with spatial extents
143	/// divisible by `r`, or the gather dispatch fails.
144	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		// out[.., c*r^2 + i*r + j, h, w] = in[.., c, h*r + i, w*r + j]
163		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}