runmat-vm 0.5.5

RunMat virtual machine and bytecode interpreter
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
use runmat_builtins::Value;
#[cfg(feature = "native-accel")]
use std::collections::HashSet;

#[cfg(feature = "native-accel")]
pub fn clear_value(value: &Value) -> Result<(), String> {
    clear_handles_in_value(value)
}

#[cfg(not(feature = "native-accel"))]
pub fn clear_value(_value: &Value) -> Result<(), String> {
    Ok(())
}

#[cfg(feature = "native-accel")]
pub fn clear_value_excluding(current: &Value, incoming: &Value) -> Result<(), String> {
    let mut keep_ids = HashSet::new();
    collect_gpu_buffer_ids(incoming, &mut keep_ids)?;
    clear_handles_in_value_excluding(current, &keep_ids)
}

#[cfg(feature = "native-accel")]
fn clear_handles_in_value(value: &Value) -> Result<(), String> {
    clear_handles_in_value_excluding(value, &HashSet::new())
}

#[cfg(feature = "native-accel")]
fn clear_handles_in_value_excluding(value: &Value, keep_ids: &HashSet<u64>) -> Result<(), String> {
    let mut visited_handle_targets = HashSet::new();
    clear_handles_in_value_excluding_with_visited(value, keep_ids, &mut visited_handle_targets)
}

#[cfg(feature = "native-accel")]
fn clear_handles_in_value_excluding_with_visited(
    value: &Value,
    keep_ids: &HashSet<u64>,
    visited_handle_targets: &mut HashSet<usize>,
) -> Result<(), String> {
    match value {
        Value::GpuTensor(handle) => {
            if !keep_ids.contains(&handle.buffer_id) {
                if let Some(provider) = runmat_accelerate_api::provider_for_handle(handle) {
                    let _ = provider.free(handle);
                }
                runmat_accelerate::fusion_residency::clear(handle);
                runmat_accelerate_api::clear_handle_logical(handle);
                runmat_accelerate_api::clear_handle_storage(handle);
                runmat_accelerate_api::clear_handle_transpose(handle);
            }
        }
        Value::Cell(cell) => {
            for elem in &cell.data {
                clear_handles_in_value_excluding_with_visited(
                    elem,
                    keep_ids,
                    visited_handle_targets,
                )?;
            }
        }
        Value::Struct(struct_value) => {
            for elem in struct_value.fields.values() {
                clear_handles_in_value_excluding_with_visited(
                    elem,
                    keep_ids,
                    visited_handle_targets,
                )?;
            }
        }
        Value::Object(object_value) => {
            for elem in object_value.properties.values() {
                clear_handles_in_value_excluding_with_visited(
                    elem,
                    keep_ids,
                    visited_handle_targets,
                )?;
            }
        }
        Value::Closure(closure) => {
            for capture in &closure.captures {
                clear_handles_in_value_excluding_with_visited(
                    capture,
                    keep_ids,
                    visited_handle_targets,
                )?;
            }
        }
        Value::OutputList(values) => {
            for elem in values {
                clear_handles_in_value_excluding_with_visited(
                    elem,
                    keep_ids,
                    visited_handle_targets,
                )?;
            }
        }
        Value::HandleObject(handle) => {
            let raw_target = runmat_gc::gc_handle_addr(&handle.target);
            if visited_handle_targets.insert(raw_target) {
                runmat_gc::gc_with_value(&handle.target, |target| {
                    clear_handles_in_value_excluding_with_visited(
                        target,
                        keep_ids,
                        visited_handle_targets,
                    )
                })
                .map_err(|err| err.to_string())??;
            }
        }
        Value::Int(_)
        | Value::Num(_)
        | Value::Complex(_, _)
        | Value::Bool(_)
        | Value::LogicalArray(_)
        | Value::String(_)
        | Value::StringArray(_)
        | Value::CharArray(_)
        | Value::Symbolic(_)
        | Value::Tensor(_)
        | Value::SparseTensor(_)
        | Value::ComplexTensor(_)
        | Value::Listener(_)
        | Value::FunctionHandle(_)
        | Value::ExternalFunctionHandle(_)
        | Value::MethodFunctionHandle(_)
        | Value::BoundFunctionHandle { .. }
        | Value::ClassRef(_)
        | Value::MException(_) => {}
    }
    Ok(())
}

#[cfg(feature = "native-accel")]
fn collect_gpu_buffer_ids(value: &Value, output: &mut HashSet<u64>) -> Result<(), String> {
    let mut visited_handle_targets = HashSet::new();
    collect_gpu_buffer_ids_with_visited(value, output, &mut visited_handle_targets)
}

