scivex-nn 0.1.1

Scivex — Neural networks, autograd, layers, optimizers
Documentation
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! ONNX intermediate representation types.
//!
//! These Rust types mirror the ONNX protobuf schema at a structural level but
//! are decoded from raw bytes by our own minimal protobuf parser.

/// ONNX tensor element data types (matches `onnx::TensorProto::DataType` enum values).
///
/// # Examples
///
/// ```
/// # use scivex_nn::onnx::ir::OnnxDataType;
/// let dt = OnnxDataType::Float;
/// assert_eq!(dt as i32, 1);
/// let dt2 = OnnxDataType::Double;
/// assert_eq!(dt2 as i32, 11);
/// ```
#[cfg_attr(
    feature = "serde-support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OnnxDataType {
    /// 32-bit float.
    Float = 1,
    /// 8-bit unsigned integer.
    Uint8 = 2,
    /// 8-bit signed integer.
    Int8 = 3,
    /// 16-bit unsigned integer.
    Uint16 = 4,
    /// 16-bit signed integer.
    Int16 = 5,
    /// 32-bit signed integer.
    Int32 = 6,
    /// 64-bit signed integer.
    Int64 = 7,
    /// UTF-8 string.
    String = 8,
    /// Boolean.
    Bool = 9,
    /// 64-bit float.
    Double = 11,
    /// 32-bit unsigned integer.
    Uint32 = 12,
    /// 64-bit unsigned integer.
    Uint64 = 13,
}

impl OnnxDataType {
    /// Decode from the protobuf enum integer.
    pub(crate) fn from_i32(v: i32) -> Option<Self> {
        match v {
            1 => Some(Self::Float),
            2 => Some(Self::Uint8),
            3 => Some(Self::Int8),
            4 => Some(Self::Uint16),
            5 => Some(Self::Int16),
            6 => Some(Self::Int32),
            7 => Some(Self::Int64),
            8 => Some(Self::String),
            9 => Some(Self::Bool),
            11 => Some(Self::Double),
            12 => Some(Self::Uint32),
            13 => Some(Self::Uint64),
            _ => None,
        }
    }
}

/// An ONNX tensor (weight / initializer / constant).
#[cfg_attr(
    feature = "serde-support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Debug, Clone)]
pub struct OnnxTensor {
    /// Optional tensor name.
    pub name: String,
    /// Element data type.
    pub data_type: OnnxDataType,
    /// Dimensions.
    pub dims: Vec<i64>,
    /// Raw float data (populated for float tensors).
    pub float_data: Vec<f32>,
    /// Raw double data.
    pub double_data: Vec<f64>,
    /// Raw int32 data.
    pub int32_data: Vec<i32>,
    /// Raw int64 data.
    pub int64_data: Vec<i64>,
    /// Raw bytes (used when data is stored in the `raw_data` field).
    pub raw_data: Vec<u8>,
}

impl OnnxTensor {
    /// Create a new empty tensor.
    ///
    /// # Examples
    ///
    /// ```
    /// # use scivex_nn::onnx::ir::{OnnxTensor, OnnxDataType};
    /// let mut t = OnnxTensor::new();
    /// t.name = "weight".to_string();
    /// t.data_type = OnnxDataType::Float;
    /// t.dims = vec![2, 3];
    /// t.float_data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
    /// assert_eq!(t.dims_usize(), vec![2, 3]);
    /// ```
    pub fn new() -> Self {
        Self {
            name: String::new(),
            data_type: OnnxDataType::Float,
            dims: Vec::new(),
            float_data: Vec::new(),
            double_data: Vec::new(),
            int32_data: Vec::new(),
            int64_data: Vec::new(),
            raw_data: Vec::new(),
        }
    }

    /// Return float data, decoding from `raw_data` if `float_data` is empty.
    pub fn to_f32_vec(&self) -> Vec<f32> {
        if !self.float_data.is_empty() {
            return self.float_data.clone();
        }
        if !self.raw_data.is_empty() {
            match self.data_type {
                OnnxDataType::Float => {
                    return self
                        .raw_data
                        .chunks_exact(4)
                        .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
                        .collect();
                }
                OnnxDataType::Double => {
                    return self
                        .raw_data
                        .chunks_exact(8)
                        .map(|c| {
                            #[allow(clippy::cast_possible_truncation)]
                            let v = f64::from_le_bytes([
                                c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7],
                            ]) as f32;
                            v
                        })
                        .collect();
                }
                _ => {}
            }
        }
        if !self.double_data.is_empty() {
            #[allow(clippy::cast_possible_truncation)]
            return self.double_data.iter().map(|&v| v as f32).collect();
        }
        if !self.int64_data.is_empty() {
            #[allow(clippy::cast_possible_truncation)]
            return self.int64_data.iter().map(|&v| v as f32).collect();
        }
        if !self.int32_data.is_empty() {
            #[allow(clippy::cast_precision_loss)]
            return self.int32_data.iter().map(|&v| v as f32).collect();
        }
        Vec::new()
    }

    /// Return the dimensions as `Vec<usize>`.
    pub fn dims_usize(&self) -> Vec<usize> {
        #[allow(clippy::cast_sign_loss)]
        self.dims.iter().map(|&d| d as usize).collect()
    }
}

