rumus 0.3.0

A native-Rust deep learning framework with explicit memory safety and hardware acceleration
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
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Thread-local ONNX graph tracer.
//!
//! When active, tensor ops record `TracedNode` entries instead of (or in
//! addition to) their normal eager execution.  The tracer intercepts at
//! two levels:
//!
//! 1. **Primitive ops** (matmul, relu, etc.) — record individual ONNX nodes.
//! 2. **Module-level fusions** (Linear → Gemm, Conv2d → Conv) — suppress
//!    primitive recording and emit a single fused ONNX node.

use std::cell::RefCell;
use std::collections::HashMap;

use crate::tensor::{DType, Tensor};

// ---------------------------------------------------------------------------
// Traced graph types
// ---------------------------------------------------------------------------

/// A single ONNX operator node captured during tracing.
#[derive(Debug, Clone)]
pub struct TracedNode {
    pub op_type: String,
    pub inputs: Vec<String>,
    pub outputs: Vec<String>,
    pub attributes: Vec<TracedAttribute>,
}

/// An ONNX attribute value.
#[derive(Debug, Clone)]
pub enum TracedAttribute {
    Int(String, i64),
    Float(String, f32),
    Ints(String, Vec<i64>),
    Floats(String, Vec<f32>),
    String(String, String),
}

/// Shape + dtype information for a traced value.
#[derive(Debug, Clone)]
pub struct ValueInfo {
    pub shape: Vec<usize>,
    pub dtype: DType,
}

/// The complete traced graph, ready for conversion to ONNX proto.
pub struct TracedGraph {
    pub nodes: Vec<TracedNode>,
    pub inputs: Vec<(String, ValueInfo)>,
    pub outputs: Vec<(String, ValueInfo)>,
    pub initializers: Vec<(String, Tensor)>,
}

// ---------------------------------------------------------------------------
// Thread-local tracer context
// ---------------------------------------------------------------------------

struct Tracer {
    nodes: Vec<TracedNode>,
    /// Maps storage pointer → value name for name propagation.
    value_names: HashMap<usize, String>,
    /// Shape + dtype per named value.
    value_info: HashMap<String, ValueInfo>,
    /// Collected parameter tensors.
    initializers: Vec<(String, Tensor)>,
    /// Monotonic counter for auto-naming.
    next_id: usize,
    /// When > 0, primitive op recording is suppressed (module-level fusion).
    suppress_depth: usize,
}

impl Tracer {
    fn new() -> Self {
        Self {
            nodes: Vec::new(),
            value_names: HashMap::new(),
            value_info: HashMap::new(),
            initializers: Vec::new(),
            next_id: 0,
            suppress_depth: 0,
        }
    }

    fn fresh_name(&mut self, prefix: &str) -> String {
        let name = format!("{}_{}", prefix, self.next_id);
        self.next_id += 1;
        name
    }
}

thread_local! {
    static TRACER: RefCell<Option<Tracer>> = RefCell::new(None);
}

/// Returns `true` if the ONNX tracer is currently active.
pub fn is_tracing() -> bool {
    TRACER.with(|t| t.borrow().is_some())
}

/// Returns `true` if primitive op recording is suppressed (inside a fused module).
pub fn is_suppressed() -> bool {
    TRACER.with(|t| {
        t.borrow()
            .as_ref()
            .map_or(false, |tr| tr.suppress_depth > 0)
    })
}

/// Execute a closure with mutable access to the active tracer.
///
/// Panics if no tracer is active.
pub fn with_tracer<F, R>(f: F) -> R
where
    F: FnOnce(&mut TracerHandle<'_>) -> R,
{
    TRACER.with(|t| {
        let mut borrow = t.borrow_mut();
        let tracer = borrow.as_mut().expect("ONNX tracer not active");
        let mut handle = TracerHandle { inner: tracer };
        f(&mut handle)
    })
}

/// Safe handle to the tracer, providing the public recording API.
pub struct TracerHandle<'a> {
    inner: &'a mut Tracer,
}

