gras 2.0.1

A Genetic Programming framework for Neural Architecture Search in Rust
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
//! Safetensors export — write a built [`Network`]'s parameters
//! `.safetensors` file (Hugging Face's simple tensor serialization format).
//!
//! The format is deliberately tiny: an 8-byte little-endian header length,
//! a JSON header mapping tensor names to `{dtype, shape, data_offsets}`,
//! then the raw byte blobs. PyTorch loads it natively:
//!
//! ```python
//! from safetensors.torch import load_file
//! tensors = load_file("champion-0b9891b7.safetensors")
//! ```
//!
//! Naming convention — **two families**, both required:
//!
//! - one Linear per graph node ⇒ a weight `node<N>.weight` of shape `[out, hidden]`
//!   and a bias `node<N>.bias` of shape `[out]` (when present);
//! - one Linear per **cross-dim bridge** (a wire whose source and target dims
//!   differ) ⇒ `proj<N>_<port>_<src>.weight` `[in_dim, src_dim]` (+ `.bias`),
//!   indexed by target node, target port, and the source's index on that port.
//!
//! A Python-side mirror builds `torch.nn.Linear(in, out)` per node, applies
//! the `proj*` layers to the wires that need them, and `load_state_dict`-style
//! copies by the same names — no gras code needed at inference. Writing
//! the `node*` family produces a net that looks right and behaves like
//! stranger: the bridges stay at their random init, and on a net with mixed
//! dims those bridges sit on the critical path.
//!
//! Round-trip: [`export_safetensors`] writes it, [`load_safetensors`] reads
//! it back into an already-built [`Network`] (shapes must match —
//! blueprint is still the source of topology truth). This is what lets
//! guardrail re-check the CHAMPION's trained weights, not a newborn's.

use std::path::{Path, PathBuf};

use flodl::tensor::{DType, Result, Tensor, TensorError};

use crate::graph::network::Network;

/// One tensor to serialize: name, dtype, shape, raw little-endian bytes.
struct TensorBlob {
    name: String,
    dtype: &'static str,
    shape: Vec<i64>,
    data: Vec<u8>,
}

/// Collect a network's parameters in safetensors naming convention. **Every**
/// trained tensor must be here — missing port bridges silently cripple a net.
fn collect_tensors(net: &Network) -> Result<Vec<TensorBlob>> {
    let mut blobs = Vec::new();
    for (idx, layer) in net.layers.iter().enumerate() {
        push_linear(&mut blobs, &format!("node{idx}"), layer)?;
    }
    // `proj<N>_<port>_0`: one bridge per input port, so the trailing source index
    for (node, ports) in net.port_projections.iter().enumerate() {
        for (port, proj) in ports.iter().enumerate() {
            if let Some(linear) = proj {
                push_linear(&mut blobs, &format!("proj{node}_{port}_0"), linear)?;
            }
        }
    }
    Ok(blobs)
}

/// Append one Linear's weight (+ optional bias) under `prefix`.
fn push_linear(blobs: &mut Vec<TensorBlob>, prefix: &str, layer: &flodl::nn::Linear) -> Result<()> {
    let w = layer.weight.variable.data();
    blobs.push(TensorBlob {
        name: format!("{prefix}.weight"),
        dtype: dtype_tag(w.dtype()),
        shape: w.shape(),
        data: w.to_blob()?,
    });
    if let Some(b) = &layer.bias {
        let bt = b.variable.data();
        blobs.push(TensorBlob {
            name: format!("{prefix}.bias"),
            dtype: dtype_tag(bt.dtype()),
            shape: bt.shape(),
            data: bt.to_blob()?,
        });
    }
    Ok(())
}

/// Short safetensors dtype tag (`"F32"`, `"F64"`, …).
fn dtype_tag(dt: DType) -> &'static str {
    match dt {
        DType::Float32 => "F32",
        DType::Float64 => "F64",
        other => unreachable!("unexpected parameter dtype {other:?}"),
    }
}

