entrenar 0.7.10

Training & Optimization library with autograd, LoRA, quantization, and model merging
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
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
//! Multi-Adapter Pipeline (GPU-SHARE Phase 2.1, GH-203)
//!
//! Trains N LoRA adapter sets concurrently on a single frozen NF4 base model.
//! The base model is loaded once to GPU, and each adapter maintains independent:
//! - LoRA A/B matrices (Q and V projections)
//! - AdamW optimizer state
//! - Training data iterator
//! - Checkpoint directory
//!
//! # VRAM Savings
//!
//! Compared to N separate processes (MPS), this saves (N-1) × base_model_vram:
//! - MPS (3 adapters on 7B): 3 × 7.3 GB = 21.9 GB
//! - Multi-adapter (3 adapters on 7B): 7.3 GB + 3 × 0.02 GB = 7.36 GB
//!
//! # Architecture
//!
//! ```text
//! ┌──────────────────────────────────────┐
//! │         Frozen NF4 Base Model        │ ← loaded once
//! │    (CudaNf4TransformerBlock × L)     │
//! └──────────┬───────────┬───────────┬───┘
//!            │           │           │
//!     ┌──────┴──┐ ┌──────┴──┐ ┌──────┴──┐
//!     │Adapter 0│ │Adapter 1│ │Adapter 2│
//!     │LoRA A/B │ │LoRA A/B │ │LoRA A/B │
//!     │Optimizer│ │Optimizer│ │Optimizer│
//!     │  Data   │ │  Data   │ │  Data   │
//!     └─────────┘ └─────────┘ └─────────┘
//! ```

use super::instruct_corpus::InstructSample;
use super::instruct_pipeline::{InstructConfig, InstructPipeline, InstructStepResult};
use super::instruct_trainer::InstructEpochMetrics;
use crate::lora::LoRALayer;
use serde::Deserialize;
use std::path::{Path, PathBuf};

/// Scheduling strategy for multi-adapter training.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AdapterSchedule {
    /// All adapters process one sample each per step (synchronized).
    Synchronized,
    /// Round-robin: each step trains one adapter.
    #[default]
    RoundRobin,
    /// Priority: adapter with highest validation loss gets the next step.
    PriorityValLoss,
}

/// Configuration for a single adapter slot.
#[derive(Debug, Clone)]
pub struct AdapterConfig {
    /// Path to training data (JSONL instruct corpus).
    pub data_path: PathBuf,
    /// Directory for adapter checkpoints.
    pub checkpoint_dir: PathBuf,
    /// Per-adapter hyperparameters (lora_rank, lr, epochs, etc.)
    pub instruct_config: InstructConfig,
}

/// TOML file schema for `--adapters-config adapters.toml` (GPU-SHARE §2.4).
///
/// # Example
///
/// ```toml
/// [[adapter]]
/// data = "data/corpus-a.jsonl"
/// checkpoint = "checkpoints/adapter-a"
/// label = "code-review"
/// rank = 16
/// learning_rate = 0.0002
///
/// [[adapter]]
/// data = "data/corpus-b.jsonl"
/// checkpoint = "checkpoints/adapter-b"
/// label = "bug-fixing"
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct AdaptersConfigFile {
    /// List of adapter configurations.
    #[serde(rename = "adapter")]
    pub adapters: Vec<AdapterEntry>,
}

/// A single adapter entry in the TOML config file.
#[derive(Debug, Clone, Deserialize)]
pub struct AdapterEntry {
    /// Path to training data (JSONL instruct corpus).
    pub data: PathBuf,
    /// Directory for adapter checkpoints.
    pub checkpoint: PathBuf,
    /// Human-readable label for this adapter.
    #[serde(default)]
    pub label: Option<String>,
    /// LoRA rank override (default: 16).
    #[serde(default)]
    pub rank: Option<usize>,
    /// Learning rate override.
    #[serde(default)]
    pub learning_rate: Option<f32>,
    /// Epochs override.
    #[serde(default)]
    pub epochs: Option<usize>,
    /// Maximum sequence length override.
    #[serde(default)]
    pub max_seq_len: Option<usize>,
}

impl AdaptersConfigFile {
    /// Parse an adapters config from a TOML file.
    pub fn from_file(path: &Path) -> Result<Self, String> {
        let contents = std::fs::read_to_string(path)
            .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
        Self::from_toml(&contents)
    }

    /// Parse an adapters config from a TOML string.
    pub fn from_toml(toml_str: &str) -> Result<Self, String> {
        let config: Self =
            toml::from_str(toml_str).map_err(|e| format!("failed to parse adapters TOML: {e}"))?;
        if config.adapters.is_empty() {
            return Err("adapters config must have at least one [[adapter]] entry".to_string());
        }
        Ok(config)
    }

    /// Convert to `Vec<AdapterConfig>` using a base `InstructConfig` for defaults.
    pub fn to_adapter_configs(&self, base: &InstructConfig) -> Vec<AdapterConfig> {
        self.adapters
            .iter()
            .map(|entry| {
                let mut config = base.clone();
                if let Some(rank) = entry.rank {
                    config.lora_rank = rank;
                    config.lora_alpha = rank as f32 * 2.0;
                }
                if let Some(lr) = entry.learning_rate {
                    config.learning_rate = lr;
                }
                if let Some(epochs) = entry.epochs {
                    config.epochs = epochs;
                }
                if let Some(seq_len) = entry.max_seq_len {
                    config.max_seq_len = seq_len;
                }
                AdapterConfig {
                    data_path: entry.data.clone(),
                    checkpoint_dir: entry.checkpoint.clone(),
                    instruct_config: config,
                }
            })
            .collect()
    }
}

/// Runtime state for one adapter during training.
pub struct AdapterSlot {
    /// Per-adapter LoRA layers (Q and V projections, per transformer layer).
    pub lora_layers: Vec<LoRALayer>,
    /// Training data for this adapter.
    pub train_samples: Vec<InstructSample>,
    /// Validation data for this adapter.
    pub val_samples: Vec<InstructSample>,
    /// Checkpoint directory for this adapter.
    pub checkpoint_dir: PathBuf,
    /// Per-adapter metrics history.
    pub metrics: Vec<InstructEpochMetrics>,
    /// Per-adapter config.
    pub config: InstructConfig,
    /// Current sample index within the training data.
    pub cursor: usize,
    /// Best validation loss (for early stopping / priority scheduling).
    pub best_val_loss: f32,

    /// Per-adapter GPU LoRA optimizer states.
    #[cfg(feature = "cuda")]
    #[allow(dead_code)]
    pub(crate) optimizer_states: Option<Vec<crate::transformer::GpuLoraOptimizerState>>,
    /// NF4 LoRA optimizer step counter.
    #[cfg(feature = "cuda")]
    pub lora_step: u32,
}

/// Multi-adapter training pipeline.
///
/// Trains N LoRA adapter sets on a shared frozen NF4 base model.
/// GPU memory is dominated by the base model (~7 GB for 7B NF4);
/// each adapter adds only ~20 MB (LoRA A/B matrices + optimizer state).
pub struct MultiAdapterPipeline {
    /// The base InstructPipeline (owns the frozen transformer + CUDA blocks).
    pub base_pipeline: InstructPipeline,
    /// Independent adapter slots.
    pub adapters: Vec<AdapterSlot>,
    /// Scheduling strategy.
    pub schedule: AdapterSchedule,
    /// Current step counter (global across all adapters).
    pub global_step: usize,
}

impl MultiAdapterPipeline {
    /// Create a new multi-adapter pipeline.
    ///
    /// The `base_pipeline` should be a fully initialized InstructPipeline
    /// (with CUDA blocks uploaded if GPU training is desired). Adapter slots
    /// are initially empty — call `add_adapter()` to register each one.
    pub fn new(base_pipeline: InstructPipeline, schedule: AdapterSchedule) -> Self {
        Self { base_pipeline, adapters: Vec::new(), schedule, global_step: 0 }
    }

    /// Add an adapter slot with its own training data and checkpoint directory.
    pub fn add_adapter(
        &mut self,
        config: AdapterConfig,
        train_samples: Vec<InstructSample>,
        val_samples: Vec<InstructSample>,
    ) {
        let model_config = &self.base_pipeline.model.config;
        let lora_layers = InstructPipeline::build_lora_layers(
            &self.base_pipeline.model,
            model_config,
            &config.instruct_config,
        );

        let slot = AdapterSlot {
            lora_layers,
            train_samples,
            val_samples,
            checkpoint_dir: config.checkpoint_dir,
            metrics: Vec::new(),
            config: config.instruct_config,
            cursor: 0,
            best_val_loss: f32::INFINITY,
            #[cfg(feature = "cuda")]
            optimizer_states: None,
            #[cfg(feature = "cuda")]
            lora_step: 0,
        };

        self.adapters.push(slot);
    }

