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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
//! Error types for numr
use crate::dtype::DType;
use thiserror::Error;
/// Result type alias using numr's Error
pub type Result<T> = std::result::Result<T, Error>;
/// Opaque CUDA driver error.
///
/// Wraps the underlying CUDA driver error code and message without exposing
/// `cudarc` types in `numr`'s public error enum.
#[cfg(feature = "cuda")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CudaDriverError {
code: i32,
message: String,
}
#[cfg(feature = "cuda")]
impl CudaDriverError {
/// Raw CUDA driver `CUresult` integer code.
#[inline]
pub fn code(&self) -> i32 {
self.code
}
/// Human-readable driver error description.
#[inline]
pub fn message(&self) -> &str {
&self.message
}
/// Construct from a `cudarc` driver error without exposing `cudarc` in core `cuda` SemVer.
#[inline]
pub(crate) fn from_driver(err: cudarc::driver::DriverError) -> Self {
Self {
code: err.0 as i32,
message: err.to_string(),
}
}
}
#[cfg(feature = "cuda")]
impl std::fmt::Display for CudaDriverError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} (code {})", self.message, self.code)
}
}
#[cfg(feature = "cuda")]
impl std::error::Error for CudaDriverError {}
#[cfg(feature = "cuda-raw-interop")]
impl From<cudarc::driver::DriverError> for CudaDriverError {
fn from(err: cudarc::driver::DriverError) -> Self {
Self::from_driver(err)
}
}
#[cfg(feature = "cuda-raw-interop")]
impl From<cudarc::driver::DriverError> for Error {
fn from(err: cudarc::driver::DriverError) -> Self {
Self::Cuda(CudaDriverError::from_driver(err))
}
}
/// Errors that can occur in numr operations
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
/// Shape mismatch in an operation
#[error("Shape mismatch: expected {expected:?}, got {got:?}")]
ShapeMismatch {
/// Expected shape
expected: Vec<usize>,
/// Actual shape
got: Vec<usize>,
},
/// Shapes cannot be broadcast together
#[error("Cannot broadcast shapes {lhs:?} and {rhs:?}")]
BroadcastError {
/// Left-hand side shape
lhs: Vec<usize>,
/// Right-hand side shape
rhs: Vec<usize>,
},
/// Invalid dimension index
#[error("Invalid dimension {dim} for tensor with {ndim} dimensions")]
InvalidDimension {
/// The invalid dimension
dim: isize,
/// Number of dimensions
ndim: usize,
},
/// Unsupported dtype for an operation
#[error("Unsupported dtype {dtype:?} for operation '{op}'")]
UnsupportedDType {
/// The unsupported dtype
dtype: DType,
/// The operation name
op: &'static str,
},
/// DType mismatch between operands
#[error("DType mismatch: {lhs:?} vs {rhs:?}")]
DTypeMismatch {
/// Left-hand side dtype
lhs: DType,
/// Right-hand side dtype
rhs: DType,
},
/// Device mismatch between operands
#[error("Device mismatch: tensors must be on the same device")]
DeviceMismatch,
/// Out of memory
#[error("Out of memory: failed to allocate {size} bytes")]
OutOfMemory {
/// Requested size in bytes
size: usize,
},
/// Tensor allocation failed, with the shape/dtype/device context
///
/// Wraps the underlying allocation error (usually [`Error::OutOfMemory`])
/// so the message names what was being allocated, not only a byte count.
#[error("failed to allocate tensor {shape:?} {dtype} on {device}: {source}")]
AllocFailed {
/// Shape of the tensor that could not be allocated
shape: Vec<usize>,
/// Element type short name (e.g. "bf16", "q4_0")
dtype: String,
/// Device name (from [`Device::name`](crate::runtime::Device::name))
device: String,
/// The underlying allocation error
#[source]
source: Box<Error>,
},
/// Index out of bounds
#[error("Index {index} out of bounds for dimension of size {size}")]
IndexOutOfBounds {
/// The invalid index
index: usize,
/// Size of the dimension
size: usize,
},
/// Invalid argument provided to an operation
#[error("Invalid argument '{arg}': {reason}")]
InvalidArgument {
/// The argument name
arg: &'static str,
/// Reason for invalidity
reason: String,
},
/// Tensor is not contiguous when contiguous memory is required
#[error("Operation requires contiguous tensor")]
NotContiguous,
/// A host read names an element type whose width differs from the dtype.
///
/// A width mismatch sizes the copy wrong, so it would read past the buffer.
#[error(
"cannot read a {dtype} tensor ({dtype_bytes} bytes per element) as \
{elem_bytes}-byte elements: cast it to the target dtype first"
)]
HostReadTypeMismatch {
/// Short name of the stored dtype
dtype: &'static str,
/// Bytes per element of the stored dtype
dtype_bytes: usize,
/// Bytes per element of the requested host type
elem_bytes: usize,
},
/// Missing gradient in backward pass
#[error("Missing gradient for tensor")]
MissingGradient,
/// Backend-specific error
#[error("Backend error: {0}")]
Backend(String),
/// Backend limitation - operation valid but exceeds backend capabilities
#[error("{backend} limitation: {operation} - {reason}")]
BackendLimitation {
/// The backend that has the limitation
backend: &'static str,
/// The operation being attempted
operation: &'static str,
/// Description of the limitation
reason: String,
},
/// CUDA-specific error
#[cfg(feature = "cuda")]
#[error("CUDA error: {0}")]
Cuda(#[from] CudaDriverError),
/// Generic message error
#[error("{0}")]
Msg(String),
/// Generic internal error
#[error("Internal error: {0}")]
Internal(String),
/// Feature not yet implemented
#[error("Not implemented: {feature}")]
NotImplemented {
/// Description of the unimplemented feature
feature: &'static str,
},
/// Cargo feature required but not enabled
#[error(
"{dtype:?} requires the \"{feature}\" feature. Enable it with: cargo build --features {feature}"
)]
FeatureRequired {
/// The dtype that needs the feature
dtype: DType,
/// The cargo feature name to enable
feature: &'static str,
},
/// Allocator cannot reset while allocations are still live
#[error("Allocator busy: {active_allocations} allocations still active")]
AllocatorBusy {
/// Number of allocations that are still live
active_allocations: usize,
},
/// Allocator is frozen — no new allocations permitted
#[error("Allocator frozen: allocation rejected while frozen")]
AllocatorFrozen,
/// A CUDA graph capture arena ran out of room for an intermediate
/// allocation.
///
/// Carries the numbers a caller needs to size a retry: the request that
/// failed, the bytes the arena had already handed out, and the arena's
/// total capacity. Raised during `capture_graph_into_with_arena` when an
/// intermediate allocation inside the capture overruns the pre-sized
/// arena; the caller can recapture with a larger arena sized from
/// `used + requested`.
#[error(
"CUDA graph arena exhausted: requested {requested} bytes, {used} of {capacity} arena \
bytes used; recapture with a larger arena sized from these numbers"
)]
ArenaExhausted {
/// Bytes the failing allocation asked for
requested: usize,
/// Bytes already handed out by the arena before this request
used: usize,
/// Total arena capacity in bytes
capacity: usize,
},
}
impl Error {
/// The arena-exhaustion fields, if this error is
/// [`Error::ArenaExhausted`] or wraps one as an
/// [`Error::AllocFailed`] source.
///
/// A CUDA graph intermediate is normally allocated through
/// `Tensor::empty`/`Tensor::zeros`, which wraps every allocation failure
/// in `AllocFailed` for shape/dtype/device context. This walks that one
/// layer of wrapping so a caller can react to arena exhaustion without
/// matching on message text.
pub fn as_arena_exhausted(&self) -> Option<(usize, usize, usize)> {
match self {
Error::ArenaExhausted {
requested,
used,
capacity,
} => Some((*requested, *used, *capacity)),
Error::AllocFailed { source, .. } => source.as_arena_exhausted(),
_ => None,
}
}
}
impl Error {
/// Create a shape mismatch error
pub fn shape_mismatch(expected: &[usize], got: &[usize]) -> Self {
Self::ShapeMismatch {
expected: expected.to_vec(),
got: got.to_vec(),
}
}
/// Create a broadcast error
pub fn broadcast(lhs: &[usize], rhs: &[usize]) -> Self {
Self::BroadcastError {
lhs: lhs.to_vec(),
rhs: rhs.to_vec(),
}
}
/// Create an unsupported dtype error
pub fn unsupported_dtype(dtype: DType, op: &'static str) -> Self {
Self::UnsupportedDType { dtype, op }
}
/// Returns `true` when an allocation fails for lack of memory.
///
/// This holds for [`Error::OutOfMemory`], and for [`Error::AllocFailed`]
/// that wraps it. A caller can then name the next action, such as a smaller
/// input, without reading the message.
pub fn is_out_of_memory(&self) -> bool {
match self {
Self::OutOfMemory { .. } => true,
Self::AllocFailed { source, .. } => source.is_out_of_memory(),
_ => false,
}
}
/// Create a backend limitation error
pub fn backend_limitation(
backend: &'static str,
operation: &'static str,
reason: impl Into<String>,
) -> Self {
Self::BackendLimitation {
backend,
operation,
reason: reason.into(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn alloc_failed(source: Error) -> Error {
Error::AllocFailed {
shape: vec![2, 2],
dtype: "f32".to_string(),
device: "cpu".to_string(),
source: Box::new(source),
}
}
#[test]
fn out_of_memory_is_found_directly_and_through_alloc_failed() {
assert!(Error::OutOfMemory { size: 16 }.is_out_of_memory());
assert!(alloc_failed(Error::OutOfMemory { size: 16 }).is_out_of_memory());
}
#[test]
fn other_errors_are_not_out_of_memory() {
assert!(!Error::Backend("cuMemAllocAsync failed".to_string()).is_out_of_memory());
assert!(!alloc_failed(Error::Backend("capture".to_string())).is_out_of_memory());
assert!(!Error::NotContiguous.is_out_of_memory());
}
}