/// Serialize collected blobs into the safetensors byte format.
/// Layout: `[u64 LE header_len][header JSON][padded data blobs]`.
fn serialize(blobs: &[TensorBlob]) -> Result<Vec<u8>> {
    // Data section starts right after the header; offsets are absolute
    // from the start of the data section (the safetensors convention).
    let mut offset = 0usize;
    let mut entries = Vec::with_capacity(blobs.len());
    let mut data = Vec::new();
    for b in blobs {
        let end = offset + b.data.len();
        entries.push(format!(
            "\"{}\":{{\"dtype\":\"{}\",\"shape\":{:?},\"data_offsets\":[{},{}]}}",
            b.name, b.dtype, b.shape, offset, end
        ));
        data.extend_from_slice(&b.data);
        offset = end;
    }
    let header = format!("{{{}}}", entries.join(","));
    // Header length must be a multiple of 8 per spec — pad with spaces.
    let len = header.len();
    let padded = len.div_ceil(8) * 8;
    let mut header_bytes = header.into_bytes();
    header_bytes.resize(padded, b' ');

    let mut out = Vec::with_capacity(8 + padded + data.len());
    out.extend_from_slice(&(padded as u64).to_le_bytes());
    out.extend_from_slice(&header_bytes);
    out.extend_from_slice(&data);
    Ok(out)
}

/// Write a built [`Network`]'s parameters to `path` in safetensors; returns
/// path. Works on CPU/CUDA (blobs copied to host little-endian).
pub fn export_safetensors(net: &Network, path: &Path) -> Result<PathBuf> {
    let blobs = collect_tensors(net)?;
    if blobs.is_empty() {
        return Err(TensorError::new(
            "network has no parameters — nothing to export",
        ));
    }
    let bytes = serialize(&blobs)?;
    std::fs::write(path, bytes)
        .map_err(|e| TensorError::new(&format!("failed to write {}: {e}", path.display())))?;
    Ok(path.to_path_buf())
}

/// Read a safetensors file into `net`'s parameters **in place**. Completeness
/// is enforced: a partial file is rejected, never left at random init.
pub fn load_safetensors(net: &mut Network, path: &Path) -> Result<()> {
    let raw = std::fs::read(path)
        .map_err(|e| TensorError::new(&format!("failed to read {}: {e}", path.display())))?;
    if raw.len() < 8 {
        return Err(TensorError::new("safetensors file too short"));
    }
    let hdr_len = u64::from_le_bytes(raw[..8].try_into().unwrap()) as usize;
    let header: serde_json::Map<String, serde_json::Value> =
        serde_json::from_slice(&raw[8..8 + hdr_len])
            .map_err(|e| TensorError::new(&format!("bad safetensors header: {e}")))?;
    let data_start = 8 + hdr_len;

    let mut copied = 0usize;
    for (idx, layer) in net.layers.iter_mut().enumerate() {
        copied += load_linear(&header, &raw[data_start..], &format!("node{idx}"), layer)?;
    }
    for (node, ports) in net.port_projections.iter_mut().enumerate() {
        for (port, proj) in ports.iter_mut().enumerate() {
            if let Some(linear) = proj {
                copied += load_linear(
                    &header,
                    &raw[data_start..],
                    &format!("proj{node}_{port}_0"),
                    linear,
                )?;
            }
        }
    }
    // Same count as `Network::parameters()`; checked AFTER loading
    // partial file cannot pass.
    use flodl::nn::Module;
    let expected = net.parameters().len();
    if copied != expected {
        return Err(TensorError::new(&format!(
            "incomplete safetensors: {} copied {copied} tensor(s) but the network has {expected} — \
             refusing a partial load (missing weights would silently stay at their fresh init)",
            path.display()
        )));
    }
    Ok(())
}