impl Default for OnnxTensor {
    fn default() -> Self {
        Self::new()
    }
}

/// Attribute value kinds in an ONNX node.
///
/// # Examples
///
/// ```
/// # use scivex_nn::onnx::ir::OnnxAttributeValue;
/// let v = OnnxAttributeValue::Int(3);
/// if let OnnxAttributeValue::Int(n) = v {
///     assert_eq!(n, 3);
/// }
/// ```
#[cfg_attr(
    feature = "serde-support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Debug, Clone)]
pub enum OnnxAttributeValue {
    /// A single float.
    Float(f32),
    /// A single integer.
    Int(i64),
    /// A UTF-8 string.
    String(String),
    /// A tensor value.
    Tensor(OnnxTensor),
    /// A sub-graph.
    Graph(OnnxGraph),
    /// A list of floats.
    Floats(Vec<f32>),
    /// A list of integers.
    Ints(Vec<i64>),
    /// A list of strings.
    Strings(Vec<String>),
}

/// An attribute on an ONNX node.
///
/// # Examples
///
/// ```
/// # use scivex_nn::onnx::ir::{OnnxAttribute, OnnxAttributeValue};
/// let attr = OnnxAttribute {
///     name: "kernel_shape".to_string(),
///     value: OnnxAttributeValue::Ints(vec![3, 3]),
/// };
/// assert_eq!(attr.name, "kernel_shape");
/// ```
#[cfg_attr(
    feature = "serde-support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Debug, Clone)]
pub struct OnnxAttribute {
    /// Attribute name.
    pub name: String,
    /// Attribute value.
    pub value: OnnxAttributeValue,
}

/// A single node (operator) in the ONNX computation graph.
///
/// # Examples
///
/// ```
/// # use scivex_nn::onnx::ir::OnnxNode;
/// let node = OnnxNode::new("Relu");
/// assert_eq!(node.op_type, "Relu");
/// assert!(node.inputs.is_empty());
/// ```
#[cfg_attr(
    feature = "serde-support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Debug, Clone)]
pub struct OnnxNode {
    /// Operator type (e.g. "Add", "MatMul", "Relu").
    pub op_type: String,
    /// Input tensor names.
    pub inputs: Vec<String>,
    /// Output tensor names.
    pub outputs: Vec<String>,
    /// Node name (optional, for debugging).
    pub name: String,
    /// Attributes for the operator.
    pub attributes: Vec<OnnxAttribute>,
}

impl OnnxNode {
    /// Create a new node.
    ///
    /// # Examples
    ///
    /// ```
    /// # use scivex_nn::onnx::ir::OnnxNode;
    /// let mut node = OnnxNode::new("MatMul");
    /// node.inputs = vec!["X".to_string(), "W".to_string()];
    /// node.outputs = vec!["Y".to_string()];
    /// assert_eq!(node.op_type, "MatMul");
    /// assert_eq!(node.inputs.len(), 2);
    /// ```
    pub fn new(op_type: &str) -> Self {
        Self {
            op_type: op_type.to_owned(),
            inputs: Vec::new(),
            outputs: Vec::new(),
            name: String::new(),
            attributes: Vec::new(),
        }
    }

    /// Look up an attribute by name.
    pub fn get_attr(&self, name: &str) -> Option<&OnnxAttributeValue> {
        self.attributes
            .iter()
            .find(|a| a.name == name)
            .map(|a| &a.value)
    }

    /// Get an integer attribute, returning a default if missing.
    pub fn get_int_attr(&self, name: &str, default: i64) -> i64 {
        match self.get_attr(name) {
            Some(OnnxAttributeValue::Int(v)) => *v,
            _ => default,
        }
    }

    /// Get a float attribute, returning a default if missing.
    pub fn get_float_attr(&self, name: &str, default: f32) -> f32 {
        match self.get_attr(name) {
            Some(OnnxAttributeValue::Float(v)) => *v,
            _ => default,
        }
    }

    /// Get a list-of-ints attribute, returning empty if missing.
    pub fn get_ints_attr(&self, name: &str) -> Vec<i64> {
        match self.get_attr(name) {
            Some(OnnxAttributeValue::Ints(v)) => v.clone(),
            _ => Vec::new(),
        }
    }
}