impl TracerHandle<'_> {
    /// Get or assign a name for a tensor (identified by storage pointer).
    pub fn name_of(&mut self, tensor: &Tensor) -> String {
        let key = tensor.storage.ptr_id();
        if let Some(name) = self.inner.value_names.get(&key) {
            return name.clone();
        }
        let name = self.inner.fresh_name("val");
        self.inner.value_names.insert(key, name.clone());
        self.inner.value_info.insert(
            name.clone(),
            ValueInfo {
                shape: tensor.shape().to_vec(),
                dtype: tensor.dtype(),
            },
        );
        name
    }

    /// Assign a specific name to a tensor.
    pub fn set_name(&mut self, tensor: &Tensor, name: String) {
        let key = tensor.storage.ptr_id();
        self.inner.value_names.insert(key, name.clone());
        self.inner.value_info.insert(
            name,
            ValueInfo {
                shape: tensor.shape().to_vec(),
                dtype: tensor.dtype(),
            },
        );
    }

    /// Record a traced node.  Suppressed nodes are silently dropped.
    pub fn record_node(&mut self, node: TracedNode) {
        if self.inner.suppress_depth == 0 {
            self.inner.nodes.push(node);
        }
    }

    /// Register a parameter tensor as an initializer.
    pub fn add_initializer(&mut self, name: &str, tensor: &Tensor) {
        // Avoid duplicates.
        if !self.inner.initializers.iter().any(|(n, _)| n == name) {
            self.inner.initializers.push((name.to_string(), tensor.clone()));
        }
    }

    /// Enter a fused-module scope: suppress primitive op recording.
    pub fn enter_fusion(&mut self) {
        self.inner.suppress_depth += 1;
    }

    /// Exit a fused-module scope.
    pub fn leave_fusion(&mut self) {
        self.inner.suppress_depth = self.inner.suppress_depth.saturating_sub(1);
    }

    /// Allocate a fresh unique name.
    pub fn fresh_name(&mut self, prefix: &str) -> String {
        self.inner.fresh_name(prefix)
    }

    /// Register value info for a name.
    pub fn register_value(&mut self, name: &str, info: ValueInfo) {
        self.inner.value_info.insert(name.to_string(), info);
    }
}

// ---------------------------------------------------------------------------
// Public tracing API
// ---------------------------------------------------------------------------

/// Trace a model's forward pass and capture the ONNX computational graph.
///
/// Creates dummy input tensors, runs the forward function, and collects
/// the traced nodes + initializers.
///
/// # Arguments
///
/// - `state_dict`: parameter name → tensor map (from `model.state_dict("")`).
/// - `input_specs`: list of `(name, shape, dtype)` for each model input.
/// - `forward_fn`: closure executing the model's forward pass.
pub fn trace<F>(
    state_dict: &HashMap<String, Tensor>,
    input_specs: &[(&str, Vec<usize>, DType)],
    forward_fn: F,
) -> TracedGraph
where
    F: FnOnce(&[Tensor]) -> Tensor,
{
    // Create dummy inputs.
    let mut inputs = Vec::with_capacity(input_specs.len());
    let mut input_infos = Vec::new();

    // Initialize the tracer.
    let mut tracer = Tracer::new();

    // Pre-register all parameters as initializers and named values.
    for (name, tensor) in state_dict {
        let key = tensor.storage.ptr_id();
        tracer.value_names.insert(key, name.clone());
        tracer.value_info.insert(
            name.clone(),
            ValueInfo {
                shape: tensor.shape().to_vec(),
                dtype: tensor.dtype(),
            },
        );
        tracer.initializers.push((name.clone(), tensor.clone()));
    }

    for (name, shape, dtype) in input_specs {
        let numel: usize = shape.iter().product();
        let tensor = Tensor::new(vec![0.0f32; numel], shape.clone());
        let key = tensor.storage.ptr_id();
        tracer.value_names.insert(key, name.to_string());
        tracer.value_info.insert(
            name.to_string(),
            ValueInfo {
                shape: shape.clone(),
                dtype: *dtype,
            },
        );
        input_infos.push((name.to_string(), ValueInfo { shape: shape.clone(), dtype: *dtype }));
        inputs.push(tensor);
    }

    // Activate the tracer.
    TRACER.with(|t| *t.borrow_mut() = Some(tracer));

    // Run the forward pass — ops will record TracedNodes.
    let output = forward_fn(&inputs);

    // Deactivate and extract.
    let tracer = TRACER.with(|t| t.borrow_mut().take()).expect("tracer lost");

    let output_name = tracer
        .value_names
        .get(&output.storage.ptr_id())
        .cloned()
        .unwrap_or_else(|| "output_0".to_string());
    let output_info = ValueInfo {
        shape: output.shape().to_vec(),
        dtype: output.dtype(),
    };

    TracedGraph {
        nodes: tracer.nodes,
        inputs: input_infos,
        outputs: vec![(output_name, output_info)],
        initializers: tracer.initializers,
    }
}

