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
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
//! Tensor data I/O — the engine's data contract.
//!
//! The engine consumes data as a **path to tensors**: this module owns the
//! tiny binary format used on disk and also reads plain CSV. Since flodl has
//! no built-in `Tensor::save`/`load`, the binary pair is ours end to end:
//!
//! ```text
//!   magic "GRA1" (4 bytes) | dtype tag (1 byte) | ndim (u64 LE)
//!   | shape (ndim × u64 LE) | raw bytes
//! ```
//!
//! Deliberately **dependency-light**: pure `std` + flodl + fastrand (already
//! in the crate), so the library binary stays lean. Real-world dataset
//! producers that need HTTP (e.g. a MNIST downloader) live in `examples/`
//! and use `[dev-dependencies]` instead.

use std::fs;
use std::path::Path;

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

use crate::utils::error::DataError;

/// One input/target pair, ready for the engine: `inputs [n, in_dim]`,
/// `targets [n, out_dim]`. Tensors only — the engine never sees other types.
#[derive(Clone, Debug)]
pub struct Dataset {
    /// Input tensor `[n, in_dim]`.
    pub inputs: Tensor,
    /// Target tensor `[n, out_dim]`.
    pub targets: Tensor,
}

impl Dataset {
    /// Number of samples in the dataset.
    pub fn len(&self) -> usize {
        self.inputs.shape()[0] as usize
    }

    /// True when the dataset holds no samples.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The two widths a topology needs: `(input_dim, output_dim)`; rows are [`Dataset::len`].
    pub fn dims(&self) -> (usize, usize) {
        (
            self.inputs.shape()[1] as usize,
            self.targets.shape()[1] as usize,
        )
    }

    /// Build a dataset from tensors already in memory — the same pair [`load_dataset`] returns,
    /// with no directory in between.
    pub fn from_tensors(inputs: Tensor, targets: Tensor) -> Result<Dataset> {
        let rows = |t: &Tensor| t.shape().first().copied().unwrap_or(0) as usize;
        let (rows_in, rows_out) = (rows(&inputs), rows(&targets));
        if rows_in != rows_out {
            return Err(DataError::RowCountMismatch {
                inputs: rows_in,
                targets: rows_out,
            }
            .into());
        }
        Ok(Dataset { inputs, targets })
    }

    /// Cast both tensors to `Float32` (flodl's workhorse dtype) so a dataset
    /// written in another dtype is normalized once, up front.
    pub fn to_f32(&self) -> Result<Dataset> {
        self.to_dtype(DType::Float32)
    }

    /// Cast both tensors to the given dtype if they aren't already.
    /// The engine calls this on load to match the network's dtype.
    pub fn to_dtype(&self, dtype: DType) -> Result<Dataset> {
        let cast = |t: &Tensor| -> Result<Tensor> {
            if t.dtype() == dtype {
                Ok(t.clone())
            } else {
                t.to_dtype(dtype)
            }
        };
        Ok(Dataset {
            inputs: cast(&self.inputs)?,
            targets: cast(&self.targets)?,
        })
    }

    /// Move both tensors to the given device.
    /// The engine calls this on load to place data on CUDA when needed.
    pub fn to_device(&self, device: Device) -> Result<Dataset> {
        let transfer = |t: &Tensor| -> Result<Tensor> {
            if t.device() == device {
                Ok(t.clone())
            } else {
                let data = t.to_f32_vec()?;
                Tensor::from_f32(&data, &t.shape(), device)
            }
        };
        Ok(Dataset {
            inputs: transfer(&self.inputs)?,
            targets: transfer(&self.targets)?,
        })
    }

    /// Row-concatenate two datasets (`self` rows first) — shared dims/device —
    /// used by the explicit train/test layout to build pools by construction.
    pub fn concat(&self, other: &Dataset) -> Result<Dataset> {
        Ok(Dataset {
            inputs: Tensor::cat_many(&[&self.inputs, &other.inputs], 0)?,
            targets: Tensor::cat_many(&[&self.targets, &other.targets], 0)?,
        })
    }
}

// ── the binary tensor format ─────────────────────────────────────────────

/// Magic bytes at the start of every tensor file written by this module.
const MAGIC: &[u8; 4] = b"GRA1";

/// Single-byte dtype tags in the header.
const TAG_F32: u8 = 0;
/// Binary tag byte for Float64 tensors.
const TAG_F64: u8 = 1;
/// Binary tag byte for Int64 tensors.
const TAG_I64: u8 = 2;