    /// Number of registered adapters.
    pub fn num_adapters(&self) -> usize {
        self.adapters.len()
    }

    /// Select which adapter index to train next based on the schedule.
    pub fn select_next_adapter(&self) -> Option<usize> {
        if self.adapters.is_empty() {
            return None;
        }
        match self.schedule {
            AdapterSchedule::Synchronized => {
                // All adapters train — caller should iterate all
                Some(0)
            }
            AdapterSchedule::RoundRobin => Some(self.global_step % self.adapters.len()),
            AdapterSchedule::PriorityValLoss => {
                // Pick adapter with highest (worst) validation loss
                self.adapters
                    .iter()
                    .enumerate()
                    .max_by(|(_, a), (_, b)| {
                        a.best_val_loss
                            .partial_cmp(&b.best_val_loss)
                            .unwrap_or(std::cmp::Ordering::Equal)
                    })
                    .map(|(i, _)| i)
            }
        }
    }

    /// Train one step on the specified adapter.
    ///
    /// Swaps the adapter's LoRA layers into the base pipeline, runs one
    /// training step, then swaps them back out.
    ///
    /// # Returns
    ///
    /// Training step result (loss, perplexity) or `None` if the adapter's
    /// data is exhausted.
    pub fn train_step_adapter(&mut self, adapter_idx: usize) -> Option<InstructStepResult> {
        let slot = &mut self.adapters[adapter_idx];

        // Check if data is exhausted
        if slot.cursor >= slot.train_samples.len() {
            return None;
        }

        let sample = &slot.train_samples[slot.cursor];
        slot.cursor += 1;

        // Tokenize prompt and response separately
        if !self.base_pipeline.has_tokenizer() {
            return None;
        }
        let prompt_ids = self.base_pipeline.tokenize(&sample.instruction);
        let response_ids = self.base_pipeline.tokenize(&sample.response);

        if prompt_ids.is_empty() || response_ids.is_empty() {
            return None;
        }

        // Swap adapter's LoRA layers into the base pipeline
        std::mem::swap(&mut slot.lora_layers, &mut self.base_pipeline.lora_layers);

        // Run training step through base pipeline (uses shared CUDA blocks)
        let result = self.base_pipeline.train_step(&prompt_ids, &response_ids);

        // Swap LoRA layers back
        std::mem::swap(&mut slot.lora_layers, &mut self.base_pipeline.lora_layers);

        self.global_step += 1;

        Some(result)
    }

    /// Reset all adapter cursors for a new epoch.
    pub fn reset_epoch(&mut self, seed: u64) {
        for (i, slot) in self.adapters.iter_mut().enumerate() {
            slot.cursor = 0;
            // Shuffle training data with per-adapter seed
            shuffle_samples(&mut slot.train_samples, seed.wrapping_add(i as u64));
        }
    }

    /// Check if all adapters have exhausted their training data.
    pub fn all_exhausted(&self) -> bool {
        self.adapters.iter().all(|s| s.cursor >= s.train_samples.len())
    }

    /// Batch training step across all non-exhausted adapters (GH-204).
    ///
    /// Trains each adapter that still has data, using the scheduling mode.
    /// In `Synchronized` mode, all adapters train one sample each.
    /// In `RoundRobin`, only the next scheduled adapter trains.
    /// In `PriorityValLoss`, the adapter with highest val loss trains.
    ///
    /// Returns per-adapter step results (indexed by adapter, None if skipped/exhausted).
    ///
    /// NOTE: Current implementation runs sequential forward+backward per adapter
    /// (swapping LoRA layers). Future optimization: fused BatchLoRA forward
    /// through shared NF4 blocks with per-adapter LoRA deltas (arXiv:2510.00206).
    pub fn batch_train_step(&mut self) -> Vec<Option<InstructStepResult>> {
        let n = self.adapters.len();
        let mut results = vec![None; n];

        match self.schedule {
            AdapterSchedule::Synchronized => {
                // All adapters train one sample each
                for i in 0..n {
                    results[i] = self.train_step_adapter(i);
                }
            }
            AdapterSchedule::RoundRobin | AdapterSchedule::PriorityValLoss => {
                // Single adapter per step
                if let Some(idx) = self.select_next_adapter() {
                    results[idx] = self.train_step_adapter(idx);
                }
            }
        }

        results
    }

    /// Save a checkpoint for the specified adapter.
    ///
    /// Creates `{checkpoint_dir}/epoch-{epoch}/` with:
    /// - `metadata.json`: adapter index, epoch, metrics
    /// - `model.safetensors`: LoRA A/B weights for this adapter
    pub fn save_adapter_checkpoint(
        &self,
        adapter_idx: usize,
        epoch: usize,
        avg_loss: f32,
    ) -> Result<PathBuf, Box<dyn std::error::Error>> {
        let slot = &self.adapters[adapter_idx];
        let ckpt_dir = slot.checkpoint_dir.join(format!("epoch-{epoch}"));
        std::fs::create_dir_all(&ckpt_dir)?;

        // Metadata
        let metadata = serde_json::json!({
            "mode": "multi_adapter",
            "adapter_index": adapter_idx,
            "epoch": epoch,
            "avg_loss": avg_loss,
            "best_val_loss": slot.best_val_loss,
            "lora_rank": slot.config.lora_rank,
            "lora_alpha": slot.config.lora_alpha,
            "train_samples": slot.train_samples.len(),
            "global_step": self.global_step,
        });
        std::fs::write(ckpt_dir.join("metadata.json"), serde_json::to_string_pretty(&metadata)?)?;

        // Save LoRA weights as SafeTensors
        save_adapter_lora_weights(&slot.lora_layers, &ckpt_dir)?;

        Ok(ckpt_dir)
    }

    /// Save best checkpoint for an adapter (overwrites previous best).
    pub fn save_best_checkpoint(
        &self,
        adapter_idx: usize,
        epoch: usize,
        avg_loss: f32,
    ) -> Result<PathBuf, Box<dyn std::error::Error>> {
        let slot = &self.adapters[adapter_idx];
        let best_dir = slot.checkpoint_dir.join("best");
        std::fs::create_dir_all(&best_dir)?;

        let metadata = serde_json::json!({
            "mode": "multi_adapter",
            "adapter_index": adapter_idx,
            "epoch": epoch,
            "avg_loss": avg_loss,
            "lora_rank": slot.config.lora_rank,
            "lora_alpha": slot.config.lora_alpha,
            "global_step": self.global_step,
        });
        std::fs::write(best_dir.join("metadata.json"), serde_json::to_string_pretty(&metadata)?)?;

        save_adapter_lora_weights(&slot.lora_layers, &best_dir)?;
        Ok(best_dir)
    }
}