#[cfg(feature = "native-accel")]
fn collect_gpu_buffer_ids_with_visited(
    value: &Value,
    output: &mut HashSet<u64>,
    visited_handle_targets: &mut HashSet<usize>,
) -> Result<(), String> {
    match value {
        Value::GpuTensor(handle) => {
            output.insert(handle.buffer_id);
        }
        Value::Cell(cell) => {
            for elem in &cell.data {
                collect_gpu_buffer_ids_with_visited(elem, output, visited_handle_targets)?;
            }
        }
        Value::Struct(struct_value) => {
            for elem in struct_value.fields.values() {
                collect_gpu_buffer_ids_with_visited(elem, output, visited_handle_targets)?;
            }
        }
        Value::Object(object_value) => {
            for elem in object_value.properties.values() {
                collect_gpu_buffer_ids_with_visited(elem, output, visited_handle_targets)?;
            }
        }
        Value::Closure(closure) => {
            for capture in &closure.captures {
                collect_gpu_buffer_ids_with_visited(capture, output, visited_handle_targets)?;
            }
        }
        Value::OutputList(values) => {
            for elem in values {
                collect_gpu_buffer_ids_with_visited(elem, output, visited_handle_targets)?;
            }
        }
        Value::HandleObject(handle) => {
            let raw_target = runmat_gc::gc_handle_addr(&handle.target);
            if visited_handle_targets.insert(raw_target) {
                runmat_gc::gc_with_value(&handle.target, |target| {
                    collect_gpu_buffer_ids_with_visited(target, output, visited_handle_targets)
                })
                .map_err(|err| err.to_string())??;
            }
        }
        Value::Int(_)
        | Value::Num(_)
        | Value::Complex(_, _)
        | Value::Bool(_)
        | Value::LogicalArray(_)
        | Value::String(_)
        | Value::StringArray(_)
        | Value::CharArray(_)
        | Value::Symbolic(_)
        | Value::Tensor(_)
        | Value::SparseTensor(_)
        | Value::ComplexTensor(_)
        | Value::Listener(_)
        | Value::FunctionHandle(_)
        | Value::ExternalFunctionHandle(_)
        | Value::MethodFunctionHandle(_)
        | Value::BoundFunctionHandle { .. }
        | Value::ClassRef(_)
        | Value::MException(_) => {}
    }
    Ok(())
}

#[cfg(all(test, feature = "native-accel"))]
mod tests {
    use super::{clear_value, clear_value_excluding};
    use futures::executor::block_on;
    use once_cell::sync::Lazy;
    use runmat_accelerate::fusion_residency;
    use runmat_accelerate::simple_provider::InProcessProvider;
    use runmat_accelerate_api::{
        AccelProvider, GpuTensorHandle, HostTensorView, ThreadProviderGuard,
    };
    use runmat_builtins::{CellArray, Closure, HandleRef, StructValue, Value};

    static TEST_PROVIDER: Lazy<InProcessProvider> = Lazy::new(InProcessProvider::new);

    fn upload_handle(data: Vec<f64>, shape: Vec<usize>) -> GpuTensorHandle {
        TEST_PROVIDER
            .upload(&HostTensorView {
                data: &data,
                shape: &shape,
            })
            .expect("upload should succeed")
    }

    #[test]
    fn clear_value_releases_nested_gpu_handles_in_cells() {
        let handle = GpuTensorHandle {
            shape: vec![1],
            device_id: 7,
            buffer_id: 7001,
        };
        fusion_residency::mark(&handle);
        assert!(fusion_residency::is_resident(&handle));

        let value = Value::Cell(
            CellArray::new(vec![Value::GpuTensor(handle.clone())], 1, 1).expect("cell"),
        );
        clear_value(&value).expect("clear nested cell handles");
        assert!(
            !fusion_residency::is_resident(&handle),
            "nested cell GPU handles should clear residency"
        );
    }

    #[test]
    fn clear_value_releases_nested_gpu_handles_in_closure_captures() {
        let handle = GpuTensorHandle {
            shape: vec![1],
            device_id: 8,
            buffer_id: 8001,
        };
        fusion_residency::mark(&handle);
        assert!(fusion_residency::is_resident(&handle));

        let value = Value::Closure(Closure {
            function_name: "worker".to_string(),
            bound_function: None,
            captures: vec![Value::GpuTensor(handle.clone())],
        });
        clear_value(&value).expect("clear nested closure handles");
        assert!(
            !fusion_residency::is_resident(&handle),
            "closure-captured GPU handles should clear residency"
        );
    }