/// Map a `DType` to its binary tag byte.
fn dtype_tag(dtype: DType) -> std::result::Result<u8, DataError> {
    match dtype {
        DType::Float32 => Ok(TAG_F32),
        DType::Float64 => Ok(TAG_F64),
        DType::Int64 => Ok(TAG_I64),
        other => Err(DataError::UnsupportedDtype(format!(
            "{other:?} for tensor file (use Float32/Float64/Int64)"
        ))),
    }
}

/// Map a binary tag byte back to a `DType`.
fn tag_dtype(tag: u8) -> std::result::Result<DType, DataError> {
    match tag {
        TAG_F32 => Ok(DType::Float32),
        TAG_F64 => Ok(DType::Float64),
        TAG_I64 => Ok(DType::Int64),
        other => Err(DataError::UnknownDtypeTag(other)),
    }
}

/// Byte width of one element of `dtype`.
fn elem_size(dtype: DType) -> usize {
    match dtype {
        DType::Float32 => 4,
        DType::Float64 => 8,
        DType::Int64 => 8,
        _ => 0,
    }
}

/// Write a tensor to `path` in the gras binary format (see the module docs).
pub fn save_tensor(path: &Path, t: &Tensor) -> Result<()> {
    let dtype = t.dtype();
    let tag = dtype_tag(dtype)?;
    let shape = t.shape();
    let blob = t.to_blob()?;
    let mut out: Vec<u8> = Vec::with_capacity(8 + 8 + shape.len() * 8 + blob.len());
    out.extend_from_slice(MAGIC);
    out.push(tag);
    out.extend_from_slice(&(shape.len() as u64).to_le_bytes());
    for &d in &shape {
        out.extend_from_slice(&(d as u64).to_le_bytes());
    }
    out.extend_from_slice(&blob);
    fs::write(path, out).map_err(|source| DataError::Io {
        path: path.display().to_string(),
        source,
    })?;
    Ok(())
}

/// Read a tensor written by [`save_tensor`].
pub fn load_tensor(path: &Path) -> Result<Tensor> {
    let path_str = path.display().to_string();
    let bytes = fs::read(path).map_err(|source| DataError::Io {
        path: path_str.clone(),
        source,
    })?;
    if bytes.len() < 9 || &bytes[..4] != MAGIC {
        return Err(DataError::BadMagic { path: path_str }.into());
    }
    let dtype = tag_dtype(bytes[4])?;
    let mut off = 5usize;
    let read_u64 = |off: &mut usize| -> std::result::Result<u64, DataError> {
        if *off + 8 > bytes.len() {
            return Err(DataError::Truncated("tensor header".to_string()));
        }
        let v = u64::from_le_bytes(bytes[*off..*off + 8].try_into().unwrap());
        *off += 8;
        Ok(v)
    };
    let ndim = read_u64(&mut off)? as usize;
    let mut shape = Vec::with_capacity(ndim);
    for _ in 0..ndim {
        shape.push(read_u64(&mut off)? as i64);
    }
    let numel: i64 = shape.iter().product();
    let expected = (numel as usize) * elem_size(dtype);
    if off + expected != bytes.len() {
        return Err(DataError::SizeMismatch {
            path: path_str,
            expected,
            found: bytes.len() - off,
        }
        .into());
    }
    Tensor::from_blob(&bytes[off..], &shape, dtype, Device::CPU)
}

// ── datasets ─────────────────────────────────────────────────────────────

/// On-disk format for [`save_dataset_as`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DataFormat {
    /// flodl-native binary tensors (`inputs.bin` + `targets.bin` + `meta.json`):
    /// lossless and fast — the engine's native format.
    Bin,
    /// Plain-text floats (`inputs.csv` + `targets.csv`, 6-decimal precision):
    /// human-inspectable and portable, lossy for full f32 precision.
    Csv,
    /// Write **both** formats into `dir`, so the same dataset is usable
    /// by tools that only read one or the other.
    Both,
}

/// Save a dataset in the requested format — one-stop over [`save_dataset`] (`.bin`)
/// and [`save_csv_dataset`] (`.csv`); `Both` writes all four files.
pub fn save_dataset_as(dir: impl AsRef<Path>, ds: &Dataset, format: DataFormat) -> Result<()> {
    // `impl AsRef<Path>` is an owned generic — normalize to `&Path` ONCE up front
    // and reuse the borrow.
    let dir = dir.as_ref();
    match format {
        DataFormat::Bin => save_dataset(dir, ds),
        DataFormat::Csv => save_csv_dataset(dir, &ds.inputs, &ds.targets),
        DataFormat::Both => {
            save_dataset(dir, ds)?;
            save_csv_dataset(dir, &ds.inputs, &ds.targets)
        }
    }
}

