gras 0.1.13

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
//! Tensor data I/O — the engine's data contract.
//!
//! The engine consumes data as a **path to tensors** (flodl-native; this
//! crate deals with no other data formats). Since flodl has no built-in
//! `Tensor::save`/`load`, this module owns the tiny binary tensor format
//! used on disk:
//!
//! ```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 (all
//! 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 data
/// types.
#[derive(Clone, Debug)]
pub struct Dataset {
    pub inputs: Tensor,
    pub targets: Tensor,
}

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

    /// Cast both tensors to `Float32` if they aren't already — flodl's
    /// native workhorse dtype and this crate's default precision. The
    /// engine calls this on load, so a dataset written in another dtype
    /// (e.g. Float64) 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)?,
        })
    }
}

// ── 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;
const TAG_F64: u8 = 1;
const TAG_I64: u8 = 2;

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)"
        ))),
    }
}

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)),
    }
}

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` + a
    /// human-readable `meta.json`). Lossless and fast to load — 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 — the one-stop convenience
/// over [`save_dataset`] (`.bin`) and [`save_csv_dataset`] (`.csv`).
/// With [`DataFormat::Both`] the directory ends up with `inputs.bin` +
/// `targets.bin` + `inputs.csv` + `targets.csv`.
pub fn save_dataset_as(dir: &Path, ds: &Dataset, format: DataFormat) -> Result<()> {
    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 — the read-side counterpart
/// of [`save_dataset_as`]. Looks for `inputs.bin` (native) first, then
/// `inputs.csv`; errors if the directory holds neither. Unlike
/// [`resolve_dataset`] it does no CSV→bin caching — pure "read what's
/// there".
pub fn load_dataset_auto(dir: &Path) -> Result<Dataset> {
    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` with the tensor shapes (informational only).
pub fn save_dataset(dir: &Path, ds: &Dataset) -> Result<()> {
    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`].
pub fn load_dataset(dir: &Path) -> Result<Dataset> {
    let inputs = load_tensor(&dir.join("inputs.bin"))?;
    let targets = load_tensor(&dir.join("targets.bin"))?;
    Ok(Dataset { inputs, targets })
}

/// Auto-detect data format: .bin (cached or direct) or .csv (converts to .bin).
///
/// Priority:
/// 1. `{dir}/flodl_data/inputs.bin` (cached .bin)
/// 2. `{dir}/inputs.bin` (direct .bin)
/// 3. `{dir}/inputs.csv` → convert → cache in `{dir}/flodl_data/`
pub fn resolve_dataset(dir: &Path) -> Result<Dataset> {
    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 inputs.bin or inputs.csv found in {}", dir.display()),
        ),
    }
    .into())
}

/// Load a dataset from CSV files (`inputs.csv` + `targets.csv`).
///
/// CSV format: one sample per line, comma-separated floats.
/// Headers are auto-detected (skipped if first row contains non-numeric values).
/// Lines starting with `#` are treated as comments and skipped.
/// All data rows must have the same number of columns.
pub fn load_csv_dataset(dir: &Path) -> Result<Dataset> {
    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;
                    log::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;
                    log::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`).
///
/// Each row is one sample, values comma-separated.
pub fn save_csv_dataset(dir: &Path, inputs: &Tensor, targets: &Tensor) -> Result<()> {
    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(())
}

/// Generate a synthetic classification dataset: random inputs `[n, in_dim]`
/// and one-hot targets `[n, out_dim]` (each row sums to 1). Quick stand-in
/// for MNIST or any categorical task — no download needed.
pub 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 })
}

/// Synthetic sine wave: `y = sin(2πx)`, `x ∈ [-1, 1]`. Returns `(inputs, targets)` tensors.
pub fn make_sine(n: usize) -> (Tensor, Tensor) {
    let mut rng = fastrand::Rng::with_seed(42);
    let inputs: Vec<f32> = (0..n).map(|_| rng.f32() * 2.0 - 1.0).collect();
    let targets: Vec<f32> = inputs.iter().map(|x| (x * std::f32::consts::TAU).sin()).collect();
    let inputs = Tensor::from_f32(&inputs, &[n as i64, 1], Device::CPU).unwrap();
    let targets = Tensor::from_f32(&targets, &[n as i64, 1], Device::CPU).unwrap();
    (inputs, targets)
}

/// Synthetic XOR: 2 features, 2 classes (one-hot `[n, 2]`). Returns `(inputs, targets)` tensors.
pub fn make_xor(n: usize) -> (Tensor, Tensor) {
    let mut rng = fastrand::Rng::with_seed(42);
    let mut inputs = Vec::with_capacity(n * 2);
    let mut targets = Vec::with_capacity(n * 2);
    for _ in 0..n {
        let a = rng.f32();
        let b = rng.f32();
        inputs.push(a);
        inputs.push(b);
        let xor = if (a > 0.5) ^ (b > 0.5) { 1.0 } else { 0.0 };
        targets.push(xor);
        targets.push(1.0 - xor);
    }
    let inputs = Tensor::from_f32(&inputs, &[n as i64, 2], Device::CPU).unwrap();
    let targets = Tensor::from_f32(&targets, &[n as i64, 2], Device::CPU).unwrap();
    (inputs, targets)
}

/// Split a dataset length into train and eval index vectors.
/// Returns `(train_indices, eval_indices)`.
pub fn split_indices(
    len: usize,
    train_ratio: f32,
    eval_ratio: f32,
    seed: u64,
) -> (Vec<i64>, Vec<i64>) {
    assert!((train_ratio + eval_ratio - 1.0).abs() < 1e-6, "ratios must sum to 1.0");
    let mut indices: Vec<i64> = (0..len as i64).collect();
    // Deterministic shuffle via seed
    let mut rng = fastrand::Rng::with_seed(seed);
    for i in (1..indices.len()).rev() {
        let j = rng.usize(0..=i);
        indices.swap(i, j);
    }
    let split = (len as f32 * train_ratio).round() as usize;
    let train: Vec<i64> = indices[..split].to_vec();
    let eval: Vec<i64> = indices[split..].to_vec();
    // Silent fallback: if eval is empty, use all data for eval
    if eval.is_empty() {
        static WARNED: std::sync::Once = std::sync::Once::new();
        WARNED.call_once(|| {
            log::warn!(
                "eval set is empty (train_ratio={train_ratio}) — falling back to using ALL data for eval (train/eval overlap)"
            );
        });
        (train, indices.clone())
    } else {
        (train, eval)
    }
}

#[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);
    }

    #[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);
        }
    }
}

/// 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)
}