/// A typed input/output descriptor for the graph.
///
/// # Examples
///
/// ```
/// # use scivex_nn::onnx::ir::{OnnxValueInfo, OnnxDataType};
/// let vi = OnnxValueInfo {
///     name: "input".to_string(),
///     data_type: OnnxDataType::Float,
///     shape: vec![1, 3, 224, 224],
/// };
/// assert_eq!(vi.name, "input");
/// assert_eq!(vi.shape.len(), 4);
/// ```
#[cfg_attr(
    feature = "serde-support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Debug, Clone)]
pub struct OnnxValueInfo {
    /// Tensor name.
    pub name: String,
    /// Element data type.
    pub data_type: OnnxDataType,
    /// Shape (may contain -1 for dynamic dims).
    pub shape: Vec<i64>,
}

/// An ONNX computation graph.
///
/// # Examples
///
/// ```
/// # use scivex_nn::onnx::ir::{OnnxGraph, OnnxNode};
/// let mut graph = OnnxGraph::new();
/// graph.name = "main_graph".to_string();
/// graph.nodes.push(OnnxNode::new("Relu"));
/// assert_eq!(graph.nodes.len(), 1);
/// ```
#[cfg_attr(
    feature = "serde-support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Debug, Clone)]
pub struct OnnxGraph {
    /// Graph name.
    pub name: String,
    /// Computation nodes.
    pub nodes: Vec<OnnxNode>,
    /// Weight / constant initializers.
    pub initializers: Vec<OnnxTensor>,
    /// Graph inputs.
    pub inputs: Vec<OnnxValueInfo>,
    /// Graph outputs.
    pub outputs: Vec<OnnxValueInfo>,
}

impl OnnxGraph {
    /// Create a new empty graph.
    ///
    /// # Examples
    ///
    /// ```
    /// # use scivex_nn::onnx::ir::OnnxGraph;
    /// let graph = OnnxGraph::new();
    /// assert!(graph.nodes.is_empty());
    /// assert!(graph.initializers.is_empty());
    /// ```
    pub fn new() -> Self {
        Self {
            name: String::new(),
            nodes: Vec::new(),
            initializers: Vec::new(),
            inputs: Vec::new(),
            outputs: Vec::new(),
        }
    }
}

impl Default for OnnxGraph {
    fn default() -> Self {
        Self::new()
    }
}

/// An ONNX opset import.
///
/// # Examples
///
/// ```
/// # use scivex_nn::onnx::ir::OnnxOpsetImport;
/// let opset = OnnxOpsetImport {
///     domain: String::new(), // default ONNX domain
///     version: 17,
/// };
/// assert_eq!(opset.version, 17);
/// assert!(opset.domain.is_empty());
/// ```
#[cfg_attr(
    feature = "serde-support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Debug, Clone)]
pub struct OnnxOpsetImport {
    /// Domain (empty string = default ONNX domain).
    pub domain: String,
    /// Opset version.
    pub version: i64,
}

/// Top-level ONNX model.
///
/// # Examples
///
/// ```
/// # use scivex_nn::onnx::ir::{OnnxModel, OnnxOpsetImport};
/// let mut model = OnnxModel::new();
/// model.ir_version = 8;
/// model.producer_name = "scivex".to_string();
/// model.opset_imports.push(OnnxOpsetImport { domain: String::new(), version: 17 });
/// assert_eq!(model.ir_version, 8);
/// assert_eq!(model.opset_imports.len(), 1);
/// ```
#[cfg_attr(
    feature = "serde-support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Debug, Clone)]
pub struct OnnxModel {
    /// IR version.
    pub ir_version: i64,
    /// Opset imports.
    pub opset_imports: Vec<OnnxOpsetImport>,
    /// The computation graph.
    pub graph: OnnxGraph,
    /// Producer name.
    pub producer_name: String,
    /// Model version.
    pub model_version: i64,
}

impl OnnxModel {
    /// Create a new empty model.
    ///
    /// # Examples
    ///
    /// ```
    /// # use scivex_nn::onnx::ir::OnnxModel;
    /// let model = OnnxModel::new();
    /// assert_eq!(model.ir_version, 0);
    /// assert!(model.opset_imports.is_empty());
    /// assert!(model.graph.nodes.is_empty());
    /// ```
    pub fn new() -> Self {
        Self {
            ir_version: 0,
            opset_imports: Vec::new(),
            graph: OnnxGraph::new(),
            producer_name: String::new(),
            model_version: 0,
        }
    }
}

impl Default for OnnxModel {
    fn default() -> Self {
        Self::new()
    }
}