/// Load a dataset written in **either** format — looks for `inputs.bin` first,
/// then `inputs.csv`; no CSV→bin caching. Read-side counterpart of `save_dataset_as`.
pub fn load_dataset_auto(dir: impl AsRef<Path>) -> Result<Dataset> {
    let dir = dir.as_ref();
    if dir.join("inputs.bin").exists() {
        return load_dataset(dir);
    }
    if dir.join("inputs.csv").exists() {
        return load_csv_dataset(dir);
    }
    Err(DataError::Io {
        path: dir.display().to_string(),
        source: std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("no inputs.bin or inputs.csv found in {}", dir.display()),
        ),
    }
    .into())
}

/// Save a dataset into `dir` as `inputs.bin` + `targets.bin`, plus a human-readable `meta.json` carrying the tensor shapes (informational: nothing reads it back).
pub fn save_dataset(dir: impl AsRef<Path>, ds: &Dataset) -> Result<()> {
    let dir = dir.as_ref();
    fs::create_dir_all(dir).map_err(|source| DataError::Io {
        path: dir.display().to_string(),
        source,
    })?;
    save_tensor(&dir.join("inputs.bin"), &ds.inputs)?;
    save_tensor(&dir.join("targets.bin"), &ds.targets)?;
    let meta = serde_json::json!({
        "inputs_shape": ds.inputs.shape(),
        "targets_shape": ds.targets.shape(),
    });
    let meta = serde_json::to_string_pretty(&meta)
        .map_err(|e| DataError::Json(format!("meta.json: {e}")))?;
    fs::write(dir.join("meta.json"), meta).map_err(|source| DataError::Io {
        path: dir.join("meta.json").display().to_string(),
        source,
    })?;
    Ok(())
}

/// Load a dataset written by [`save_dataset`]. `impl AsRef<Path>` accepts
/// `&str`/`String`/`PathBuf` directly (`load_dataset("data/mnist")`).
pub fn load_dataset(dir: impl AsRef<Path>) -> Result<Dataset> {
    let dir = dir.as_ref();
    let inputs = load_tensor(&dir.join("inputs.bin"))?;
    let targets = load_tensor(&dir.join("targets.bin"))?;
    Ok(Dataset { inputs, targets })
}

/// Auto-detect the format: `flodl_data/inputs.bin`, then `inputs.bin`,
/// `inputs.csv` (converted + cached). Errors loudly — no synthetic fallback.
pub fn resolve_dataset(dir: impl AsRef<Path>) -> Result<Dataset> {
    resolve_inputs_targets_datasets(dir)
}

/// Resolve a **single-pool** dataset dir (`inputs.csv|bin` + `targets.csv|bin`),
/// caching CSV→bin under `<dir>/flodl_data/`. No synthetic fallback.
pub fn resolve_inputs_targets_datasets(dir: impl AsRef<Path>) -> Result<Dataset> {
    let dir = dir.as_ref();
    let cache_dir = dir.join("flodl_data");

    // Priority 1: cached .bin
    if cache_dir.join("inputs.bin").exists() {
        return load_dataset(&cache_dir);
    }

    // Priority 2: .bin in dir
    if dir.join("inputs.bin").exists() {
        return load_dataset(dir);
    }

    // Priority 3: CSV → convert → cache
    if dir.join("inputs.csv").exists() {
        let dataset = load_csv_dataset(dir)?;
        std::fs::create_dir_all(&cache_dir)
            .map_err(|e| flodl::tensor::TensorError::new(&e.to_string()))?;
        save_dataset(&cache_dir, &dataset)?;
        return Ok(dataset);
    }

    Err(DataError::Io {
        path: dir.display().to_string(),
        source: std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!(
                "no dataset found in {} — expected inputs.csv|bin + targets.csv|bin (or train/ + test/ subdirs for resolve_train_test_datasets)",
                dir.display()
            ),
        ),
    }
    .into())
}

