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
//! Cumulative operation helpers for CPU tensors
use super::super::kernels;
use super::super::{CpuClient, CpuRuntime};
use crate::dispatch_dtype;
use crate::error::{Error, Result};
use crate::ops::reduce_output_shape;
use crate::runtime::ensure_contiguous;
use crate::tensor::Tensor;
/// Normalize a dimension index, allowing negative indexing
#[inline]
fn normalize_dim(ndim: usize, dim: isize) -> Option<usize> {
if dim >= 0 {
let d = dim as usize;
if d < ndim { Some(d) } else { None }
} else {
let d = dim + ndim as isize;
if d >= 0 { Some(d as usize) } else { None }
}
}
/// Cumulative sum along a dimension
pub fn cumsum_impl(
client: &CpuClient,
a: &Tensor<CpuRuntime>,
dim: isize,
) -> Result<Tensor<CpuRuntime>> {
let dtype = a.dtype();
let shape = a.shape();
let ndim = shape.len();
let dim_idx = normalize_dim(ndim, dim).ok_or(Error::InvalidDimension { dim, ndim })?;
// Handle empty tensor
if a.numel() == 0 {
return Tensor::<CpuRuntime>::empty(shape, dtype, &client.device);
}
// Make contiguous for simplicity
let a_contig = ensure_contiguous(a)?;
// Output has same shape as input
let out = Tensor::<CpuRuntime>::empty(shape, dtype, &client.device)?;
// Compute sizes for the scan. Unclamped: an empty slice already products to 1,
// so `.max(1)` here would only fabricate a row for a genuinely zero dimension.
let scan_size = shape[dim_idx];
let outer_size: usize = shape[..dim_idx].iter().product();
let inner_size: usize = shape[dim_idx + 1..].iter().product();
let a_ptr = a_contig.ptr();
let out_ptr = out.ptr();
dispatch_dtype!(dtype, T => {
unsafe {
if inner_size == 1 {
// Fast path: scan dimension is last (or tensor is 1D)
kernels::cumsum_kernel(
a_ptr as *const T,
out_ptr as *mut T,
scan_size,
outer_size,
);
} else {
// General path: strided access
kernels::cumsum_strided_kernel(
a_ptr as *const T,
out_ptr as *mut T,
scan_size,
outer_size,
inner_size,
);
}
}
}, "cumsum");
Ok(out)
}
/// Cumulative product along a dimension
pub fn cumprod_impl(
client: &CpuClient,
a: &Tensor<CpuRuntime>,
dim: isize,
) -> Result<Tensor<CpuRuntime>> {
let dtype = a.dtype();
let shape = a.shape();
let ndim = shape.len();
let dim_idx = normalize_dim(ndim, dim).ok_or(Error::InvalidDimension { dim, ndim })?;
// Handle empty tensor
if a.numel() == 0 {
return Tensor::<CpuRuntime>::empty(shape, dtype, &client.device);
}
// Make contiguous for simplicity
let a_contig = ensure_contiguous(a)?;
// Output has same shape as input
let out = Tensor::<CpuRuntime>::empty(shape, dtype, &client.device)?;
// Compute sizes for the scan. Unclamped: an empty slice already products to 1,
// so `.max(1)` here would only fabricate a row for a genuinely zero dimension.
let scan_size = shape[dim_idx];
let outer_size: usize = shape[..dim_idx].iter().product();
let inner_size: usize = shape[dim_idx + 1..].iter().product();
let a_ptr = a_contig.ptr();
let out_ptr = out.ptr();
dispatch_dtype!(dtype, T => {
unsafe {
if inner_size == 1 {
// Fast path: scan dimension is last (or tensor is 1D)
kernels::cumprod_kernel(
a_ptr as *const T,
out_ptr as *mut T,
scan_size,
outer_size,
);
} else {
// General path: strided access
kernels::cumprod_strided_kernel(
a_ptr as *const T,
out_ptr as *mut T,
scan_size,
outer_size,
inner_size,
);
}
}
}, "cumprod");
Ok(out)
}
/// Log-sum-exp along specified dimensions (numerically stable)
///
/// Only supports floating-point dtypes (F32, F64, F16, BF16).
pub fn logsumexp_impl(
client: &CpuClient,
a: &Tensor<CpuRuntime>,
dims: &[usize],
keepdim: bool,
) -> Result<Tensor<CpuRuntime>> {
let dtype = a.dtype();
let shape = a.shape();
let ndim = shape.len();
// Logsumexp only makes sense for floating-point types
if !dtype.is_float() {
return Err(Error::UnsupportedDType {
dtype,
op: "logsumexp",
});
}
// Validate dimensions
for &d in dims {
if d >= ndim {
return Err(Error::InvalidDimension {
dim: d as isize,
ndim,
});
}
}
// For single last-dimension reduction on contiguous tensor, use fast path
if dims.len() == 1 && dims[0] == ndim - 1 && a.is_contiguous() {
let reduce_size = shape[ndim - 1];
// Unclamped: a zero leading dim must stay 0, or the kernel walks past the
// allocation. An empty slice already products to 1 for the rank-1 case.
let outer_size: usize = shape[..ndim - 1].iter().product();
let out_shape = reduce_output_shape(shape, dims, keepdim);
let out = Tensor::<CpuRuntime>::empty(&out_shape, dtype, &client.device)?;
let a_ptr = a.ptr();
let out_ptr = out.ptr();
dispatch_dtype!(dtype, T => {
unsafe {
kernels::logsumexp_kernel(
a_ptr as *const T,
out_ptr as *mut T,
reduce_size,
outer_size,
);
}
}, "logsumexp");
return Ok(out);
}
// For empty dims, return copy
if dims.is_empty() {
return Ok(a.clone());
}
// General case: reduce one dimension at a time
let a_contig = ensure_contiguous(a)?;
let mut sorted_dims: Vec<usize> = dims.to_vec();
sorted_dims.sort_unstable();
sorted_dims.reverse();
let mut current = a_contig;
for &dim in &sorted_dims {
current = logsumexp_single_dim(client, ¤t, dim, keepdim)?;
}
Ok(current)
}
/// Log-sum-exp along a single dimension
fn logsumexp_single_dim(
client: &CpuClient,
a: &Tensor<CpuRuntime>,
dim: usize,
keepdim: bool,
) -> Result<Tensor<CpuRuntime>> {
let dtype = a.dtype();
let shape = a.shape();
let ndim = shape.len();
if dim >= ndim {
return Err(Error::InvalidDimension {
dim: dim as isize,
ndim,
});
}
// Unclamped: an empty slice already products to 1, so `.max(1)` would only
// fabricate a row for a genuinely zero dimension and index out of bounds.
let reduce_size = shape[dim];
let outer_size: usize = shape[..dim].iter().product();
let inner_size: usize = shape[dim + 1..].iter().product();
// Output shape: remove the reduced dimension (or keep as 1)
let out_shape: Vec<usize> = if keepdim {
shape
.iter()
.enumerate()
.map(|(i, &s)| if i == dim { 1 } else { s })
.collect()
} else {
shape
.iter()
.enumerate()
.filter_map(|(i, &s)| if i != dim { Some(s) } else { None })
.collect()
};
let out = Tensor::<CpuRuntime>::empty(&out_shape, dtype, &client.device)?;
let a_ptr = a.ptr();
let out_ptr = out.ptr();
dispatch_dtype!(dtype, T => {
unsafe {
if inner_size == 1 {
// Fast path: reduce dimension is last
kernels::logsumexp_kernel(
a_ptr as *const T,
out_ptr as *mut T,
reduce_size,
outer_size,
);
} else {
// General path: strided access
kernels::logsumexp_strided_kernel(
a_ptr as *const T,
out_ptr as *mut T,
reduce_size,
outer_size,
inner_size,
inner_size, // in_stride
inner_size, // out_stride
);
}
}
}, "logsumexp");
Ok(out)
}