/// Copy one Linear's weight (+ bias when the layer has one) from the header.
/// Returns the number of tensors copied so the caller can verify coverage.
fn load_linear(
    header: &serde_json::Map<String, serde_json::Value>,
    data: &[u8],
    prefix: &str,
    layer: &mut flodl::nn::Linear,
) -> Result<usize> {
    let mut copied = 0usize;
    let w = header
        .get(&format!("{prefix}.weight"))
        .ok_or_else(|| TensorError::new(&format!("safetensors missing {prefix}.weight")))?;
    copy_entry(w, data, &mut layer.weight.variable)?;
    copied += 1;
    if let Some(bias) = &mut layer.bias {
        let b = header
            .get(&format!("{prefix}.bias"))
            .ok_or_else(|| TensorError::new(&format!("safetensors missing {prefix}.bias")))?;
        copy_entry(b, data, &mut bias.variable)?;
        copied += 1;
    }
    Ok(copied)
}

/// Copy one header entry's blob into a parameter variable, checking shape.
/// tensor is built on CPU then moved to the parameter's device (CUDA-safe).
fn copy_entry(
    entry: &serde_json::Value,
    data: &[u8],
    variable: &mut flodl::Variable,
) -> Result<()> {
    let shape: Vec<usize> = entry["shape"]
        .as_array()
        .ok_or_else(|| TensorError::new("bad tensor entry"))?
        .iter()
        .map(|v| v.as_u64().unwrap_or(0) as usize)
        .collect();
    let [a, b] = [
        entry["data_offsets"][0].as_u64().unwrap_or(0) as usize,
        entry["data_offsets"][1].as_u64().unwrap_or(0) as usize,
    ];
    let blob = data
        .get(a..b)
        .ok_or_else(|| TensorError::new("tensor offsets out of bounds"))?;
    let shape_i64: Vec<i64> = shape.iter().map(|&d| d as i64).collect();
    let t = Tensor::from_blob(blob, &shape_i64, DType::Float32, flodl::tensor::Device::CPU)?;
    let cur = variable.data();
    if cur.shape() != t.shape() {
        return Err(TensorError::new(&format!(
            "shape mismatch: file {:?} vs network {:?}",
            t.shape(),
            cur.shape()
        )));
    }
    // Place the host tensor on the parameter's device (no-op on CPU,
    // crucial step on CUDA — see the doc comment).
    let t = t.to_device(cur.device())?;
    variable.set_data(t);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::network::Network;
    use crate::graph::node::Node;
    use crate::graph::topology::Topology;

    /// A small hand-built graph: input(2) → hidden(4→4) → output(4→1).
    fn small_topo() -> Topology {
        let mut graph = Topology::new(42, None);
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_hidden(1, 1, 1));
        graph.nodes.push(Node::new_output(2, 1, 1));
        graph.refresh_labels();
        graph.finalize();
        graph
    }

    #[test]
    fn safetensors_roundtrip_header_and_blobs() {
        let graph = small_topo();
        let net = Network::build(&graph, flodl::tensor::Device::CPU).unwrap();
        let dir = std::env::temp_dir().join(format!(
            "gras_st_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("test.safetensors");
        export_safetensors(&net, &path).unwrap();

        let raw = std::fs::read(&path).unwrap();
        // 1. Header length prefix: u64 LE, multiple of 8, fits in file.
        let hdr_len = u64::from_le_bytes(raw[..8].try_into().unwrap()) as usize;
        assert_eq!(hdr_len % 8, 0, "header must be 8-aligned");
        assert!(8 + hdr_len < raw.len());

        // 2. Header JSON parses; every entry has F32 dtype + valid offsets.
        let header: serde_json::Map<String, serde_json::Value> =
            serde_json::from_slice(&raw[8..8 + hdr_len]).unwrap();
        assert_eq!(header.len(), 2 * net.layers.len(), "weight+bias per layer");
        for (name, entry) in &header {
            assert!(name.starts_with("node"), "unexpected tensor name {name}");
            assert_eq!(entry["dtype"].as_str().unwrap(), "F32");
            let [a, b] = [
                entry["data_offsets"][0].as_u64().unwrap() as usize,
                entry["data_offsets"][1].as_u64().unwrap() as usize,
            ];
            assert!(b > a);
            assert!(8 + hdr_len + b <= raw.len(), "blob out of bounds");
            // shape numel * 4 == blob length
            let shape: Vec<usize> = entry["shape"]
                .as_array()
                .unwrap()
                .iter()
                .map(|v| v.as_u64().unwrap() as usize)
                .collect();
            assert_eq!(shape.iter().product::<usize>() * 4, b - a);
        }

        // 3. Named tensors exist and shapes are sane.
        assert!(header.contains_key("node0.weight"));
        assert!(header.contains_key("node1.weight"));

        // 4. ROUND-TRIP: load the file back into a rebuilt network
        //    verify parameters are byte-identical to the exported ones.
        let mut net2 = Network::build(&graph, flodl::tensor::Device::CPU).unwrap();
        load_safetensors(&mut net2, &path).unwrap();
        for (l1, l2) in net.layers.iter().zip(net2.layers.iter()) {
            assert_eq!(
                l1.weight.variable.data().to_blob().unwrap(),
                l2.weight.variable.data().to_blob().unwrap()
            );
        }
        std::fs::remove_dir_all(&dir).ok();
    }

    /// A graph with MISMATCHED node dims, so `bridge_diff_dims` creates real
    /// port projections (the shape the old exporter half-saved).
    fn bridged_topo() -> Topology {
        use crate::graph::topology::{Connection, Port};
        let mut graph = Topology::new(7, None);
        let mut input_node = Node::new_input(0, 4);
        input_node.hidden_dim = Some(128); // 4 → 128
        graph.nodes.push(input_node);
        let mut h1 = Node::new_hidden(1, 1, 1);
        h1.hidden_dim = Some(32); // 128 → 32 (a cross-dim bridge)
        graph.nodes.push(h1);
        graph.nodes.push(Node::new_output(2, 1, 1));
        graph.connections.push(Connection {
            from: Port { node: 0, index: 0 },
            to: Port { node: 1, index: 0 },
        });
        graph.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        graph.refresh_labels();
        graph.finalize();
        graph
    }

    #[test]
    fn safetensors_roundtrip_includes_port_projections() {
        let graph = bridged_topo();
        let net = Network::build(&graph, flodl::tensor::Device::CPU).unwrap();
        let dir = std::env::temp_dir().join(format!(
            "gras_st_proj_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("bridged.safetensors");

        use flodl::nn::Module;
        let expected = net.parameters().len();
        // Export must cover EVERY parameter, bridges included.
        export_safetensors(&net, &path).unwrap();
        let raw = std::fs::read(&path).unwrap();
        let hdr_len = u64::from_le_bytes(raw[..8].try_into().unwrap()) as usize;
        let header: serde_json::Map<String, serde_json::Value> =
            serde_json::from_slice(&raw[8..8 + hdr_len]).unwrap();
        assert_eq!(
            header.len(),
            expected,
            "file must carry one entry per parameter tensor (bridges included)"
        );
        assert!(
            header.keys().any(|k| k.starts_with("proj")),
            "a bridged net's file must contain proj* entries; got {:?}",
            header.keys().collect::<Vec<_>>()
        );

        // Round-trip: every parameter (layers AND projections) is restored
        // byte-identically into a freshly built net.
        let mut net2 = Network::build(&graph, flodl::tensor::Device::CPU).unwrap();
        load_safetensors(&mut net2, &path).unwrap();
        for (a, b) in net.parameters().iter().zip(net2.parameters().iter()) {
            assert_eq!(
                a.variable.data().to_blob().unwrap(),
                b.variable.data().to_blob().unwrap(),
                "parameter mismatch after round-trip"
            );
        }

        // A PARTIAL file must be rejected loudly, never silently applied —
        // silence is how a guardrail reported 25/500 on a 500 champion.
        let truncated = dir.join("partial.safetensors");
        let only_header_len = 8 + hdr_len;
        std::fs::write(&truncated, &raw[..only_header_len]).unwrap();
        let mut net3 = Network::build(&graph, flodl::tensor::Device::CPU).unwrap();
        assert!(
            load_safetensors(&mut net3, &truncated).is_err(),
            "a partial safetensors must be rejected, not partially loaded"
        );
        std::fs::remove_dir_all(&dir).ok();
    }
}