/// Resolve a **two-split** dataset dir (`train/` + `test/`), each
/// `inputs.csv|bin` + `targets.csv|bin`; returns two independent datasets.
pub fn resolve_train_test_datasets(dir: impl AsRef<Path>) -> Result<(Dataset, Dataset)> {
    resolve_two_splits(dir.as_ref(), "train", "test")
}

/// Resolve a **`train/` + `val/`** dir: `train/` learns, `val/` is the pool the race RANKS
/// on; a sibling `test/` is report-only.
pub fn resolve_train_val_datasets(dir: impl AsRef<Path>) -> Result<(Dataset, Dataset)> {
    resolve_two_splits(dir.as_ref(), "train", "val")
}

/// The shared two-role resolver: `learn/` and `rank/`, dims checked to agree.
fn resolve_two_splits(dir: &Path, learn: &str, rank: &str) -> Result<(Dataset, Dataset)> {
    let learn_dir = dir.join(learn);
    let rank_dir = dir.join(rank);
    for sub in [&learn_dir, &rank_dir] {
        if !sub.exists() {
            let name = sub.file_name().and_then(|s| s.to_str()).unwrap_or("?");
            return Err(DataError::Io {
                path: sub.display().to_string(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    format!(
                        "missing '{name}/' split in {dir} — a two-role layout needs {dir}/{learn}/ and {dir}/{rank}/ each with inputs.csv|bin + targets.csv|bin",
                        dir = dir.display(),
                    ),
                ),
            }
            .into());
        }
    }
    let learn_ds = resolve_inputs_targets_datasets(&learn_dir)?;
    let rank_ds = resolve_inputs_targets_datasets(&rank_dir)?;
    // Feature/target dims must agree across splits — a dim mismatch would
    // surface later as a cryptic shape error mid-step.
    let (li, ri) = (learn_ds.inputs.shape()[1], rank_ds.inputs.shape()[1]);
    if li != ri {
        return Err(DataError::Csv(format!(
            "feature dim mismatch: {learn}/ inputs have {li} columns, {rank}/ inputs have {ri}"
        ))
        .into());
    }
    let (lt, rt) = (learn_ds.targets.shape()[1], rank_ds.targets.shape()[1]);
    if lt != rt {
        return Err(DataError::Csv(format!(
            "target dim mismatch: {learn}/ targets have {lt} columns, {rank}/ targets have {rt}"
        ))
        .into());
    }
    Ok((learn_ds, rank_ds))
}

/// Which roles a dataset dir supplies, decided by its SUBDIRECTORIES and nothing else
/// (no config flag, no setter): the layout on disk is the contract.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PoolLayout {
    /// One pool (`inputs.csv|bin` + `targets.csv|bin`): the engine splits
    /// `eval_share`, so there is no held-out number beyond that split.
    Single,
    /// `train/` + `val/` — train learns, **val ranks**, and a sibling `test/`
    /// report-only exam.
    TrainVal,
    /// `train/` + `test/` — the pre-2026-11-02 layout: `test/` is the pool the race
    /// ranks on, and only a separate `exam/` is untouched.
    TrainTest,
}

impl PoolLayout {
    /// The subdirectory whose rows the race ranks on; `None` = a seeded slice of one
    /// pool. This is what `engine.json → eval_split` records.
    pub fn eval_dir(self) -> Option<&'static str> {
        match self {
            Self::TrainVal => Some("val"),
            Self::TrainTest => Some("test"),
            Self::Single => None,
        }
    }
}

/// Read the layout off the directory. Refusals are by NAME: a `val/` with nothing
/// learn from, or three role dirs where one of them would be read by nobody.
pub fn detect_pool_layout(dir: impl AsRef<Path>) -> Result<PoolLayout> {
    let dir = dir.as_ref();
    let has = |name: &str| dir.join(name).exists();
    let (train, val, test, exam) = (has("train"), has("val"), has("test"), has("exam"));
    match (train, val, test) {
        (true, true, true) if exam => Err(DataError::Csv(format!(
            "{dir} holds `val/`, `test/` AND `exam/`: with `val/` ranking, `test/` would already be the \
             report-only exam, so the second exam store could never be read. Keep `train/` + `val/` + \
             `test/` (test is the exam) or `train/` + `val/` + `exam/`, not all four",
            dir = dir.display()
        ))
        .into()),
        (true, true, _) => Ok(PoolLayout::TrainVal),
        (true, false, true) => Ok(PoolLayout::TrainTest),
        (false, true, _) => Err(DataError::Csv(format!(
            "{dir} has `val/` but no `train/` — the val pool RANKS, it never trains, so there is \
             nothing to learn from",
            dir = dir.display()
        ))
        .into()),
        (false, false, true) => Err(DataError::Csv(format!(
            "{dir} has `test/` but no `train/` — add `train/`, or make this dir the pool itself \
             (inputs.csv|bin + targets.csv|bin)",
            dir = dir.display()
        ))
        .into()),
        _ => Ok(PoolLayout::Single),
    }
}