// ---------------------------------------------------------------------------
// Convenience helpers for recording common ops
// ---------------------------------------------------------------------------

/// Record a simple unary op (Relu, Sigmoid, Tanh, etc.).
pub fn record_unary(input: &Tensor, output: &Tensor, op_type: &str) {
    if !is_tracing() || is_suppressed() {
        return;
    }
    with_tracer(|t| {
        let in_name = t.name_of(input);
        let out_name = t.name_of(output);
        t.record_node(TracedNode {
            op_type: op_type.to_string(),
            inputs: vec![in_name],
            outputs: vec![out_name],
            attributes: vec![],
        });
    });
}

/// Record a binary op (Add, Sub, Mul, MatMul, etc.).
pub fn record_binary(lhs: &Tensor, rhs: &Tensor, output: &Tensor, op_type: &str) {
    if !is_tracing() || is_suppressed() {
        return;
    }
    with_tracer(|t| {
        let l = t.name_of(lhs);
        let r = t.name_of(rhs);
        let o = t.name_of(output);
        t.record_node(TracedNode {
            op_type: op_type.to_string(),
            inputs: vec![l, r],
            outputs: vec![o],
            attributes: vec![],
        });
    });
}

/// Record a fused Gemm node (Linear layer: y = alpha*A@B + beta*C).
pub fn trace_linear(
    input: &Tensor,
    weight: &Tensor,
    bias: Option<&Tensor>,
    output: &Tensor,
    weight_name: &str,
    bias_name: Option<&str>,
) {
    if !is_tracing() {
        return;
    }
    with_tracer(|t| {
        let in_name = t.name_of(input);
        let out_name = t.name_of(output);
        t.add_initializer(weight_name, weight);
        let mut inputs = vec![in_name, weight_name.to_string()];
        if let (Some(b), Some(bn)) = (bias, bias_name) {
            t.add_initializer(bn, b);
            inputs.push(bn.to_string());
        }
        t.record_node(TracedNode {
            op_type: "Gemm".to_string(),
            inputs,
            outputs: vec![out_name],
            attributes: vec![
                TracedAttribute::Float("alpha".to_string(), 1.0),
                TracedAttribute::Float("beta".to_string(), 1.0),
                TracedAttribute::Int("transB".to_string(), 0), // weight is [in, out], no transpose needed
            ],
        });
    });
}

/// Record a fused Conv node.
pub fn trace_conv2d(
    input: &Tensor,
    output: &Tensor,
    weight_name: &str,
    weight: &Tensor,
    bias_name: Option<&str>,
    bias: Option<&Tensor>,
    kernel_size: usize,
    stride: usize,
    padding: usize,
    in_channels: usize,
    out_channels: usize,
) {
    if !is_tracing() {
        return;
    }
    with_tracer(|t| {
        let in_name = t.name_of(input);
        let out_name = t.name_of(output);

        // Register weight as initializer.
        // ONNX Conv expects weight shape [C_out, C_in, K, K].
        // Our weight is [C_out, C_in*K*K] — register with the ONNX-expected shape
        // in the value info (the raw data is correct when reshaped).
        t.add_initializer(weight_name, weight);
        t.register_value(weight_name, ValueInfo {
            shape: vec![out_channels, in_channels, kernel_size, kernel_size],
            dtype: weight.dtype(),
        });

        let mut inputs = vec![in_name, weight_name.to_string()];
        if let (Some(b), Some(bn)) = (bias, bias_name) {
            t.add_initializer(bn, b);
            inputs.push(bn.to_string());
        }

        t.record_node(TracedNode {
            op_type: "Conv".to_string(),
            inputs,
            outputs: vec![out_name],
            attributes: vec![
                TracedAttribute::Ints("kernel_shape".to_string(), vec![kernel_size as i64, kernel_size as i64]),
                TracedAttribute::Ints("strides".to_string(), vec![stride as i64, stride as i64]),
                TracedAttribute::Ints("pads".to_string(), vec![padding as i64, padding as i64, padding as i64, padding as i64]),
                TracedAttribute::Ints("dilations".to_string(), vec![1, 1]),
            ],
        });
    });
}