/// Save LoRA A/B weights to a SafeTensors file in the given directory.
fn save_adapter_lora_weights(
    lora_layers: &[LoRALayer],
    dir: &std::path::Path,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut tensor_data: Vec<(String, Vec<u8>, Vec<usize>)> = Vec::new();

    for (idx, lora) in lora_layers.iter().enumerate() {
        let layer = idx / 2;
        let proj = if idx % 2 == 0 { "q" } else { "v" };

        // LoRA A: [rank, d_in]
        let a_data = lora.lora_a().data();
        let a_bytes: Vec<u8> =
            bytemuck::cast_slice(a_data.as_slice().expect("contiguous lora_a")).to_vec();
        let a_shape = vec![lora.rank(), lora.d_in()];
        tensor_data.push((format!("lora.{layer}.{proj}_proj.lora_a"), a_bytes, a_shape));

        // LoRA B: [d_out, rank]
        let b_data = lora.lora_b().data();
        let b_bytes: Vec<u8> =
            bytemuck::cast_slice(b_data.as_slice().expect("contiguous lora_b")).to_vec();
        let b_shape = vec![lora.d_out(), lora.rank()];
        tensor_data.push((format!("lora.{layer}.{proj}_proj.lora_b"), b_bytes, b_shape));
    }

    let views: Vec<(&str, safetensors::tensor::TensorView<'_>)> = tensor_data
        .iter()
        .map(|(name, bytes, shape)| {
            let view = safetensors::tensor::TensorView::new(
                safetensors::tensor::Dtype::F32,
                shape.clone(),
                bytes,
            )
            .expect("valid tensor view");
            (name.as_str(), view)
        })
        .collect();

    let safetensor_bytes = safetensors::serialize(views, None)
        .map_err(|e| format!("SafeTensors serialization failed: {e}"))?;
    std::fs::write(dir.join("model.safetensors"), safetensor_bytes)?;
    Ok(())
}

/// Simple Fisher-Yates shuffle with a deterministic seed.
fn shuffle_samples(samples: &mut [InstructSample], seed: u64) {
    let mut rng = seed;
    for i in (1..samples.len()).rev() {
        // xorshift64
        rng ^= rng << 13;
        rng ^= rng >> 7;
        rng ^= rng << 17;
        let j = (rng as usize) % (i + 1);
        samples.swap(i, j);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_schedule_round_robin() {
        let sched = AdapterSchedule::RoundRobin;
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot(), dummy_slot(), dummy_slot()],
            schedule: sched,
            global_step: 0,
        };

        assert_eq!(pipeline.select_next_adapter(), Some(0));

        let pipeline = MultiAdapterPipeline { global_step: 1, ..pipeline };
        assert_eq!(pipeline.select_next_adapter(), Some(1));

        let pipeline = MultiAdapterPipeline { global_step: 5, ..pipeline };
        assert_eq!(pipeline.select_next_adapter(), Some(2));
    }

    #[test]
    fn test_schedule_priority_val_loss() {
        let mut slot0 = dummy_slot();
        slot0.best_val_loss = 1.0;
        let mut slot1 = dummy_slot();
        slot1.best_val_loss = 3.0; // worst
        let mut slot2 = dummy_slot();
        slot2.best_val_loss = 2.0;

        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot0, slot1, slot2],
            schedule: AdapterSchedule::PriorityValLoss,
            global_step: 0,
        };

        assert_eq!(pipeline.select_next_adapter(), Some(1)); // highest loss
    }

    #[test]
    fn test_empty_pipeline() {
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        assert_eq!(pipeline.select_next_adapter(), None);
        assert!(pipeline.all_exhausted());
    }

    #[test]
    fn test_shuffle_deterministic() {
        let mut samples1 = vec![
            InstructSample {
                instruction: "a".into(),
                response: "1".into(),
                system: None,
                metadata: None,
            },
            InstructSample {
                instruction: "b".into(),
                response: "2".into(),
                system: None,
                metadata: None,
            },
            InstructSample {
                instruction: "c".into(),
                response: "3".into(),
                system: None,
                metadata: None,
            },
        ];
        let mut samples2 = samples1.clone();

        shuffle_samples(&mut samples1, 42);
        shuffle_samples(&mut samples2, 42);

        // Same seed → same order
        for (s1, s2) in samples1.iter().zip(samples2.iter()) {
            assert_eq!(s1.instruction, s2.instruction);
        }
    }

    #[test]
    fn test_batch_train_step_synchronized() {
        let mut pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot(), dummy_slot()],
            schedule: AdapterSchedule::Synchronized,
            global_step: 0,
        };

        // No tokenizer → all results are None, but batch_train_step returns correct length
        let results = pipeline.batch_train_step();
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_batch_train_step_round_robin() {
        let mut pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot(), dummy_slot(), dummy_slot()],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };

        let results = pipeline.batch_train_step();
        assert_eq!(results.len(), 3);
        // RoundRobin at step 0 → only adapter 0 would be trained
        // (but no tokenizer, so all None)
    }

    #[test]
    fn test_adapters_config_parse() {
        let toml = r#"
[[adapter]]
data = "data/corpus-a.jsonl"
checkpoint = "checkpoints/adapter-a"
label = "code-review"
rank = 16
learning_rate = 0.0002

[[adapter]]
data = "data/corpus-b.jsonl"
checkpoint = "checkpoints/adapter-b"
label = "bug-fixing"
rank = 8
"#;
        let config = AdaptersConfigFile::from_toml(toml).expect("valid TOML");
        assert_eq!(config.adapters.len(), 2);
        assert_eq!(config.adapters[0].data, PathBuf::from("data/corpus-a.jsonl"));
        assert_eq!(config.adapters[0].rank, Some(16));
        assert_eq!(config.adapters[0].learning_rate, Some(0.0002));
        assert_eq!(config.adapters[1].rank, Some(8));
        assert!(config.adapters[1].learning_rate.is_none());
    }

    #[test]
    fn test_adapters_config_to_adapter_configs() {
        let toml = r#"
[[adapter]]
data = "data/a.jsonl"
checkpoint = "ckpt/a"
rank = 32
learning_rate = 0.001
epochs = 5
max_seq_len = 256
"#;
        let config = AdaptersConfigFile::from_toml(toml).expect("valid");
        let base = InstructConfig::default();
        let adapters = config.to_adapter_configs(&base);
        assert_eq!(adapters.len(), 1);
        assert_eq!(adapters[0].instruct_config.lora_rank, 32);
        assert!((adapters[0].instruct_config.learning_rate - 0.001).abs() < f32::EPSILON);
        assert_eq!(adapters[0].instruct_config.epochs, 5);
        assert_eq!(adapters[0].instruct_config.max_seq_len, 256);
    }

    #[test]
    fn test_adapters_config_empty_fails() {
        let toml = "";
        assert!(AdaptersConfigFile::from_toml(toml).is_err());
    }

    #[test]
    fn test_adapters_config_defaults_from_base() {
        let toml = r#"
[[adapter]]
data = "data/x.jsonl"
checkpoint = "ckpt/x"
"#;
        let config = AdaptersConfigFile::from_toml(toml).expect("valid");
        let base = InstructConfig {
            lora_rank: 16,
            learning_rate: 0.0002,
            epochs: 3,
            max_seq_len: 512,
            ..Default::default()
        };
        let adapters = config.to_adapter_configs(&base);
        // Should inherit base defaults when not overridden
        assert_eq!(adapters[0].instruct_config.lora_rank, 16);
        assert!((adapters[0].instruct_config.learning_rate - 0.0002).abs() < f32::EPSILON);
        assert_eq!(adapters[0].instruct_config.epochs, 3);
        assert_eq!(adapters[0].instruct_config.max_seq_len, 512);
    }

    fn create_dummy_pipeline() -> InstructPipeline {
        use crate::transformer::TransformerConfig;
        let config = TransformerConfig::tiny();
        InstructPipeline::new(&config, InstructConfig::default())
    }

    fn dummy_slot() -> AdapterSlot {
        AdapterSlot {
            lora_layers: Vec::new(),
            train_samples: Vec::new(),
            val_samples: Vec::new(),
            checkpoint_dir: PathBuf::from("/tmp/test"),
            metrics: Vec::new(),
            config: InstructConfig::default(),
            cursor: 0,
            best_val_loss: f32::INFINITY,
            #[cfg(feature = "cuda")]
            optimizer_states: None,
            #[cfg(feature = "cuda")]
            lora_step: 0,
        }
    }

    fn dummy_slot_with_data(n_samples: usize) -> AdapterSlot {
        let samples: Vec<InstructSample> = (0..n_samples)
            .map(|i| InstructSample {
                instruction: format!("inst_{i}"),
                response: format!("resp_{i}"),
                system: None,
                metadata: None,
            })
            .collect();
        AdapterSlot {
            lora_layers: Vec::new(),
            train_samples: samples,
            val_samples: Vec::new(),
            checkpoint_dir: PathBuf::from("/tmp/test"),
            metrics: Vec::new(),
            config: InstructConfig::default(),
            cursor: 0,
            best_val_loss: f32::INFINITY,
            #[cfg(feature = "cuda")]
            optimizer_states: None,
            #[cfg(feature = "cuda")]
            lora_step: 0,
        }
    }

    // ── Coverage improvement tests ───────────────────────────────

    #[test]
    fn test_adapter_schedule_default() {
        let sched: AdapterSchedule = Default::default();
        assert_eq!(sched, AdapterSchedule::RoundRobin);
    }

    #[test]
    fn test_adapter_schedule_debug() {
        assert_eq!(format!("{:?}", AdapterSchedule::Synchronized), "Synchronized");
        assert_eq!(format!("{:?}", AdapterSchedule::RoundRobin), "RoundRobin");
        assert_eq!(format!("{:?}", AdapterSchedule::PriorityValLoss), "PriorityValLoss");
    }

    #[test]
    fn test_adapter_schedule_clone() {
        let sched = AdapterSchedule::PriorityValLoss;
        let cloned = sched;
        assert_eq!(sched, cloned);
    }

    #[test]
    fn test_adapter_schedule_eq() {
        assert_eq!(AdapterSchedule::Synchronized, AdapterSchedule::Synchronized);
        assert_ne!(AdapterSchedule::Synchronized, AdapterSchedule::RoundRobin);
        assert_ne!(AdapterSchedule::RoundRobin, AdapterSchedule::PriorityValLoss);
    }

    #[test]
    fn test_select_next_adapter_synchronized() {
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot(), dummy_slot()],
            schedule: AdapterSchedule::Synchronized,
            global_step: 0,
        };
        // Synchronized always returns Some(0)
        assert_eq!(pipeline.select_next_adapter(), Some(0));
    }

    #[test]
    fn test_select_next_adapter_synchronized_any_step() {
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot(), dummy_slot()],
            schedule: AdapterSchedule::Synchronized,
            global_step: 42,
        };
        assert_eq!(pipeline.select_next_adapter(), Some(0));
    }

    #[test]
    fn test_select_next_adapter_round_robin_wraps() {
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot(), dummy_slot(), dummy_slot()],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 3,
        };
        assert_eq!(pipeline.select_next_adapter(), Some(0)); // 3 % 3 = 0
    }

    #[test]
    fn test_select_next_adapter_priority_all_infinity() {
        // All slots have INFINITY best_val_loss → first one wins (or any, but deterministic)
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot(), dummy_slot()],
            schedule: AdapterSchedule::PriorityValLoss,
            global_step: 0,
        };
        let result = pipeline.select_next_adapter();
        assert!(result.is_some());
    }

    #[test]
    fn test_select_next_adapter_priority_with_nan() {
        let mut slot0 = dummy_slot();
        slot0.best_val_loss = f32::NAN;
        let mut slot1 = dummy_slot();
        slot1.best_val_loss = 1.0;

        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot0, slot1],
            schedule: AdapterSchedule::PriorityValLoss,
            global_step: 0,
        };
        // NaN comparison uses Ordering::Equal fallback, so result is deterministic
        let result = pipeline.select_next_adapter();
        assert!(result.is_some());
    }

    #[test]
    fn test_num_adapters() {
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot(), dummy_slot(), dummy_slot()],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        assert_eq!(pipeline.num_adapters(), 3);
    }

    #[test]
    fn test_num_adapters_empty() {
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        assert_eq!(pipeline.num_adapters(), 0);
    }

    #[test]
    fn test_all_exhausted_with_data() {
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot_with_data(3), dummy_slot_with_data(2)],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        assert!(!pipeline.all_exhausted());
    }

    #[test]
    fn test_all_exhausted_partially() {
        let mut slot0 = dummy_slot_with_data(3);
        slot0.cursor = 3; // exhausted
        let slot1 = dummy_slot_with_data(2); // not exhausted

        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot0, slot1],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        assert!(!pipeline.all_exhausted());
    }

    #[test]
    fn test_all_exhausted_all_done() {
        let mut slot0 = dummy_slot_with_data(3);
        slot0.cursor = 3;
        let mut slot1 = dummy_slot_with_data(2);
        slot1.cursor = 2;

        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot0, slot1],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        assert!(pipeline.all_exhausted());
    }

    #[test]
    fn test_reset_epoch() {
        let mut pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot_with_data(5), dummy_slot_with_data(3)],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        pipeline.adapters[0].cursor = 5;
        pipeline.adapters[1].cursor = 3;

        pipeline.reset_epoch(42);

        assert_eq!(pipeline.adapters[0].cursor, 0);
        assert_eq!(pipeline.adapters[1].cursor, 0);
    }

    #[test]
    fn test_reset_epoch_shuffle_deterministic() {
        let mut pipeline1 = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot_with_data(10)],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        let mut pipeline2 = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot_with_data(10)],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };

        pipeline1.reset_epoch(123);
        pipeline2.reset_epoch(123);

        // Same seed should produce same shuffle
        for (s1, s2) in pipeline1.adapters[0]
            .train_samples
            .iter()
            .zip(pipeline2.adapters[0].train_samples.iter())
        {
            assert_eq!(s1.instruction, s2.instruction);
        }
    }

    #[test]
    fn test_shuffle_samples_empty() {
        let mut samples: Vec<InstructSample> = vec![];
        shuffle_samples(&mut samples, 42);
        assert!(samples.is_empty());
    }

    #[test]
    fn test_shuffle_samples_single() {
        let mut samples = vec![InstructSample {
            instruction: "only".into(),
            response: "one".into(),
            system: None,
            metadata: None,
        }];
        shuffle_samples(&mut samples, 42);
        assert_eq!(samples.len(), 1);
        assert_eq!(samples[0].instruction, "only");
    }

    #[test]
    fn test_shuffle_samples_different_seeds() {
        let mut samples1 = vec![
            InstructSample {
                instruction: "a".into(),
                response: "1".into(),
                system: None,
                metadata: None,
            },
            InstructSample {
                instruction: "b".into(),
                response: "2".into(),
                system: None,
                metadata: None,
            },
            InstructSample {
                instruction: "c".into(),
                response: "3".into(),
                system: None,
                metadata: None,
            },
            InstructSample {
                instruction: "d".into(),
                response: "4".into(),
                system: None,
                metadata: None,
            },
            InstructSample {
                instruction: "e".into(),
                response: "5".into(),
                system: None,
                metadata: None,
            },
        ];
        let mut samples2 = samples1.clone();

        shuffle_samples(&mut samples1, 1);
        shuffle_samples(&mut samples2, 999);

        // Different seeds should (very likely) produce different orderings
        let same =
            samples1.iter().zip(samples2.iter()).all(|(s1, s2)| s1.instruction == s2.instruction);
        // With 5! = 120 permutations, probability of same is ~0.83%, so this is safe
        assert!(!same, "Different seeds should produce different shuffles");
    }

    #[test]
    fn test_adapters_config_from_toml_invalid_toml() {
        let toml = "this is not valid TOML {{{}}}";
        let result = AdaptersConfigFile::from_toml(toml);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("failed to parse"), "Expected parse error, got: {err}");
    }

    #[test]
    fn test_adapters_config_from_toml_empty_adapters_array() {
        // Valid TOML but no [[adapter]] entries → should fail
        let toml = r#"
[settings]
foo = "bar"
"#;
        let result = AdaptersConfigFile::from_toml(toml);
        assert!(result.is_err());
    }

    #[test]
    fn test_adapters_config_from_file_not_found() {
        let result = AdaptersConfigFile::from_file(Path::new("/tmp/nonexistent_adapters_xyz.toml"));
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("failed to read"), "Expected read error, got: {err}");
    }

    #[test]
    fn test_adapters_config_from_file_valid() {
        let dir = std::env::temp_dir().join("entrenar_adapter_cfg_test");
        std::fs::create_dir_all(&dir).expect("create dir");
        let path = dir.join("adapters.toml");
        std::fs::write(
            &path,
            r#"
[[adapter]]
data = "data/a.jsonl"
checkpoint = "ckpt/a"
label = "test-adapter"
"#,
        )
        .expect("write file");
        let config = AdaptersConfigFile::from_file(&path).expect("valid config");
        assert_eq!(config.adapters.len(), 1);
        assert_eq!(config.adapters[0].label, Some("test-adapter".to_string()));
        std::fs::remove_file(&path).expect("cleanup");
    }

    #[test]
    fn test_adapter_entry_defaults() {
        let toml = r#"
[[adapter]]
data = "data/x.jsonl"
checkpoint = "ckpt/x"
"#;
        let config = AdaptersConfigFile::from_toml(toml).expect("valid");
        let entry = &config.adapters[0];
        assert!(entry.label.is_none());
        assert!(entry.rank.is_none());
        assert!(entry.learning_rate.is_none());
        assert!(entry.epochs.is_none());
        assert!(entry.max_seq_len.is_none());
    }

    #[test]
    fn test_adapter_entry_all_fields() {
        let toml = r#"
[[adapter]]
data = "data/full.jsonl"
checkpoint = "ckpt/full"
label = "full-adapter"
rank = 64
learning_rate = 0.001
epochs = 10
max_seq_len = 1024
"#;
        let config = AdaptersConfigFile::from_toml(toml).expect("valid");
        let entry = &config.adapters[0];
        assert_eq!(entry.data, PathBuf::from("data/full.jsonl"));
        assert_eq!(entry.checkpoint, PathBuf::from("ckpt/full"));
        assert_eq!(entry.label, Some("full-adapter".to_string()));
        assert_eq!(entry.rank, Some(64));
        assert_eq!(entry.learning_rate, Some(0.001));
        assert_eq!(entry.epochs, Some(10));
        assert_eq!(entry.max_seq_len, Some(1024));
    }

    #[test]
    fn test_to_adapter_configs_rank_sets_alpha() {
        let toml = r#"
[[adapter]]
data = "data/a.jsonl"
checkpoint = "ckpt/a"
rank = 32
"#;
        let config = AdaptersConfigFile::from_toml(toml).expect("valid");
        let base = InstructConfig::default();
        let adapters = config.to_adapter_configs(&base);
        // rank=32 → alpha = 32*2.0 = 64.0
        assert_eq!(adapters[0].instruct_config.lora_rank, 32);
        assert!((adapters[0].instruct_config.lora_alpha - 64.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_to_adapter_configs_multiple() {
        let toml = r#"
[[adapter]]
data = "a.jsonl"
checkpoint = "ckpt/a"
rank = 8
learning_rate = 0.0001

[[adapter]]
data = "b.jsonl"
checkpoint = "ckpt/b"
epochs = 20

[[adapter]]
data = "c.jsonl"
checkpoint = "ckpt/c"
max_seq_len = 128
"#;
        let config = AdaptersConfigFile::from_toml(toml).expect("valid");
        let base = InstructConfig {
            lora_rank: 16,
            learning_rate: 0.0002,
            epochs: 3,
            max_seq_len: 512,
            ..Default::default()
        };
        let adapters = config.to_adapter_configs(&base);
        assert_eq!(adapters.len(), 3);

        // First adapter: rank=8, lr=0.0001
        assert_eq!(adapters[0].instruct_config.lora_rank, 8);
        assert!((adapters[0].instruct_config.learning_rate - 0.0001).abs() < f32::EPSILON);
        assert_eq!(adapters[0].instruct_config.epochs, 3); // inherited

        // Second adapter: epochs=20
        assert_eq!(adapters[1].instruct_config.lora_rank, 16); // inherited
        assert_eq!(adapters[1].instruct_config.epochs, 20);

        // Third adapter: max_seq_len=128
        assert_eq!(adapters[2].instruct_config.max_seq_len, 128);
        assert_eq!(adapters[2].instruct_config.lora_rank, 16); // inherited
    }

    #[test]
    fn test_batch_train_step_priority_val_loss() {
        let mut slot0 = dummy_slot();
        slot0.best_val_loss = 2.0;
        let mut slot1 = dummy_slot();
        slot1.best_val_loss = 5.0; // worst → should be selected

        let mut pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot0, slot1],
            schedule: AdapterSchedule::PriorityValLoss,
            global_step: 0,
        };

        let results = pipeline.batch_train_step();
        assert_eq!(results.len(), 2);
        // No tokenizer → both None, but the function should not panic
    }

    #[test]
    fn test_adapter_config_debug() {
        let config = AdapterConfig {
            data_path: PathBuf::from("test.jsonl"),
            checkpoint_dir: PathBuf::from("/tmp/ckpt"),
            instruct_config: InstructConfig::default(),
        };
        let debug = format!("{config:?}");
        assert!(debug.contains("AdapterConfig"));
        assert!(debug.contains("test.jsonl"));
    }

    #[test]
    fn test_adapter_config_clone() {
        let config = AdapterConfig {
            data_path: PathBuf::from("test.jsonl"),
            checkpoint_dir: PathBuf::from("/tmp/ckpt"),
            instruct_config: InstructConfig::default(),
        };
        let cloned = config.clone();
        assert_eq!(cloned.data_path, PathBuf::from("test.jsonl"));
        assert_eq!(cloned.checkpoint_dir, PathBuf::from("/tmp/ckpt"));
    }

    #[test]
    fn test_adapters_config_file_debug() {
        let toml = r#"
[[adapter]]
data = "a.jsonl"
checkpoint = "ckpt/a"
"#;
        let config = AdaptersConfigFile::from_toml(toml).expect("valid");
        let debug = format!("{config:?}");
        assert!(debug.contains("AdaptersConfigFile"));
    }

    #[test]
    fn test_adapter_entry_debug() {
        let toml = r#"
[[adapter]]
data = "a.jsonl"
checkpoint = "ckpt/a"
label = "test"
"#;
        let config = AdaptersConfigFile::from_toml(toml).expect("valid");
        let debug = format!("{:?}", config.adapters[0]);
        assert!(debug.contains("AdapterEntry"));
        assert!(debug.contains("test"));
    }

    #[test]
    fn test_adapter_slot_cursor_tracking() {
        let mut slot = dummy_slot_with_data(5);
        assert_eq!(slot.cursor, 0);
        slot.cursor = 3;
        assert_eq!(slot.cursor, 3);
        assert!(slot.cursor < slot.train_samples.len());
        slot.cursor = 5;
        assert!(slot.cursor >= slot.train_samples.len());
    }

    #[test]
    fn test_adapter_slot_best_val_loss() {
        let mut slot = dummy_slot();
        assert_eq!(slot.best_val_loss, f32::INFINITY);
        slot.best_val_loss = 0.5;
        assert!((slot.best_val_loss - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn test_multi_adapter_pipeline_global_step() {
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        assert_eq!(pipeline.global_step, 0);
    }

    #[test]
    fn test_train_step_adapter_exhausted() {
        let mut slot = dummy_slot_with_data(2);
        slot.cursor = 2; // already exhausted

        let mut pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };

        let result = pipeline.train_step_adapter(0);
        assert!(result.is_none(), "Exhausted adapter should return None");
    }

    #[test]
    fn test_batch_train_step_empty() {
        let mut pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![],
            schedule: AdapterSchedule::Synchronized,
            global_step: 0,
        };
        let results = pipeline.batch_train_step();
        assert!(results.is_empty());
    }

    // ── Additional coverage tests ─────────────────────────────────

    #[test]
    fn test_multi_adapter_pipeline_new() {
        let pipeline =
            MultiAdapterPipeline::new(create_dummy_pipeline(), AdapterSchedule::Synchronized);
        assert_eq!(pipeline.num_adapters(), 0);
        assert_eq!(pipeline.global_step, 0);
        assert!(pipeline.all_exhausted());
    }

    #[test]
    fn test_multi_adapter_pipeline_add_adapter() {
        let mut pipeline =
            MultiAdapterPipeline::new(create_dummy_pipeline(), AdapterSchedule::RoundRobin);
        let config = AdapterConfig {
            data_path: PathBuf::from("data.jsonl"),
            checkpoint_dir: PathBuf::from("/tmp/ckpt"),
            instruct_config: InstructConfig::default(),
        };
        let samples = vec![InstructSample {
            instruction: "test".into(),
            response: "response".into(),
            system: None,
            metadata: None,
        }];
        pipeline.add_adapter(config, samples, vec![]);
        assert_eq!(pipeline.num_adapters(), 1);
        assert!(!pipeline.all_exhausted());
    }

    #[test]
    fn test_train_step_adapter_no_tokenizer() {
        let mut pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot_with_data(5)],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        // No tokenizer loaded → should return None
        let result = pipeline.train_step_adapter(0);
        assert!(result.is_none());
        // Cursor should have advanced
        assert_eq!(pipeline.adapters[0].cursor, 1);
    }

    #[test]
    fn test_train_step_increments_global_step() {
        let mut pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot_with_data(5)],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        // Even though result is None (no tokenizer), global_step should not increment
        // because early return happens before step increment
        let _ = pipeline.train_step_adapter(0);
        // Cursor advanced to 1, but no tokenizer so returns early before global_step increment
    }

    #[test]
    fn test_batch_train_step_synchronized_all_exhausted() {
        let mut slot0 = dummy_slot_with_data(1);
        slot0.cursor = 1;
        let mut slot1 = dummy_slot_with_data(1);
        slot1.cursor = 1;

        let mut pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot0, slot1],
            schedule: AdapterSchedule::Synchronized,
            global_step: 0,
        };
        let results = pipeline.batch_train_step();
        assert_eq!(results.len(), 2);
        assert!(results.iter().all(Option::is_none));
    }

    #[test]
    fn test_reset_epoch_different_seeds_different_orders() {
        let mut pipeline1 = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot_with_data(20)],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        let mut pipeline2 = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot_with_data(20)],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };

        pipeline1.reset_epoch(1);
        pipeline2.reset_epoch(999);

        let same = pipeline1.adapters[0]
            .train_samples
            .iter()
            .zip(pipeline2.adapters[0].train_samples.iter())
            .all(|(s1, s2)| s1.instruction == s2.instruction);
        assert!(!same, "Different seeds should produce different shuffles");
    }

    #[test]
    fn test_shuffle_samples_preserves_elements() {
        let mut samples: Vec<InstructSample> = (0..10)
            .map(|i| InstructSample {
                instruction: format!("inst_{i}"),
                response: format!("resp_{i}"),
                system: None,
                metadata: None,
            })
            .collect();
        let original_instructions: Vec<String> =
            samples.iter().map(|s| s.instruction.clone()).collect();

        shuffle_samples(&mut samples, 42);

        // All original elements should still be present
        let mut shuffled_instructions: Vec<String> =
            samples.iter().map(|s| s.instruction.clone()).collect();
        let mut sorted_original = original_instructions.clone();
        sorted_original.sort();
        shuffled_instructions.sort();
        assert_eq!(sorted_original, shuffled_instructions);
    }

    #[test]
    fn test_adapter_slot_metrics_empty() {
        let slot = dummy_slot();
        assert!(slot.metrics.is_empty());
    }

    #[test]
    fn test_adapter_slot_val_samples() {
        let slot = dummy_slot();
        assert!(slot.val_samples.is_empty());
    }

    #[test]
    fn test_adapter_slot_lora_layers_empty() {
        let slot = dummy_slot();
        assert!(slot.lora_layers.is_empty());
    }

    #[test]
    fn test_adapters_config_label_propagation() {
        let toml = r#"
[[adapter]]
data = "d1.jsonl"
checkpoint = "c1"
label = "adapter-one"

[[adapter]]
data = "d2.jsonl"
checkpoint = "c2"
"#;
        let config = AdaptersConfigFile::from_toml(toml).expect("valid");
        assert_eq!(config.adapters[0].label, Some("adapter-one".to_string()));
        assert!(config.adapters[1].label.is_none());
    }

    #[test]
    fn test_adapters_config_to_adapter_configs_alpha_calculation() {
        let toml = r#"
[[adapter]]
data = "data.jsonl"
checkpoint = "ckpt"
rank = 64
"#;
        let config = AdaptersConfigFile::from_toml(toml).expect("valid");
        let base = InstructConfig::default();
        let adapters = config.to_adapter_configs(&base);
        // alpha = rank * 2.0 = 128.0
        assert!((adapters[0].instruct_config.lora_alpha - 128.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_select_next_adapter_round_robin_large_step() {
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot(), dummy_slot()],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 1000,
        };
        assert_eq!(pipeline.select_next_adapter(), Some(0)); // 1000 % 2 = 0

        let pipeline = MultiAdapterPipeline { global_step: 1001, ..pipeline };
        assert_eq!(pipeline.select_next_adapter(), Some(1)); // 1001 % 2 = 1
    }

    #[test]
    fn test_select_next_adapter_priority_selects_worst() {
        let mut slot0 = dummy_slot();
        slot0.best_val_loss = 0.1;
        let mut slot1 = dummy_slot();
        slot1.best_val_loss = 10.0;
        let mut slot2 = dummy_slot();
        slot2.best_val_loss = 5.0;

        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot0, slot1, slot2],
            schedule: AdapterSchedule::PriorityValLoss,
            global_step: 0,
        };
        assert_eq!(pipeline.select_next_adapter(), Some(1)); // 10.0 is worst
    }

    #[test]
    fn test_multi_adapter_multiple_add_adapter() {
        let mut pipeline =
            MultiAdapterPipeline::new(create_dummy_pipeline(), AdapterSchedule::Synchronized);

        for i in 0..3 {
            let config = AdapterConfig {
                data_path: PathBuf::from(format!("data{i}.jsonl")),
                checkpoint_dir: PathBuf::from(format!("/tmp/ckpt{i}")),
                instruct_config: InstructConfig::default(),
            };
            pipeline.add_adapter(config, vec![], vec![]);
        }
        assert_eq!(pipeline.num_adapters(), 3);
        assert!(pipeline.all_exhausted()); // all empty
    }

    // ── cov3: additional coverage tests ─────────────────────────────

    #[test]
    fn test_cov3_save_adapter_checkpoint_creates_dir_and_files() {
        let dir = std::env::temp_dir().join("entrenar_cov3_ckpt_test");
        let _ = std::fs::remove_dir_all(&dir);

        let mut pipeline =
            MultiAdapterPipeline::new(create_dummy_pipeline(), AdapterSchedule::RoundRobin);
        let config = AdapterConfig {
            data_path: PathBuf::from("data.jsonl"),
            checkpoint_dir: dir.clone(),
            instruct_config: InstructConfig::default(),
        };
        let samples = vec![InstructSample {
            instruction: "test".into(),
            response: "resp".into(),
            system: None,
            metadata: None,
        }];
        pipeline.add_adapter(config, samples, vec![]);

        let result = pipeline.save_adapter_checkpoint(0, 1, 0.5);
        assert!(result.is_ok());
        let ckpt_dir = result.unwrap();
        assert!(ckpt_dir.join("metadata.json").exists());
        assert!(ckpt_dir.join("model.safetensors").exists());

        // Verify metadata contents
        let metadata_str = std::fs::read_to_string(ckpt_dir.join("metadata.json")).unwrap();
        assert!(metadata_str.contains("\"mode\": \"multi_adapter\""));
        assert!(metadata_str.contains("\"adapter_index\": 0"));
        assert!(metadata_str.contains("\"epoch\": 1"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_cov3_save_best_checkpoint_creates_dir_and_files() {
        let dir = std::env::temp_dir().join("entrenar_cov3_best_ckpt_test");
        let _ = std::fs::remove_dir_all(&dir);

        let mut pipeline =
            MultiAdapterPipeline::new(create_dummy_pipeline(), AdapterSchedule::RoundRobin);
        let config = AdapterConfig {
            data_path: PathBuf::from("data.jsonl"),
            checkpoint_dir: dir.clone(),
            instruct_config: InstructConfig::default(),
        };
        pipeline.add_adapter(config, vec![], vec![]);

        let result = pipeline.save_best_checkpoint(0, 2, 0.3);
        assert!(result.is_ok());
        let best_dir = result.unwrap();
        assert_eq!(best_dir, dir.join("best"));
        assert!(best_dir.join("metadata.json").exists());
        assert!(best_dir.join("model.safetensors").exists());

        // Verify metadata
        let metadata_str = std::fs::read_to_string(best_dir.join("metadata.json")).unwrap();
        assert!(metadata_str.contains("\"mode\": \"multi_adapter\""));
        assert!(metadata_str.contains("\"epoch\": 2"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_cov3_save_best_checkpoint_overwrites_previous() {
        let dir = std::env::temp_dir().join("entrenar_cov3_best_overwrite");
        let _ = std::fs::remove_dir_all(&dir);

        let mut pipeline =
            MultiAdapterPipeline::new(create_dummy_pipeline(), AdapterSchedule::RoundRobin);
        let config = AdapterConfig {
            data_path: PathBuf::from("data.jsonl"),
            checkpoint_dir: dir.clone(),
            instruct_config: InstructConfig::default(),
        };
        pipeline.add_adapter(config, vec![], vec![]);

        // First save
        pipeline.save_best_checkpoint(0, 1, 1.0).unwrap();
        // Second save should overwrite
        pipeline.save_best_checkpoint(0, 5, 0.2).unwrap();

        let metadata_str = std::fs::read_to_string(dir.join("best").join("metadata.json")).unwrap();
        assert!(metadata_str.contains("\"epoch\": 5"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_cov3_save_adapter_lora_weights_empty_layers() {
        let dir = std::env::temp_dir().join("entrenar_cov3_empty_lora");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let result = save_adapter_lora_weights(&[], &dir);
        assert!(result.is_ok());
        // SafeTensors file should exist even with empty layers
        assert!(dir.join("model.safetensors").exists());

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_cov3_save_adapter_lora_weights_with_real_layers() {
        let dir = std::env::temp_dir().join("entrenar_cov3_real_lora");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        // Create a pipeline with real LoRA layers
        let model_config = crate::transformer::TransformerConfig::tiny();
        let model = crate::transformer::Transformer::new(&model_config);
        let instruct_config = InstructConfig { lora_rank: 4, ..InstructConfig::default() };
        let layers = InstructPipeline::build_lora_layers(&model, &model_config, &instruct_config);

        let result = save_adapter_lora_weights(&layers, &dir);
        assert!(result.is_ok());

        // Verify SafeTensors can be read back
        let st_bytes = std::fs::read(dir.join("model.safetensors")).unwrap();
        let st = safetensors::SafeTensors::deserialize(&st_bytes).unwrap();
        // 4 LoRA layers → 4 * 2 (A and B) = 8 tensors
        assert_eq!(st.len(), layers.len() * 2);

        // Verify naming convention
        let names: Vec<String> = st.names().iter().map(std::string::ToString::to_string).collect();
        assert!(names.iter().any(|n| n.contains("lora_a")));
        assert!(names.iter().any(|n| n.contains("lora_b")));
        assert!(names.iter().any(|n| n.contains("q_proj")));
        assert!(names.iter().any(|n| n.contains("v_proj")));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_cov3_shuffle_samples_large_input() {
        let mut samples: Vec<InstructSample> = (0..100)
            .map(|i| InstructSample {
                instruction: format!("inst_{i}"),
                response: format!("resp_{i}"),
                system: None,
                metadata: None,
            })
            .collect();
        let original: Vec<String> = samples.iter().map(|s| s.instruction.clone()).collect();

        shuffle_samples(&mut samples, 12345);

        let shuffled: Vec<String> = samples.iter().map(|s| s.instruction.clone()).collect();
        // Should be different order
        assert_ne!(original, shuffled, "100 samples should shuffle to different order");
        // But same elements
        let mut sorted_original = original;
        sorted_original.sort();
        let mut sorted_shuffled = shuffled;
        sorted_shuffled.sort();
        assert_eq!(sorted_original, sorted_shuffled);
    }

    #[test]
    fn test_cov3_shuffle_samples_two_elements() {
        let mut samples = vec![
            InstructSample {
                instruction: "a".into(),
                response: "1".into(),
                system: None,
                metadata: None,
            },
            InstructSample {
                instruction: "b".into(),
                response: "2".into(),
                system: None,
                metadata: None,
            },
        ];
        // Verify no panic with 2 elements
        shuffle_samples(&mut samples, 42);
        assert_eq!(samples.len(), 2);
    }

    #[test]
    fn test_cov3_adapters_config_toml_all_overrides() {
        let toml = r#"
[[adapter]]
data = "data/test.jsonl"
checkpoint = "ckpt/test"
label = "full-override"
rank = 64
learning_rate = 0.001
epochs = 20
max_seq_len = 2048
"#;
        let config = AdaptersConfigFile::from_toml(toml).unwrap();
        let base = InstructConfig::default();
        let adapters = config.to_adapter_configs(&base);
        assert_eq!(adapters[0].instruct_config.lora_rank, 64);
        assert!((adapters[0].instruct_config.lora_alpha - 128.0).abs() < f32::EPSILON);
        assert!((adapters[0].instruct_config.learning_rate - 0.001).abs() < f32::EPSILON);
        assert_eq!(adapters[0].instruct_config.epochs, 20);
        assert_eq!(adapters[0].instruct_config.max_seq_len, 2048);
    }

    #[test]
    fn test_cov3_adapters_config_many_adapters() {
        let mut toml_str = String::new();
        for i in 0..10 {
            toml_str.push_str(&format!(
                r#"
[[adapter]]
data = "data/{i}.jsonl"
checkpoint = "ckpt/{i}"
rank = {rank}
"#,
                i = i,
                rank = 4 + i * 2,
            ));
        }
        let config = AdaptersConfigFile::from_toml(&toml_str).unwrap();
        assert_eq!(config.adapters.len(), 10);
        // Verify each has the right rank
        for (i, entry) in config.adapters.iter().enumerate() {
            assert_eq!(entry.rank, Some(4 + i * 2));
        }
    }

    #[test]
    fn test_cov3_adapters_config_toml_missing_required_fields() {
        // Missing checkpoint field
        let toml = r#"
[[adapter]]
data = "data.jsonl"
"#;
        let result = AdaptersConfigFile::from_toml(toml);
        assert!(result.is_err());
    }

    #[test]
    fn test_cov3_adapters_config_toml_missing_data_field() {
        let toml = r#"
[[adapter]]
checkpoint = "ckpt"
"#;
        let result = AdaptersConfigFile::from_toml(toml);
        assert!(result.is_err());
    }

    #[test]
    fn test_cov3_adapters_config_toml_extra_fields_ignored() {
        // Extra fields should be ignored by serde
        let toml = r#"
[[adapter]]
data = "data.jsonl"
checkpoint = "ckpt"
unknown_field = "ignored"
"#;
        // Depending on serde config, this might fail or succeed
        // toml::from_str with #[serde(deny_unknown_fields)] would fail
        // Without it, it succeeds
        let result = AdaptersConfigFile::from_toml(toml);
        // Just verify no panic
        let _ = result;
    }

    #[test]
    fn test_cov3_adapters_config_rank_zero() {
        let toml = r#"
[[adapter]]
data = "data.jsonl"
checkpoint = "ckpt"
rank = 0
"#;
        let config = AdaptersConfigFile::from_toml(toml).unwrap();
        let base = InstructConfig::default();
        let adapters = config.to_adapter_configs(&base);
        assert_eq!(adapters[0].instruct_config.lora_rank, 0);
        assert!((adapters[0].instruct_config.lora_alpha - 0.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_cov3_add_adapter_creates_lora_layers() {
        let mut pipeline =
            MultiAdapterPipeline::new(create_dummy_pipeline(), AdapterSchedule::RoundRobin);
        let config = AdapterConfig {
            data_path: PathBuf::from("data.jsonl"),
            checkpoint_dir: PathBuf::from("/tmp/ckpt"),
            instruct_config: InstructConfig { lora_rank: 4, ..InstructConfig::default() },
        };
        pipeline.add_adapter(config, vec![], vec![]);
        // Adapter should have LoRA layers created from the base model
        // tiny model has 2 layers → 2 * 2 (Q+V) = 4 LoRA layers
        assert_eq!(pipeline.adapters[0].lora_layers.len(), 4);
    }

    #[test]
    fn test_cov3_add_adapter_with_val_samples() {
        let mut pipeline =
            MultiAdapterPipeline::new(create_dummy_pipeline(), AdapterSchedule::RoundRobin);
        let config = AdapterConfig {
            data_path: PathBuf::from("data.jsonl"),
            checkpoint_dir: PathBuf::from("/tmp/ckpt"),
            instruct_config: InstructConfig::default(),
        };
        let val_samples = vec![InstructSample {
            instruction: "val_q".into(),
            response: "val_a".into(),
            system: None,
            metadata: None,
        }];
        pipeline.add_adapter(config, vec![], val_samples);
        assert_eq!(pipeline.adapters[0].val_samples.len(), 1);
        assert_eq!(pipeline.adapters[0].val_samples[0].instruction, "val_q");
    }

    #[test]
    fn test_cov3_add_adapter_initial_state() {
        let mut pipeline =
            MultiAdapterPipeline::new(create_dummy_pipeline(), AdapterSchedule::RoundRobin);
        let config = AdapterConfig {
            data_path: PathBuf::from("data.jsonl"),
            checkpoint_dir: PathBuf::from("/tmp/ckpt_initial"),
            instruct_config: InstructConfig { lora_rank: 8, ..InstructConfig::default() },
        };
        pipeline.add_adapter(config, vec![], vec![]);
        let slot = &pipeline.adapters[0];
        assert_eq!(slot.cursor, 0);
        assert_eq!(slot.best_val_loss, f32::INFINITY);
        assert!(slot.metrics.is_empty());
        assert_eq!(slot.config.lora_rank, 8);
        assert_eq!(slot.checkpoint_dir, PathBuf::from("/tmp/ckpt_initial"));
    }

    #[test]
    fn test_cov3_train_step_adapter_empty_tokens() {
        // Test with empty instruction and response after tokenization
        let mut pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot_with_data(5)],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        // No tokenizer → returns None early
        let result = pipeline.train_step_adapter(0);
        assert!(result.is_none());
        // Cursor should have advanced by 1
        assert_eq!(pipeline.adapters[0].cursor, 1);
    }

    #[test]
    fn test_cov3_batch_train_step_synchronized_mixed_exhaustion() {
        let slot0 = dummy_slot_with_data(3); // has data
        let mut slot1 = dummy_slot_with_data(1);
        slot1.cursor = 1; // exhausted

        let mut pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot0, slot1],
            schedule: AdapterSchedule::Synchronized,
            global_step: 0,
        };

        let results = pipeline.batch_train_step();
        assert_eq!(results.len(), 2);
        // Adapter 1 is exhausted → None
        assert!(results[1].is_none());
    }

    #[test]
    fn test_cov3_batch_train_step_round_robin_cycling() {
        // Verify round-robin cycling by manually advancing global_step
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![
                dummy_slot_with_data(10),
                dummy_slot_with_data(10),
                dummy_slot_with_data(10),
            ],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };

        // Step 0 → adapter 0
        assert_eq!(pipeline.select_next_adapter(), Some(0));
        // Simulate step 1
        let pipeline = MultiAdapterPipeline { global_step: 1, ..pipeline };
        assert_eq!(pipeline.select_next_adapter(), Some(1));
        // Simulate step 2
        let pipeline = MultiAdapterPipeline { global_step: 2, ..pipeline };
        assert_eq!(pipeline.select_next_adapter(), Some(2));
        // Step 3 wraps back to 0
        let pipeline = MultiAdapterPipeline { global_step: 3, ..pipeline };
        assert_eq!(pipeline.select_next_adapter(), Some(0));
    }

    #[test]
    fn test_cov3_reset_epoch_multiple_adapters_independent_seeds() {
        let mut pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![dummy_slot_with_data(20), dummy_slot_with_data(20)],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };

        pipeline.reset_epoch(42);

        // Different adapters should get different shuffle orders
        // (seed + adapter index → different effective seed)
        let order0: Vec<String> =
            pipeline.adapters[0].train_samples.iter().map(|s| s.instruction.clone()).collect();
        let order1: Vec<String> =
            pipeline.adapters[1].train_samples.iter().map(|s| s.instruction.clone()).collect();
        // With different effective seeds, orderings should differ
        assert_ne!(order0, order1, "Different adapters should have different shuffle orders");
    }

    #[test]
    fn test_cov3_adapter_schedule_copy() {
        let s1 = AdapterSchedule::PriorityValLoss;
        let s2 = s1; // Copy
        assert_eq!(s1, s2);
    }

    #[test]
    fn test_cov3_adapters_config_file_clone() {
        let toml = r#"
[[adapter]]
data = "data.jsonl"
checkpoint = "ckpt"
label = "test"
"#;
        let config = AdaptersConfigFile::from_toml(toml).unwrap();
        let cloned = config.clone();
        assert_eq!(cloned.adapters.len(), 1);
        assert_eq!(cloned.adapters[0].label, Some("test".to_string()));
    }

    #[test]
    fn test_cov3_adapter_entry_clone() {
        let toml = r#"
[[adapter]]
data = "data.jsonl"
checkpoint = "ckpt"
rank = 32
learning_rate = 0.001
"#;
        let config = AdaptersConfigFile::from_toml(toml).unwrap();
        let cloned = config.adapters[0].clone();
        assert_eq!(cloned.rank, Some(32));
        assert_eq!(cloned.learning_rate, Some(0.001));
    }

    #[test]
    fn test_cov3_save_adapter_checkpoint_metadata_values() {
        let dir = std::env::temp_dir().join("entrenar_cov3_ckpt_meta");
        let _ = std::fs::remove_dir_all(&dir);

        let mut pipeline =
            MultiAdapterPipeline::new(create_dummy_pipeline(), AdapterSchedule::RoundRobin);
        pipeline.global_step = 42;
        let config = AdapterConfig {
            data_path: PathBuf::from("data.jsonl"),
            checkpoint_dir: dir.clone(),
            instruct_config: InstructConfig {
                lora_rank: 8,
                lora_alpha: 16.0,
                ..InstructConfig::default()
            },
        };
        let samples: Vec<InstructSample> = (0..5)
            .map(|i| InstructSample {
                instruction: format!("q{i}"),
                response: format!("a{i}"),
                system: None,
                metadata: None,
            })
            .collect();
        pipeline.add_adapter(config, samples, vec![]);
        pipeline.adapters[0].best_val_loss = 0.75;

        let ckpt_dir = pipeline.save_adapter_checkpoint(0, 3, 0.42).unwrap();
        let metadata_str = std::fs::read_to_string(ckpt_dir.join("metadata.json")).unwrap();
        let metadata: serde_json::Value = serde_json::from_str(&metadata_str).unwrap();

        assert_eq!(metadata["adapter_index"], 0);
        assert_eq!(metadata["epoch"], 3);
        assert_eq!(metadata["lora_rank"], 8);
        assert_eq!(metadata["train_samples"], 5);
        assert_eq!(metadata["global_step"], 42);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_cov3_save_adapter_checkpoint_multiple_epochs() {
        let dir = std::env::temp_dir().join("entrenar_cov3_multi_epoch");
        let _ = std::fs::remove_dir_all(&dir);

        let mut pipeline =
            MultiAdapterPipeline::new(create_dummy_pipeline(), AdapterSchedule::RoundRobin);
        let config = AdapterConfig {
            data_path: PathBuf::from("data.jsonl"),
            checkpoint_dir: dir.clone(),
            instruct_config: InstructConfig::default(),
        };
        pipeline.add_adapter(config, vec![], vec![]);

        // Save multiple epochs
        for epoch in 0..3 {
            let ckpt_dir =
                pipeline.save_adapter_checkpoint(0, epoch, 1.0 - epoch as f32 * 0.2).unwrap();
            assert!(ckpt_dir.join("metadata.json").exists());
            assert!(ckpt_dir.join("model.safetensors").exists());
        }

        // All three epoch directories should exist
        assert!(dir.join("epoch-0").exists());
        assert!(dir.join("epoch-1").exists());
        assert!(dir.join("epoch-2").exists());

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_cov3_all_exhausted_single_adapter_one_sample() {
        let slot = dummy_slot_with_data(1);
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        assert!(!pipeline.all_exhausted());
    }

    #[test]
    fn test_cov3_all_exhausted_single_adapter_cursor_at_end() {
        let mut slot = dummy_slot_with_data(1);
        slot.cursor = 1;
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot],
            schedule: AdapterSchedule::RoundRobin,
            global_step: 0,
        };
        assert!(pipeline.all_exhausted());
    }

    #[test]
    fn test_cov3_select_priority_single_adapter() {
        let mut slot = dummy_slot();
        slot.best_val_loss = 3.0;
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot],
            schedule: AdapterSchedule::PriorityValLoss,
            global_step: 0,
        };
        assert_eq!(pipeline.select_next_adapter(), Some(0));
    }

    #[test]
    fn test_cov3_select_priority_equal_losses() {
        let mut slot0 = dummy_slot();
        slot0.best_val_loss = 1.0;
        let mut slot1 = dummy_slot();
        slot1.best_val_loss = 1.0;
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![slot0, slot1],
            schedule: AdapterSchedule::PriorityValLoss,
            global_step: 0,
        };
        let result = pipeline.select_next_adapter();
        // With equal losses, max_by picks the last one (stable)
        assert!(result == Some(0) || result == Some(1));
    }

    #[test]
    fn test_cov3_to_adapter_configs_no_overrides() {
        let toml = r#"
[[adapter]]
data = "d.jsonl"
checkpoint = "c"
"#;
        let config = AdaptersConfigFile::from_toml(toml).unwrap();
        let base = InstructConfig {
            lora_rank: 32,
            lora_alpha: 64.0,
            learning_rate: 0.005,
            epochs: 7,
            max_seq_len: 1024,
            gradient_clip_norm: Some(2.0),
            quantize_nf4: true,
        };
        let adapters = config.to_adapter_configs(&base);
        // All base values should be inherited
        assert_eq!(adapters[0].instruct_config.lora_rank, 32);
        assert!((adapters[0].instruct_config.lora_alpha - 64.0).abs() < f32::EPSILON);
        assert!((adapters[0].instruct_config.learning_rate - 0.005).abs() < f32::EPSILON);
        assert_eq!(adapters[0].instruct_config.epochs, 7);
        assert_eq!(adapters[0].instruct_config.max_seq_len, 1024);
        assert_eq!(adapters[0].instruct_config.gradient_clip_norm, Some(2.0));
        assert!(adapters[0].instruct_config.quantize_nf4);
    }

    #[test]
    fn test_cov3_to_adapter_configs_preserves_data_and_checkpoint_paths() {
        let toml = r#"
[[adapter]]
data = "/absolute/path/data.jsonl"
checkpoint = "../relative/ckpt"
"#;
        let config = AdaptersConfigFile::from_toml(toml).unwrap();
        let base = InstructConfig::default();
        let adapters = config.to_adapter_configs(&base);
        assert_eq!(adapters[0].data_path, PathBuf::from("/absolute/path/data.jsonl"));
        assert_eq!(adapters[0].checkpoint_dir, PathBuf::from("../relative/ckpt"));
    }

    #[test]
    fn test_cov3_adapters_config_from_file_invalid_toml() {
        let dir = std::env::temp_dir().join("entrenar_cov3_invalid_toml");
        let _ = std::fs::create_dir_all(&dir);
        let path = dir.join("invalid.toml");
        std::fs::write(&path, "this {{ is not valid TOML").unwrap();
        let result = AdaptersConfigFile::from_file(&path);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("failed to parse"), "Expected parse error, got: {err}");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_cov3_adapter_slot_checkpoint_dir() {
        let slot = AdapterSlot {
            lora_layers: Vec::new(),
            train_samples: Vec::new(),
            val_samples: Vec::new(),
            checkpoint_dir: PathBuf::from("/my/custom/ckpt"),
            metrics: Vec::new(),
            config: InstructConfig::default(),
            cursor: 0,
            best_val_loss: f32::INFINITY,
            #[cfg(feature = "cuda")]
            optimizer_states: None,
            #[cfg(feature = "cuda")]
            lora_step: 0,
        };
        assert_eq!(slot.checkpoint_dir, PathBuf::from("/my/custom/ckpt"));
    }

    #[test]
    fn test_cov3_multi_adapter_schedule_field() {
        let pipeline = MultiAdapterPipeline {
            base_pipeline: create_dummy_pipeline(),
            adapters: vec![],
            schedule: AdapterSchedule::PriorityValLoss,
            global_step: 0,
        };
        assert_eq!(pipeline.schedule, AdapterSchedule::PriorityValLoss);
    }
}