/// Where the EXAM rows live for a layout, or `None` when nothing is held out.
pub fn exam_dir(dir: &Path, layout: PoolLayout) -> Option<std::path::PathBuf> {
    let exam = dir.join("exam");
    if exam.exists() {
        return Some(exam);
    }
    match layout {
        PoolLayout::TrainVal if dir.join("test").exists() => Some(dir.join("test")),
        _ => None,
    }
}

/// Load a dataset from CSV files (`inputs.csv` + `targets.csv`): one sample per
/// line; headers and `#` comments are skipped.
pub fn load_csv_dataset(dir: impl AsRef<Path>) -> Result<Dataset> {
    let dir = dir.as_ref();
    let inputs_path = dir.join("inputs.csv");
    let targets_path = dir.join("targets.csv");

    if !inputs_path.exists() {
        return Err(DataError::Io {
            path: inputs_path.display().to_string(),
            source: std::io::Error::new(std::io::ErrorKind::NotFound, "inputs.csv not found"),
        }
        .into());
    }
    if !targets_path.exists() {
        return Err(DataError::Io {
            path: targets_path.display().to_string(),
            source: std::io::Error::new(std::io::ErrorKind::NotFound, "targets.csv not found"),
        }
        .into());
    }

    let inputs_raw = std::fs::read_to_string(&inputs_path).map_err(|e| DataError::Io {
        path: inputs_path.display().to_string(),
        source: e,
    })?;
    let targets_raw = std::fs::read_to_string(&targets_path).map_err(|e| DataError::Io {
        path: targets_path.display().to_string(),
        source: e,
    })?;

    // Parse inputs CSV (skip header if present)
    let mut inputs_flat: Vec<f32> = Vec::new();
    let mut input_dim: Option<usize> = None;
    let mut n_samples: usize = 0;
    let mut skipped_header = false;
    for line in inputs_raw.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        // Try to parse as floats — if first non-empty line fails, treat as header
        let row: Vec<f32> = match line
            .split(',')
            .map(|s| s.trim().parse::<f32>())
            .collect::<std::result::Result<Vec<_>, _>>()
        {
            Ok(row) => row,
            Err(e) => {
                if n_samples == 0 && !skipped_header {
                    skipped_header = true;
                    tracing::debug!("inputs.csv: skipping header row: {line}");
                    continue;
                }
                return Err(DataError::Csv(format!("inputs.csv parse error: {e}")).into());
            }
        };
        if let Some(dim) = input_dim {
            if row.len() != dim {
                return Err(DataError::Csv(format!(
                    "inputs.csv: row {n_samples} has {} columns, expected {dim}",
                    row.len()
                ))
                .into());
            }
        } else {
            input_dim = Some(row.len());
        }
        inputs_flat.extend(row);
        n_samples += 1;
    }
    let input_dim = input_dim.ok_or_else(|| DataError::Csv("inputs.csv is empty".into()))?;

    // Parse targets CSV (skip header if present)
    let mut targets_flat: Vec<f32> = Vec::new();
    let mut target_dim: Option<usize> = None;
    let mut n_targets: usize = 0;
    let mut skipped_header = false;
    for line in targets_raw.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        // Try to parse as floats — if first non-empty line fails, treat as header
        let row: Vec<f32> = match line
            .split(',')
            .map(|s| s.trim().parse::<f32>())
            .collect::<std::result::Result<Vec<_>, _>>()
        {
            Ok(row) => row,
            Err(e) => {
                if n_targets == 0 && !skipped_header {
                    skipped_header = true;
                    tracing::debug!("targets.csv: skipping header row: {line}");
                    continue;
                }
                return Err(DataError::Csv(format!("targets.csv parse error: {e}")).into());
            }
        };
        if let Some(dim) = target_dim {
            if row.len() != dim {
                return Err(DataError::Csv(format!(
                    "targets.csv: row {n_targets} has {} columns, expected {dim}",
                    row.len()
                ))
                .into());
            }
        } else {
            target_dim = Some(row.len());
        }
        targets_flat.extend(row);
        n_targets += 1;
    }
    let target_dim = target_dim.ok_or_else(|| DataError::Csv("targets.csv is empty".into()))?;

    // Validate sample counts match
    if n_samples != n_targets {
        return Err(DataError::Csv(format!(
            "sample count mismatch: inputs has {n_samples}, targets has {n_targets}"
        ))
        .into());
    }

    let inputs = Tensor::from_f32(
        &inputs_flat,
        &[n_samples as i64, input_dim as i64],
        Device::CPU,
    )?;
    let targets = Tensor::from_f32(
        &targets_flat,
        &[n_targets as i64, target_dim as i64],
        Device::CPU,
    )?;

    Ok(Dataset { inputs, targets })
}

