somatize-runtime 0.2.46

Execution engine for the Soma computational graph runtime
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
//! Memory usage tests — verify that batched and streaming execution do not
//! leak memory as more chunks/batches are processed.
//!
//! Uses a tracking global allocator to measure peak and current heap usage
//! at key points during execution.

use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};

// ── Tracking allocator ──

struct TrackingAllocator;

static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
static PEAK: AtomicUsize = AtomicUsize::new(0);

unsafe impl GlobalAlloc for TrackingAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let ptr = unsafe { System.alloc(layout) };
        if !ptr.is_null() {
            let current = ALLOCATED.fetch_add(layout.size(), Ordering::Relaxed) + layout.size();
            PEAK.fetch_max(current, Ordering::Relaxed);
        }
        ptr
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        unsafe { System.dealloc(ptr, layout) };
        ALLOCATED.fetch_sub(layout.size(), Ordering::Relaxed);
    }
}

#[global_allocator]
static GLOBAL: TrackingAllocator = TrackingAllocator;

fn current_allocated() -> usize {
    ALLOCATED.load(Ordering::Relaxed)
}

fn reset_peak() {
    PEAK.store(ALLOCATED.load(Ordering::Relaxed), Ordering::Relaxed);
}

fn peak_allocated() -> usize {
    PEAK.load(Ordering::Relaxed)
}

// ── Test filters ──

use somatize_core::cache::CacheKey;
use somatize_core::error::Result;
use somatize_core::filter::{Distribution, Filter, FilterKind, FilterMeta, StreamMode};
use somatize_core::value::Value;
use std::sync::Arc;

/// Stateless filter that doubles tensor values. Allocates a new output
/// tensor on each call but keeps no internal state.
struct Doubler;