    #[test]
    fn clear_value_excluding_preserves_shared_handles() {
        let _provider_guard = ThreadProviderGuard::set(Some(&*TEST_PROVIDER));
        let shared = upload_handle(vec![1.0], vec![1]);
        let old_only = upload_handle(vec![2.0], vec![1]);
        fusion_residency::mark(&shared);
        fusion_residency::mark(&old_only);
        assert!(fusion_residency::is_resident(&shared));
        assert!(fusion_residency::is_resident(&old_only));
        assert!(block_on(TEST_PROVIDER.download(&shared)).is_ok());
        assert!(block_on(TEST_PROVIDER.download(&old_only)).is_ok());

        let current = Value::OutputList(vec![
            Value::GpuTensor(shared.clone()),
            Value::GpuTensor(old_only.clone()),
        ]);
        let incoming = Value::GpuTensor(shared.clone());
        clear_value_excluding(&current, &incoming).expect("clear excluding shared handles");

        assert!(
            fusion_residency::is_resident(&shared),
            "shared handle should remain resident across overwrite"
        );
        assert!(
            !fusion_residency::is_resident(&old_only),
            "non-shared handle should clear residency across overwrite"
        );
        assert!(
            block_on(TEST_PROVIDER.download(&shared)).is_ok(),
            "shared handle should remain available in provider storage"
        );
        assert!(
            block_on(TEST_PROVIDER.download(&old_only)).is_err(),
            "dropped handle should be released from provider storage"
        );
        fusion_residency::clear(&shared);
        let _ = TEST_PROVIDER.free(&shared);
    }

    #[test]
    fn clear_value_releases_provider_storage_for_dropped_handle() {
        let _provider_guard = ThreadProviderGuard::set(Some(&*TEST_PROVIDER));
        let handle = upload_handle(vec![3.0], vec![1]);
        assert!(block_on(TEST_PROVIDER.download(&handle)).is_ok());
        fusion_residency::mark(&handle);

        clear_value(&Value::GpuTensor(handle.clone())).expect("clear direct handle");

        assert!(
            !fusion_residency::is_resident(&handle),
            "cleared handle should no longer be marked resident"
        );
        assert!(
            block_on(TEST_PROVIDER.download(&handle)).is_err(),
            "cleared handle should be released from provider storage"
        );
    }

    #[test]
    fn clear_value_releases_gpu_handles_nested_in_handle_object_target() {
        let _provider_guard = ThreadProviderGuard::set(Some(&*TEST_PROVIDER));
        let handle = upload_handle(vec![4.0], vec![1]);
        assert!(block_on(TEST_PROVIDER.download(&handle)).is_ok());
        fusion_residency::mark(&handle);
        let mut payload = StructValue::new();
        payload
            .fields
            .insert("nested".to_string(), Value::GpuTensor(handle.clone()));
        let gc_target =
            runmat_gc::gc_allocate(Value::Struct(payload)).expect("gc allocate payload");
        let value = Value::HandleObject(HandleRef {
            class_name: "Payload".to_string(),
            target: gc_target,
            valid: true,
        });

        clear_value(&value).expect("clear handle-object target handles");

        assert!(
            !fusion_residency::is_resident(&handle),
            "nested handle-object payload should clear GPU residency"
        );
        assert!(
            block_on(TEST_PROVIDER.download(&handle)).is_err(),
            "nested handle-object payload should release provider storage"
        );
    }

    #[test]
    fn clear_value_excluding_preserves_handles_referenced_in_handle_object_target() {
        let _provider_guard = ThreadProviderGuard::set(Some(&*TEST_PROVIDER));
        let shared = upload_handle(vec![5.0], vec![1]);
        let old_only = upload_handle(vec![6.0], vec![1]);
        fusion_residency::mark(&shared);
        fusion_residency::mark(&old_only);
        assert!(block_on(TEST_PROVIDER.download(&shared)).is_ok());
        assert!(block_on(TEST_PROVIDER.download(&old_only)).is_ok());

        let current = Value::OutputList(vec![
            Value::GpuTensor(shared.clone()),
            Value::GpuTensor(old_only.clone()),
        ]);
        let mut incoming_payload = StructValue::new();
        incoming_payload
            .fields
            .insert("nested".to_string(), Value::GpuTensor(shared.clone()));
        let incoming_gc =
            runmat_gc::gc_allocate(Value::Struct(incoming_payload)).expect("gc allocate incoming");
        let incoming = Value::HandleObject(HandleRef {
            class_name: "Payload".to_string(),
            target: incoming_gc,
            valid: true,
        });

        clear_value_excluding(&current, &incoming)
            .expect("clear excluding handle-object target handles");

        assert!(
            fusion_residency::is_resident(&shared),
            "shared handle in handle-object target should remain resident across overwrite"
        );
        assert!(
            !fusion_residency::is_resident(&old_only),
            "non-shared handle should clear residency across overwrite"
        );
        assert!(
            block_on(TEST_PROVIDER.download(&shared)).is_ok(),
            "shared handle in handle-object target should remain available in provider storage"
        );
        assert!(
            block_on(TEST_PROVIDER.download(&old_only)).is_err(),
            "dropped handle should be released from provider storage"
        );
        fusion_residency::clear(&shared);
        let _ = TEST_PROVIDER.free(&shared);
    }
}