/// Save tensors as CSV files (`inputs.csv` + `targets.csv`), one sample per line,
/// values comma-separated.
pub fn save_csv_dataset(dir: impl AsRef<Path>, inputs: &Tensor, targets: &Tensor) -> Result<()> {
    let dir = dir.as_ref();
    fs::create_dir_all(dir).map_err(|source| DataError::Io {
        path: dir.display().to_string(),
        source,
    })?;

    let in_data = inputs
        .to_f32_vec()
        .map_err(|e| DataError::Csv(format!("inputs to_f32_vec: {e}")))?;
    let tgt_data = targets
        .to_f32_vec()
        .map_err(|e| DataError::Csv(format!("targets to_f32_vec: {e}")))?;
    let in_shape = inputs.shape();
    let tgt_shape = targets.shape();
    let (n_in, dim_in) = (in_shape[0] as usize, in_shape[1] as usize);
    let (n_tgt, dim_tgt) = (tgt_shape[0] as usize, tgt_shape[1] as usize);

    // Write inputs.csv
    let mut inputs_csv = String::with_capacity(n_in * dim_in * 8);
    for row in 0..n_in {
        let start = row * dim_in;
        let line: Vec<String> = (0..dim_in)
            .map(|c| format!("{:.6}", in_data[start + c]))
            .collect();
        inputs_csv.push_str(&line.join(","));
        inputs_csv.push('\n');
    }
    fs::write(dir.join("inputs.csv"), inputs_csv).map_err(|source| DataError::Io {
        path: dir.join("inputs.csv").display().to_string(),
        source,
    })?;

    // Write targets.csv
    let mut targets_csv = String::with_capacity(n_tgt * dim_tgt * 8);
    for row in 0..n_tgt {
        let start = row * dim_tgt;
        let line: Vec<String> = (0..dim_tgt)
            .map(|c| format!("{:.6}", tgt_data[start + c]))
            .collect();
        targets_csv.push_str(&line.join(","));
        targets_csv.push('\n');
    }
    fs::write(dir.join("targets.csv"), targets_csv).map_err(|source| DataError::Io {
        path: dir.join("targets.csv").display().to_string(),
        source,
    })?;

    Ok(())
}

/// Test-only synthetic classification dataset: random inputs, one-hot targets —
/// keeps unit fixtures download-free without widening the public API.
#[cfg(test)]
pub(crate) fn synthetic_classification(
    n: usize,
    in_dim: usize,
    out_dim: usize,
    seed: u64,
    device: Device,
) -> Result<Dataset> {
    let mut rng = fastrand::Rng::with_seed(seed);
    let inputs: Vec<f32> = (0..n * in_dim).map(|_| rng.f32()).collect();
    let inputs = Tensor::from_f32(&inputs, &[n as i64, in_dim as i64], device)?;
    let mut targets = vec![0.0f32; n * out_dim];
    for row in 0..n {
        let c = rng.usize(0..out_dim);
        targets[row * out_dim + c] = 1.0;
    }
    let targets = Tensor::from_f32(&targets, &[n as i64, out_dim as i64], device)?;
    Ok(Dataset { inputs, targets })
}