impl Filter for Doubler {
    fn config_hash(&self) -> CacheKey {
        CacheKey::from_parts(&[b"Doubler"])
    }
    fn fit(&self, _x: &Value, _y: Option<&Value>) -> Result<Value> {
        Ok(Value::Empty)
    }
    fn forward(&self, x: &Value, _state: &Value) -> Result<Value> {
        match x {
            Value::Tensor { values, shape } => Ok(Value::tensor(
                values.iter().map(|v| v * 2.0).collect(),
                shape.clone(),
            )),
            _ => Ok(x.clone()),
        }
    }
    fn meta(&self) -> FilterMeta {
        FilterMeta {
            name: "Doubler".into(),
            kind: FilterKind::Stateless,
            cacheable: false,
            differentiable: false,
            stream_mode: StreamMode::FixedState,
            distribution: Distribution::Local,
            input_schema: None,
            output_schema: None,
        }
    }
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Trainable filter that learns a mean and subtracts it.
struct MeanNormalizer;

impl Filter for MeanNormalizer {
    fn config_hash(&self) -> CacheKey {
        CacheKey::from_parts(&[b"MeanNorm"])
    }
    fn fit(&self, x: &Value, _y: Option<&Value>) -> Result<Value> {
        if let Some((data, _)) = x.as_tensor() {
            let mean = data.iter().sum::<f64>() / data.len().max(1) as f64;
            Ok(Value::json(serde_json::json!({ "mean": mean })))
        } else {
            Ok(Value::Empty)
        }
    }
    fn forward(&self, x: &Value, state: &Value) -> Result<Value> {
        let mean = state
            .as_json()
            .and_then(|j| j["mean"].as_f64())
            .unwrap_or(0.0);
        match x {
            Value::Tensor { values, shape } => Ok(Value::tensor(
                values.iter().map(|v| v - mean).collect(),
                shape.clone(),
            )),
            _ => Ok(x.clone()),
        }
    }
    fn meta(&self) -> FilterMeta {
        FilterMeta {
            name: "MeanNorm".into(),
            kind: FilterKind::Trainable,
            cacheable: false,
            differentiable: false,
            stream_mode: StreamMode::FixedState,
            distribution: Distribution::Local,
            input_schema: None,
            output_schema: None,
        }
    }
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

// ── Helper ──

use somatize_core::graph::{Graph, Node};
use somatize_runtime::cache::MemoryCache;
use somatize_runtime::filter_library::FilterLibrary;
use somatize_runtime::graph_session::GraphSession;

fn make_doubler_session() -> GraphSession {
    let mut graph = Graph::new();
    graph.nodes.push(Node::new("double", "Double", "double"));

    let mut lib = FilterLibrary::new();
    lib.register("double", Box::new(Doubler));

    let cache = Arc::new(MemoryCache::new(64 * 1024 * 1024)); // 64 MB
    GraphSession::new(graph, lib).with_cache(cache)
}

fn make_pipeline_session() -> GraphSession {
    use somatize_core::graph::Edge;

    let mut graph = Graph::new();
    graph.nodes.push(Node::new("norm", "Normalize", "norm"));
    graph.nodes.push(Node::new("double", "Double", "double"));
    graph
        .edges
        .push(Edge::data("norm_to_double", "norm", "double"));

    let mut lib = FilterLibrary::new();
    lib.register("norm", Box::new(MeanNormalizer));
    lib.register("double", Box::new(Doubler));

    let cache = Arc::new(MemoryCache::new(64 * 1024 * 1024));
    GraphSession::new(graph, lib).with_cache(cache)
}

// ── Memory tests ──

/// Stream many chunks and verify memory stays bounded.
///
/// The current stream executor accumulates all chunk outputs in a Vec
/// before concatenating them (known design tradeoff). So we expect memory
/// proportional to input + output + accumulated chunks. What we guard
/// against is EXTRA growth beyond that — e.g. leaked contexts, duplicated
/// states, or unbounded caches.
#[test]
fn stream_memory_does_not_grow_with_chunks() {
    use somatize_runtime::forward::Stream;

    let session = make_doubler_session();

    let chunk_rows = 1000;
    let n_chunks = 50;
    let total_rows = chunk_rows * n_chunks;

    // Large input: many rows
    let input = Value::tensor(
        (0..total_rows).map(|i| i as f64).collect(),
        vec![total_rows],
    );

    // Warm up — let internal structures settle
    let small = Value::tensor(vec![1.0; chunk_rows], vec![chunk_rows]);
    let _ = session.forward_with(
        &small,
        &Stream {
            chunk_size: chunk_rows,
        },
    );

    // Measure baseline
    reset_peak();
    let before = current_allocated();

    let result = session.forward_with(
        &input,
        &Stream {
            chunk_size: chunk_rows,
        },
    );
    assert!(result.is_ok());

    let after = current_allocated();
    let peak = peak_allocated();

    // Expected: input (held during streaming) + output tensor + intermediate
    // chunk outputs Vec. The output is ~total_rows * 8 bytes.
    let expected_output_bytes = total_rows * std::mem::size_of::<f64>();
    let growth = after.saturating_sub(before);

    eprintln!(
        "Stream: before={before}B, after={after}B, peak={peak}B, growth={growth}B, expected_output={expected_output_bytes}B"
    );

    // Growth should be bounded: output tensor + some overhead.
    // Fail if we see more than 8× the output size (which would indicate
    // a real leak beyond the expected chunk accumulation).
    assert!(
        growth < expected_output_bytes * 8,
        "Memory grew {growth}B after streaming {n_chunks} chunks — possible leak \
         (expected < {}B)",
        expected_output_bytes * 8
    );
}

/// Process many batches and verify memory stays bounded.
///
/// Simulates what Batched strategy does: repeatedly calling forward()
/// with different batch data. Memory should not accumulate across calls.
#[test]
fn repeated_forward_memory_does_not_grow() {
    let session = make_doubler_session();

    let batch_size = 1000;
    let n_batches = 100;

    // Warm up
    let warm = Value::tensor(vec![1.0; batch_size], vec![batch_size]);
    let _ = session.forward(&warm);

    reset_peak();
    let before = current_allocated();

    for i in 0..n_batches {
        let batch = Value::tensor(
            (0..batch_size)
                .map(|j| (i * batch_size + j) as f64)
                .collect(),
            vec![batch_size],
        );
        let result = session.forward(&batch);
        assert!(result.is_ok());
    }

    let after = current_allocated();
    let peak = peak_allocated();

    let single_batch_bytes = batch_size * std::mem::size_of::<f64>();
    let growth = after.saturating_sub(before);

    eprintln!(
        "Batched: before={before}B, after={after}B, peak={peak}B, growth={growth}B, single_batch={single_batch_bytes}B"
    );

    // After all batches are done, memory should not retain more than a few
    // batch-sized buffers. If it grew linearly with n_batches, that's a leak.
    // Allow 10× single batch as margin (cache entries, Arc overhead, etc).
    assert!(
        growth < single_batch_bytes * 10,
        "Memory grew {growth}B after {n_batches} forward() calls — possible leak \
         (expected < {}B)",
        single_batch_bytes * 10
    );
}

/// Verify that peak memory during streaming is bounded.
///
/// The current executor holds all chunk outputs until concatenation, so
/// peak ≈ input + all chunk outputs + final tensor. We verify it doesn't
/// exceed a reasonable multiple of the data size.
#[test]
fn stream_peak_memory_bounded() {
    use somatize_runtime::forward::Stream;

    let session = make_doubler_session();

    let chunk_rows = 500;
    let total_rows = 50_000; // 100 chunks

    let input = Value::tensor(
        (0..total_rows).map(|i| i as f64).collect(),
        vec![total_rows],
    );

    let input_bytes = total_rows * std::mem::size_of::<f64>();

    // Warm up
    let small = Value::tensor(vec![1.0; chunk_rows], vec![chunk_rows]);
    let _ = session.forward_with(
        &small,
        &Stream {
            chunk_size: chunk_rows,
        },
    );

    reset_peak();
    let before = current_allocated();

    let result = session.forward_with(
        &input,
        &Stream {
            chunk_size: chunk_rows,
        },
    );
    assert!(result.is_ok());

    let peak = peak_allocated();
    let peak_growth = peak.saturating_sub(before);

    eprintln!("Peak: before={before}B, peak={peak}B, growth={peak_growth}B, input={input_bytes}B");

    // Peak = input (400KB) + chunked outputs (~400KB) + final concat (~400KB)
    // + overhead. Allow 8× input as upper bound to catch real leaks.
    assert!(
        peak_growth < input_bytes * 8,
        "Peak memory {peak_growth}B during streaming is too high — may accumulate \
         extra data (expected < {}B)",
        input_bytes * 8
    );
}

/// Run fit + forward on a pipeline and verify memory stays stable across
/// multiple forward passes after fitting.
#[test]
fn pipeline_fit_then_repeated_forward_stable() {
    let mut session = make_pipeline_session();

    let train_data = Value::tensor((0..5000).map(|i| i as f64).collect(), vec![5000]);

    // Fit the pipeline
    let fit_result = session.fit(&train_data, None);
    assert!(fit_result.is_ok());

    // Warm up forward
    let warm = Value::tensor(vec![1.0; 1000], vec![1000]);
    let _ = session.forward(&warm);

    reset_peak();
    let before = current_allocated();

    // Run many forward passes
    let n_passes = 50;
    let batch_size = 1000;
    for i in 0..n_passes {
        let batch = Value::tensor(
            (0..batch_size)
                .map(|j| (i * batch_size + j) as f64)
                .collect(),
            vec![batch_size],
        );
        let result = session.forward(&batch);
        assert!(result.is_ok());
    }

    let after = current_allocated();
    let single_batch_bytes = batch_size * std::mem::size_of::<f64>();
    let growth = after.saturating_sub(before);

    eprintln!("Pipeline: before={before}B, after={after}B, growth={growth}B");

    // Memory should not grow linearly with number of forward passes.
    assert!(
        growth < single_batch_bytes * 15,
        "Pipeline memory grew {growth}B after {n_passes} forward passes — possible leak \
         (expected < {}B)",
        single_batch_bytes * 15
    );
}

/// Verify that Value::clone() is cheap (Arc clone, not deep copy).
#[test]
fn value_clone_is_cheap() {
    // Create a large tensor
    let big = Value::tensor(vec![42.0; 100_000], vec![100_000]);

    reset_peak();
    let before = current_allocated();

    // Clone 100 times — should be essentially free
    let mut clones = Vec::with_capacity(100);
    for _ in 0..100 {
        clones.push(big.clone());
    }

    let after = current_allocated();
    let growth = after.saturating_sub(before);

    // The original tensor is 100K * 8 = 800KB.
    // 100 clones via Arc should cost ~0 bytes of data, just pointer+refcount overhead.
    // Allow 100KB for Vec<Value> + Arc overhead (which is negligible).
    let data_size = 100_000 * std::mem::size_of::<f64>();

    eprintln!("Clone: before={before}B, after={after}B, growth={growth}B, data_size={data_size}B");

    assert!(
        growth < data_size / 4, // Less than 25% of ONE tensor copy
        "Cloning Value allocated {growth}B — expected near-zero \
         (Arc clone). data_size={data_size}B"
    );

    drop(clones);
}