1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//! Convolution operations for neural network layers.
//!
//! This module defines the `ConvOps` trait for 1D and 2D convolution operations
//! commonly used in neural networks for feature extraction.
use crate::error::{Error, Result};
use crate::runtime::Runtime;
use crate::tensor::Tensor;
/// Padding mode for convolution operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PaddingMode {
/// No padding - output is smaller than input.
#[default]
Valid,
/// Padding to make output same size as input (when stride=1).
Same,
/// Custom padding specified as explicit values.
/// For conv1d: (left, right)
/// For conv2d: (top, bottom, left, right)
Custom(usize, usize, usize, usize),
}
impl PaddingMode {
/// Creates padding for a specific amount on all sides.
pub fn uniform(padding: usize) -> Self {
PaddingMode::Custom(padding, padding, padding, padding)
}
/// Creates asymmetric padding for conv1d.
pub fn conv1d(left: usize, right: usize) -> Self {
PaddingMode::Custom(left, right, 0, 0)
}
/// Creates asymmetric padding for conv2d.
pub fn conv2d(top: usize, bottom: usize, left: usize, right: usize) -> Self {
PaddingMode::Custom(top, bottom, left, right)
}
/// Returns the name of the padding mode for error messages.
pub fn name(&self) -> &'static str {
match self {
PaddingMode::Valid => "valid",
PaddingMode::Same => "same",
PaddingMode::Custom(..) => "custom",
}
}
}
/// Convolution operations.
///
/// Provides 1D and 2D convolution operations commonly used in neural networks
/// for tasks like image classification, object detection, and signal processing.
///
/// # Memory Layout
///
/// All tensors use the following memory layouts:
/// - **Input 1D**: `(N, C_in, L)` - batch, input channels, length
/// - **Input 2D**: `(N, C_in, H, W)` - batch, input channels, height, width
/// - **Weight 1D**: `(C_out, C_in/groups, K)` - output channels, input channels per group, kernel size
/// - **Weight 2D**: `(C_out, C_in/groups, K_h, K_w)` - output channels, input channels per group, kernel height, kernel width
/// - **Bias**: `(C_out,)` - one bias per output channel
/// - **Output 1D**: `(N, C_out, L_out)` - batch, output channels, output length
/// - **Output 2D**: `(N, C_out, H_out, W_out)` - batch, output channels, output height, output width
///
/// # Backend Support
///
/// ## Data Types
///
/// - **CPU**: Supports F32, F64, F16, BF16 (with `f16` feature)
/// - **CUDA**: Supports F32, F64, F16, BF16 (with `f16` feature)
/// - **WebGPU**: Currently supports F32 only
///
/// All backends require floating-point dtypes. Integer dtypes are not supported.
pub trait ConvOps<R: Runtime> {
/// Applies a 1D convolution over an input signal.
///
/// Given input of shape `(N, C_in, L)` and weight of shape `(C_out, C_in/groups, K)`,
/// produces output of shape `(N, C_out, L_out)`.
///
/// # Arguments
///
/// * `input` - Input tensor of shape `(N, C_in, L)`
/// * `weight` - Convolution kernel of shape `(C_out, C_in/groups, K)`
/// * `bias` - Optional bias of shape `(C_out,)`
/// * `stride` - Stride of the convolution (default: 1)
/// * `padding` - Padding mode
/// * `dilation` - Spacing between kernel elements (default: 1)
/// * `groups` - Number of blocked connections from input to output channels (default: 1)
///
/// # Returns
///
/// Output tensor of shape `(N, C_out, L_out)` where:
/// `L_out = floor((L + pad_left + pad_right - dilation * (K - 1) - 1) / stride + 1)`
///
/// # Errors
///
/// Returns `Error::InvalidArgument` if:
/// - Input is not a 3D tensor
/// - Weight is not a 3D tensor
/// - Bias is not a 1D tensor with length C_out
/// - C_in is not divisible by groups
/// - C_out is not divisible by groups
/// - stride, dilation, or groups is 0
///
/// Returns `Error::UnsupportedDType` if dtype is not floating point.
///
/// # Examples
///
/// ```
/// # use numr::prelude::*;
/// # use numr::dtype::DType;
/// # use numr::ops::PaddingMode;
/// # let device = CpuDevice::new();
/// # let client = CpuRuntime::default_client(&device);
/// use numr::ops::ConvOps;
///
/// // Input: batch=2, channels=3, length=10
/// let input = client.randn(&[2, 3, 10], DType::F32)?;
/// // Kernel: 16 output channels, 3 input channels, kernel size 3
/// let weight = client.randn(&[16, 3, 3], DType::F32)?;
/// let bias = client.fill(&[16], 0.0, DType::F32)?;
///
/// let output = client.conv1d(&input, &weight, Some(&bias), 1, PaddingMode::Same, 1, 1)?;
/// // output has shape (2, 16, 10)
/// # Ok::<(), numr::error::Error>(())
/// ```
fn conv1d(
&self,
input: &Tensor<R>,
weight: &Tensor<R>,
bias: Option<&Tensor<R>>,
stride: usize,
padding: PaddingMode,
dilation: usize,
groups: usize,
) -> Result<Tensor<R>> {
let _ = (input, weight, bias, stride, padding, dilation, groups);
Err(Error::NotImplemented {
feature: "ConvOps::conv1d",
})
}
/// Applies a 2D convolution over an input image.
///
/// Given input of shape (N, C_in, H, W) and weight of shape (C_out, C_in/groups, K_h, K_w),
/// produces output of shape (N, C_out, H_out, W_out).
///
/// # Arguments
///
/// * `input` - Input tensor of shape (N, C_in, H, W)
/// * `weight` - Convolution kernel of shape (C_out, C_in/groups, K_h, K_w)
/// * `bias` - Optional bias of shape (C_out,)
/// * `stride` - Stride of the convolution as (stride_h, stride_w)
/// * `padding` - Padding mode
/// * `dilation` - Spacing between kernel elements as (dilation_h, dilation_w)
/// * `groups` - Number of blocked connections from input to output channels
///
/// # Returns
///
/// Output tensor of shape (N, C_out, H_out, W_out) where:
/// H_out = floor((H + pad_top + pad_bottom - dilation_h * (K_h - 1) - 1) / stride_h + 1)
/// W_out = floor((W + pad_left + pad_right - dilation_w * (K_w - 1) - 1) / stride_w + 1)
///
/// # Errors
///
/// Returns `Error::InvalidArgument` if:
/// - Input is not a 4D tensor
/// - Weight is not a 4D tensor
/// - Bias is not a 1D tensor with length C_out
/// - C_in is not divisible by groups
/// - C_out is not divisible by groups
/// - Any stride, dilation, or groups value is 0
///
/// Returns `Error::UnsupportedDType` if dtype is not floating point.
///
/// # Examples
///
/// ```
/// # use numr::prelude::*;
/// # use numr::dtype::DType;
/// # use numr::ops::PaddingMode;
/// # let device = CpuDevice::new();
/// # let client = CpuRuntime::default_client(&device);
/// use numr::ops::ConvOps;
///
/// // Input: batch=2, channels=3, height=32, width=32
/// let input = client.randn(&[2, 3, 32, 32], DType::F32)?;
/// // Kernel: 64 output channels, 3 input channels, 3x3 kernel
/// let weight = client.randn(&[64, 3, 3, 3], DType::F32)?;
/// let bias = client.fill(&[64], 0.0, DType::F32)?;
///
/// let output = client.conv2d(&input, &weight, Some(&bias), (1, 1), PaddingMode::Same, (1, 1), 1)?;
/// // output has shape (2, 64, 32, 32)
/// # Ok::<(), numr::error::Error>(())
/// ```
fn conv2d(
&self,
input: &Tensor<R>,
weight: &Tensor<R>,
bias: Option<&Tensor<R>>,
stride: (usize, usize),
padding: PaddingMode,
dilation: (usize, usize),
groups: usize,
) -> Result<Tensor<R>> {
let _ = (input, weight, bias, stride, padding, dilation, groups);
Err(Error::NotImplemented {
feature: "ConvOps::conv2d",
})
}
/// Applies a depthwise separable 2D convolution.
///
/// In depthwise convolution, each input channel is convolved separately with
/// its own set of filters. This is equivalent to grouped convolution where
/// groups = C_in = C_out.
///
/// # Arguments
///
/// * `input` - Input tensor of shape (N, C, H, W)
/// * `weight` - Depthwise kernel of shape (C, 1, K_h, K_w)
/// * `bias` - Optional bias of shape (C,)
/// * `stride` - Stride of the convolution as (stride_h, stride_w)
/// * `padding` - Padding mode
/// * `dilation` - Spacing between kernel elements as (dilation_h, dilation_w)
///
/// # Returns
///
/// Output tensor of shape (N, C, H_out, W_out).
///
/// # Errors
///
/// Returns `Error::InvalidArgument` if:
/// - Input is not a 4D tensor
/// - Weight is not a 4D tensor with `shape[1]` = 1
/// - Weight channels don't match input channels
/// - Bias is not a 1D tensor with length C
/// - Any stride or dilation value is 0
///
/// Returns `Error::UnsupportedDType` if dtype is not floating point.
///
/// # Examples
///
/// ```
/// # use numr::prelude::*;
/// # use numr::dtype::DType;
/// # use numr::ops::PaddingMode;
/// # let device = CpuDevice::new();
/// # let client = CpuRuntime::default_client(&device);
/// use numr::ops::ConvOps;
///
/// // Input: batch=2, channels=32, height=28, width=28
/// let input = client.randn(&[2, 32, 28, 28], DType::F32)?;
/// // Depthwise kernel: 32 channels, 1 input per group, 3x3 kernel
/// let weight = client.randn(&[32, 1, 3, 3], DType::F32)?;
///
/// let output = client.depthwise_conv2d(&input, &weight, None, (1, 1), PaddingMode::Same, (1, 1))?;
/// // output has shape (2, 32, 28, 28)
/// # Ok::<(), numr::error::Error>(())
/// ```
fn depthwise_conv2d(
&self,
input: &Tensor<R>,
weight: &Tensor<R>,
bias: Option<&Tensor<R>>,
stride: (usize, usize),
padding: PaddingMode,
dilation: (usize, usize),
) -> Result<Tensor<R>> {
let _ = (input, weight, bias, stride, padding, dilation);
Err(Error::NotImplemented {
feature: "ConvOps::depthwise_conv2d",
})
}
/// Applies a 1D transposed convolution (also called "deconvolution") over an input signal.
///
/// Given input of shape `(N, C_in, L_in)` and weight of shape `(C_in, C_out/groups, K)`,
/// produces output of shape `(N, C_out, L_out)` where:
/// `L_out = (L_in - 1) * stride - pad_left - pad_right + dilation * (K - 1) + output_padding + 1`
///
/// Note: the weight layout differs from `conv1d`: input channels come first, then output
/// channels per group — matching PyTorch's `ConvTranspose1d` convention.
///
/// Used by StyleTTS2-family TTS decoders (Kokoro, etc.) and by generative models
/// that upsample a latent sequence to a waveform / spectrogram.
///
/// # Arguments
///
/// * `input` - Input tensor of shape `(N, C_in, L_in)`
/// * `weight` - Kernel of shape `(C_in, C_out/groups, K)`
/// * `bias` - Optional bias of shape `(C_out,)`
/// * `stride` - Upsampling stride
/// * `padding` - Padding mode. Note: for transposed conv, this *reduces* output length.
/// * `output_padding` - Extra padding added to one side of the output to resolve the
/// ambiguity when `stride > 1`. Must be `< stride`.
/// * `dilation` - Spacing between kernel elements
/// * `groups` - Number of blocked connections from input to output channels
///
/// # Errors
///
/// Returns `Error::NotImplemented` until a backend provides an implementation.
fn conv_transpose1d(
&self,
input: &Tensor<R>,
weight: &Tensor<R>,
bias: Option<&Tensor<R>>,
stride: usize,
padding: PaddingMode,
output_padding: usize,
dilation: usize,
groups: usize,
) -> Result<Tensor<R>> {
let _ = (
input,
weight,
bias,
stride,
padding,
output_padding,
dilation,
groups,
);
Err(Error::NotImplemented {
feature: "ConvOps::conv_transpose1d",
})
}
}