/// One-hot encode class indices: `indices: Vec<usize>` → `[n, num_classes]` tensor.
pub fn one_hot(indices: &[usize], num_classes: usize, device: Device) -> Result<Tensor> {
    let n = indices.len();
    let mut data = vec![0.0f32; n * num_classes];
    for (i, &c) in indices.iter().enumerate() {
        data[i * num_classes + c] = 1.0;
    }
    Tensor::from_f32(&data, &[n as i64, num_classes as i64], device)
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;
    use std::path::PathBuf;

    fn temp_dir() -> PathBuf {
        std::env::temp_dir().join(format!("gras_data_test_{}", fastrand::u64(..)))
    }

    #[test]
    fn test_tensor_roundtrip() {
        let dir = temp_dir();
        std::fs::create_dir_all(&dir).unwrap();
        let t = Tensor::from_f32(&[1.0, 2.0, 3.0, 4.0], &[2, 2], Device::CPU).unwrap();
        let path = dir.join("t.bin");
        save_tensor(&path, &t).unwrap();
        let loaded = load_tensor(&path).unwrap();
        assert_eq!(loaded.shape(), t.shape());
        assert_eq!(loaded.to_f32_vec().unwrap(), t.to_f32_vec().unwrap());
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The in-memory constructor takes the same pair the loaders produce,
    /// refuses the one shape the engine cannot use.
    #[test]
    fn from_tensors_accepts_matching_rows_and_rejects_a_mismatch() {
        let inputs = || Tensor::from_f32(&[1.0, 2.0, 3.0, 4.0], &[2, 2], Device::CPU).unwrap();
        let targets = Tensor::from_f32(&[1.0, 0.0], &[2, 1], Device::CPU).unwrap();
        let ds = Dataset::from_tensors(inputs(), targets).unwrap();
        assert_eq!(ds.len(), 2);
        assert_eq!(ds.inputs.shape(), &[2, 2]);
        assert_eq!(ds.targets.shape(), &[2, 1]);

        // 2 input rows against 1 target row: the mismatch `meta.json` catches
        // for an on-disk dataset, refused here for an in-memory one.
        let short = Tensor::from_f32(&[1.0], &[1, 1], Device::CPU).unwrap();
        let msg = Dataset::from_tensors(inputs(), short)
            .unwrap_err()
            .to_string();
        assert!(
            msg.contains("row count") && msg.contains('2') && msg.contains('1'),
            "the mismatch error names both row counts, got: {msg}"
        );
    }

    #[test]
    fn test_dataset_roundtrip() {
        let dir = temp_dir();
        let inputs = Tensor::from_f32(&[1.0, 2.0, 3.0, 4.0], &[2, 2], Device::CPU).unwrap();
        let targets = Tensor::from_f32(&[5.0, 6.0, 7.0, 8.0], &[2, 2], Device::CPU).unwrap();
        let ds = Dataset { inputs, targets };
        save_dataset(&dir, &ds).unwrap();
        let loaded = load_dataset(&dir).unwrap();
        assert_eq!(loaded.inputs.shape(), ds.inputs.shape());
        assert_eq!(loaded.targets.shape(), ds.targets.shape());
        assert_eq!(
            loaded.inputs.to_f32_vec().unwrap(),
            ds.inputs.to_f32_vec().unwrap()
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_load_tensor_rejects_garbage() {
        let dir = temp_dir();
        let path = dir.join("bad.bin");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(&path, b"not a gras tensor").unwrap();
        assert!(load_tensor(&path).is_err());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_csv_roundtrip() {
        let dir = temp_dir();
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("inputs.csv"), "1.0,2.0\n3.0,4.0\n5.0,6.0\n").unwrap();
        std::fs::write(dir.join("targets.csv"), "0.0\n1.0\n0.0\n").unwrap();
        let ds = load_csv_dataset(&dir).unwrap();
        assert_eq!(ds.inputs.shape(), &[3, 2]);
        assert_eq!(ds.targets.shape(), &[3, 1]);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_csv_with_header() {
        let dir = temp_dir();
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("inputs.csv"), "feat1,feat2\n1.0,2.0\n3.0,4.0\n").unwrap();
        std::fs::write(dir.join("targets.csv"), "label\n0.0\n1.0\n").unwrap();
        let ds = load_csv_dataset(&dir).unwrap();
        assert_eq!(ds.inputs.shape(), &[2, 2]);
        assert_eq!(ds.targets.shape(), &[2, 1]);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_csv_sample_count_mismatch() {
        let dir = temp_dir();
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("inputs.csv"), "1.0,2.0\n3.0,4.0\n5.0,6.0\n").unwrap();
        std::fs::write(dir.join("targets.csv"), "0.0\n1.0\n").unwrap(); // only 2 rows
        let result = load_csv_dataset(&dir);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("sample count mismatch"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_csv_skips_comments() {
        let dir = temp_dir();
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("inputs.csv"),
            "# header comment\n1.0,2.0\n3.0,4.0\n",
        )
        .unwrap();
        std::fs::write(dir.join("targets.csv"), "# another comment\n0.0\n1.0\n").unwrap();
        let ds = load_csv_dataset(&dir).unwrap();
        assert_eq!(ds.inputs.shape(), &[2, 2]);
        let _ = std::fs::remove_dir_all(&dir);
    }

    // ── convenience helpers ───────────────────────────────────────────────

    /// `save_dataset_as` writes what the matching `load_dataset_auto` reads,
    /// in every format (bin-only dirs, csv-only dirs, both).
    #[test]
    fn test_save_dataset_as_roundtrip_all_formats() {
        let mut rng = fastrand::Rng::with_seed(7);
        let data: Vec<f32> = (0..24).map(|_| rng.f32()).collect();
        let ds = Dataset {
            inputs: Tensor::from_f32(&data, &[8, 3], Device::CPU).unwrap(),
            targets: Tensor::from_f32(
                &[0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0],
                &[8, 1],
                Device::CPU,
            )
            .unwrap(),
        };

        for fmt in [DataFormat::Bin, DataFormat::Csv, DataFormat::Both] {
            let dir = std::env::temp_dir().join(format!("gras_data_fmt_{:?}", fmt));
            let _ = std::fs::remove_dir_all(&dir);
            save_dataset_as(&dir, &ds, fmt).unwrap();
            // Whatever was written, the auto-loader must read it back.
            let loaded = load_dataset_auto(&dir).unwrap();
            assert_eq!(loaded.inputs.shape(), ds.inputs.shape());
            assert_eq!(loaded.targets.shape(), ds.targets.shape());
            let _ = std::fs::remove_dir_all(&dir);
        }

        // Both writes bin + csv into the same dir.
        let dir = std::env::temp_dir().join("gras_data_fmt_Both_files");
        let _ = std::fs::remove_dir_all(&dir);
        save_dataset_as(&dir, &ds, DataFormat::Both).unwrap();
        assert!(dir.join("inputs.bin").exists(), "Bin part of Both");
        assert!(dir.join("inputs.csv").exists(), "Csv part of Both");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// `load_dataset_auto` prefers .bin when both formats are present.
    #[test]
    fn test_load_dataset_auto_prefers_bin() {
        let mut rng = fastrand::Rng::with_seed(11);
        let data: Vec<f32> = (0..16).map(|_| rng.f32()).collect();
        let ds = Dataset {
            inputs: Tensor::from_f32(&data, &[8, 2], Device::CPU).unwrap(),
            targets: Tensor::from_f32(&data, &[8, 2], Device::CPU).unwrap(),
        };
        let dir = std::env::temp_dir().join("gras_data_auto_prefer");
        let _ = std::fs::remove_dir_all(&dir);
        save_dataset_as(&dir, &ds, DataFormat::Both).unwrap();
        let loaded = load_dataset_auto(&dir).unwrap();
        // .bin is exact f32; .csv would have rounded to 6 decimals — check
        // a value that exposes rounding if the CSV were picked.
        assert_eq!(loaded.inputs.to_f32_vec().unwrap(), data, "must load .bin");
        let _ = std::fs::remove_dir_all(&dir);
    }

    // ── property tests ────────────────────────────────────────────────────

    proptest! {
        /// Any Float32 tensor round-trips through the binary format
        /// losslessly: same shape, same values, same dtype.
        #[test]
        fn prop_tensor_roundtrip(
            rows in 1usize..8,
            cols in 1usize..8,
            seed in 0u64..1_000_000,
        ) {
            let mut rng = fastrand::Rng::with_seed(seed);
            let data: Vec<f32> = (0..rows * cols).map(|_| rng.f32()).collect();
            let t = Tensor::from_f32(&data, &[rows as i64, cols as i64], Device::CPU).unwrap();
            let dir = temp_dir();
            std::fs::create_dir_all(&dir).unwrap();
            let path = dir.join("t.bin");
            save_tensor(&path, &t).unwrap();
            let loaded = load_tensor(&path).unwrap();
            prop_assert_eq!(loaded.shape(), t.shape());
            prop_assert_eq!(loaded.dtype(), t.dtype());
            prop_assert_eq!(loaded.to_f32_vec().unwrap(), t.to_f32_vec().unwrap());
            let _ = std::fs::remove_dir_all(&dir);
        }
    }
}