cera 0.2.2

Rust-native LLM inference engine
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
//! Stateful, multimodal, cancellable inference session.
//!
//! `Session` owns a model's `InferenceState` + `Sampler` and drives
//! prefill/decode through a sink-based streaming API. It replaces the
//! one-shot `engine::generate()` so every downstream consumer — CLI,
//! FFI bindings, browser workers, the AIDL service — shares one core.
//!
//! The API is multimodal from day one even though only text is wired
//! in v1: `append_image` and `append_audio` return
//! `CeraError::UnsupportedModality` until the VL / audio loaders land
//! in follow-ups. Callbacks use a `ModalitySink` trait with default-empty
//! methods so text-only consumers override just `on_text_tokens` + `on_done`.

use std::io;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};

use thiserror::Error;

use crate::time::Instant;

use crate::kv_cache::{InferenceState, KvCompression};
use crate::model::Model;
use crate::model::audio_encoder::AudioEncoderWeights;
use crate::sampler::{Sampler, SamplerConfig};
use crate::tokenizer::BpeTokenizer;

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// Per-session configuration. Set at construction; immutable thereafter.
#[derive(Debug, Clone)]
pub struct SessionConfig {
    /// Cap on total tokens held in KV. `None` → model's default `max_seq_len`.
    pub max_seq_len: Option<u32>,
    /// KV cache compression mode.
    pub kv_compression: KvCompression,
    /// Reserved for Phase 1.5 context shift — tokens pinned at the front on overflow. Ignored in 1.1.
    pub n_keep: u32,
    /// Optional deterministic seed for the sampler.
    pub seed: Option<u64>,
    /// Reserved for Phase 1.4 chunked prefill — ubatch size. Ignored in 1.1 (prefill is monolithic).
    pub ubatch_size: u32,
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            max_seq_len: None,
            kv_compression: KvCompression::None,
            n_keep: 0,
            seed: None,
            ubatch_size: 512,
        }
    }
}

/// Per-call generation options.
#[derive(Debug, Clone)]
pub struct GenerateOpts {
    pub max_tokens: u32,
    pub temperature: f32,
    pub top_p: f32,
    pub top_k: u32,
    /// Min-p (relative) nucleus cutoff: drop tokens below `min_p * p_max`. `0.0`
    /// disables it. Applied after top-k/top-p in the stochastic path only.
    pub min_p: f32,
    /// Repetition penalty over tokens generated so far this call (CTRL-style).
    /// `1.0` disables it. Applied in the stochastic path only — greedy/argmax
    /// decoding (`temperature <= 0` or `top_k == 1`) is unaffected.
    pub repetition_penalty: f32,
    /// If any of these fires, decode stops with `FinishReason::Stop`.
    pub stop_tokens: Vec<u32>,
    /// Optional GBNF grammar. When set, decode is constrained: each step masks the
    /// logits to only tokens the grammar accepts (EOS only when the grammar is
    /// complete). Forces off the greedy `forward_greedy` fast path. See [`crate::grammar`].
    pub grammar: Option<Arc<crate::grammar::Grammar>>,
    /// Emit `on_text_tokens` at least every N tokens. `0` treats as 1.
    pub flush_every_tokens: u32,
    /// Emit `on_text_tokens` at least every N milliseconds. `0` disables time-based flushing.
    pub flush_every_ms: u32,
}

impl Default for GenerateOpts {
    fn default() -> Self {
        Self {
            max_tokens: 256,
            temperature: 0.7,
            top_p: 0.9,
            top_k: 40,
            min_p: 0.0,
            repetition_penalty: 1.0,
            stop_tokens: Vec::new(),
            grammar: None,
            flush_every_tokens: 16,
            flush_every_ms: 50,
        }
    }
}

/// Summary returned from a completed `generate` call.
#[derive(Debug, Clone)]
pub struct GenerateSummary {
    pub tokens_generated: u32,
    pub prompt_eval_tokens: u32,
    pub prompt_eval_ms: u32,
    pub decode_ms: u32,
    pub finish_reason: FinishReason,
}

/// Why a decode loop ended.
#[derive(Debug, Clone)]
pub enum FinishReason {
    /// Hit `max_tokens`.
    MaxTokens,
    /// Hit an EOS token or an explicit `stop_tokens` entry.
    Stop,
    /// External `cancel()` flipped the atomic.
    Cancelled,
    /// Reached the session's `max_seq_len`; no room to decode further
    /// without a context shift (landing in Phase 1.5 via `n_keep`).
    ContextFull,
    /// A grammar constraint left no token allowed at this step (the grammar can't be
    /// satisfied by the vocabulary from here). Decode stops rather than spin.
    GrammarDeadEnd,
    /// Other error; the outer `Result` is the authoritative channel.
    Error(String),
}

/// Streaming output sink. Default-empty methods let text-only consumers
/// override just `on_text_tokens` + `on_done`; audio callers override
/// `on_audio_frames` as well.
pub trait ModalitySink {
    fn on_text_tokens(&mut self, _tokens: &[u32]) {}
    fn on_audio_frames(&mut self, _pcm: &[f32], _sample_rate: u32) {}
    fn on_done(&mut self, reason: FinishReason);
}

/// Modality support flags for a loaded model.
#[derive(Debug, Clone, Copy, Default)]
pub struct ModalityCapabilities {
    pub text_in: bool,
    pub text_out: bool,
    pub image_in: bool,
    pub audio_in: bool,
    pub audio_out: bool,
}

impl ModalityCapabilities {
    /// Text-in, text-out only. The baseline for LLaMA-family LLMs.
    pub fn text_only() -> Self {
        Self {
            text_in: true,
            text_out: true,
            ..Default::default()
        }
    }

    /// Text + audio bidirectional — LFM2-Audio-class models: PCM audio
    /// in via [`Session::append_audio`], text + audio frames out via
    /// [`ModalitySink`].
    pub fn text_and_audio() -> Self {
        Self {
            text_in: true,
            text_out: true,
            audio_in: true,
            audio_out: true,
            ..Default::default()
        }
    }

    /// Text + image in, text out — VL-class models (LFM2-VL,
    /// LLaVA-family). Image output is not an LFM2-family capability.
    pub fn text_and_image_in() -> Self {
        Self {
            text_in: true,
            text_out: true,
            image_in: true,
            ..Default::default()
        }
    }

    /// Derive capabilities from a manifest's `inference_type`. Unknown
    /// variants fall back to text-only so a bundle we don't understand
    /// at least reports safe minimums.
    pub fn from_inference_type(it: &crate::manifest::InferenceType) -> Self {
        use crate::manifest::InferenceType::*;
        match it {
            LlamaCppTextToText => Self::text_only(),
            LlamaCppImageToText => Self::text_and_image_in(),
            LlamaCppLfm2AudioV1 => Self::text_and_audio(),
            Unknown(_) => Self::text_only(),
        }
    }
}

/// Error type for session operations. Upstream consumers using
/// `anyhow::Error` can continue to use `?` because `thiserror` derives
/// `std::error::Error` for this type, making it compatible with `anyhow`.
#[derive(Error, Debug)]
pub enum CeraError {
    #[error("modality not supported by this model")]
    UnsupportedModality,
    #[error("inference_type `{0}` is not supported in this version of cera")]
    UnsupportedInferenceType(String),
    #[error("session is busy with another operation")]
    Busy,
    #[error("cancelled")]
    Cancelled,
    #[error("context window ({max_seq_len}) exceeded by {by} tokens")]
    ContextOverflow { max_seq_len: u32, by: u32 },
    #[error("empty input")]
    EmptyInput,
    #[error("token id {id} out of range (vocab_size {vocab_size})")]
    InvalidToken { id: u32, vocab_size: u32 },
    #[error("LoRA adapter incompatible with this model: {0}")]
    LoraDimMismatch(String),
    #[error("backend: {0}")]
    Backend(String),
    #[error("io: {0}")]
    Io(#[from] io::Error),
}

// ---------------------------------------------------------------------------
// Session
// ---------------------------------------------------------------------------

/// Decide whether `append_tokens` may run a `n_keep` context shift
/// instead of returning `ContextOverflow`. Pure 4-input predicate,
/// extracted from the overflow arm so it can be unit-tested without
/// spinning up a full `Session` (which needs a real `BpeTokenizer`).
///
/// All four must hold:
/// - `supports_kv_shift`: backend opted in via [`Model::supports_kv_shift`]
/// - `n_keep > 0`: user wants to preserve a prefix
/// - `!is_compressed`: TurboQuant caches aren't shiftable yet
/// - `current_pos >= n_keep + shift_needed`: the pinned prefix leaves
///   at least `shift_needed` rotatable cells to drop
pub fn can_shift(
    supports_kv_shift: bool,
    n_keep: usize,
    is_compressed: bool,
    current_pos: usize,
    shift_needed: usize,
) -> bool {
    supports_kv_shift && n_keep > 0 && !is_compressed && current_pos >= n_keep + shift_needed
}

/// One slice of a tokenized chat template, distinguishing text runs
/// from image-marker positions. `Text { start, end }` is a half-open
/// index range into the same `tokens` slice that
/// [`splice_image_markers`] received; `Image` is an in-place marker
/// that the caller should swap for the
/// `<|image_start|>` + image embeddings + `<|image_end|>`
/// envelope at append time.
///
/// `Copy` because every variant is either unit (`Image`) or
/// composed of `usize` fields (`Text { start, end }`) — letting the
/// walk loop in [`Session::append_chat_with_images`] match on
/// `*seg` without the borrow-checker friction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ChatTemplateSegment {
    Text { start: usize, end: usize },
    Image,
}

/// Walk a tokenized chat-template stream and produce a splice plan:
/// for each contiguous run of non-marker tokens emit a
/// [`ChatTemplateSegment::Text`] range; for each `<image>` token
/// (id == `image_marker_id`) emit a [`ChatTemplateSegment::Image`].
///
/// Empty text runs (two adjacent markers, marker at start/end of
/// stream) are elided so the segment list never carries
/// zero-length text spans — the caller's `append_tokens(&[])`
/// would be a no-op anyway, but keeping the segment list tight
/// makes the unit-test assertions cleaner and the walk loop
/// branch-free on the empty case.
pub(crate) fn splice_image_markers(
    tokens: &[u32],
    image_marker_id: u32,
) -> Vec<ChatTemplateSegment> {
    let mut segments = Vec::new();
    let mut start = 0;
    for (i, &t) in tokens.iter().enumerate() {
        if t == image_marker_id {
            if i > start {
                segments.push(ChatTemplateSegment::Text { start, end: i });
            }
            segments.push(ChatTemplateSegment::Image);
            start = i + 1;
        }
    }
    if start < tokens.len() {
        segments.push(ChatTemplateSegment::Text {
            start,
            end: tokens.len(),
        });
    }
    segments
}

/// Stateful inference session. Owns refcounted handles to the model
/// and tokenizer — no borrow lifetime — so `Session` values can flow
/// across an FFI boundary or be returned from a constructor without
/// tying them to an owning `CeraEngine`.
///
/// The `Arc`-based design replaced the earlier `Session<'a> { model:
/// &'a dyn Model, tokenizer: &'a BpeTokenizer }` form because UniFFI
/// and bindgen tools don't marshal Rust lifetimes — the exposed type
/// has to own its dependencies.
pub struct Session {
    model: Arc<dyn Model>,
    tokenizer: Arc<BpeTokenizer>,
    state: InferenceState,
    sampler: Sampler,
    /// Total tokens currently in KV.
    current_pos: usize,
    /// Mirror of `current_pos` for lock-free external reads via `position()`.
    position_atomic: Arc<AtomicU32>,
    /// External cancel flag. Checked between tokens during decode.
    cancel: Arc<AtomicBool>,
    /// Logits from the last prefill / decode step — seeds the next generate call.
    last_logits: Option<Vec<f32>>,
    /// Copied from config — enforced on `append_tokens`.
    max_seq_len: usize,
    /// What this session can accept / emit, derived from the model's
    /// inference_type at construction. Immutable for the session's
    /// lifetime.
    capabilities: ModalityCapabilities,
    /// Retained for `reset()` (rebuild state + sampler) and
    /// `sync_sampler_from_opts` (read back the seed).
    config: SessionConfig,
    /// Audio encoder weights, if attached. None for text-only
    /// sessions; populated via [`Self::attach_audio_encoder`] before
    /// [`Self::append_audio`] is called. Held by `Arc` so the same
    /// encoder can back multiple sessions (one per concurrent
    /// generation) without re-loading the ~hundreds-of-MB weights.
    audio_encoder: Option<Arc<AudioEncoderWeights>>,
    /// Vision encoder weights, if attached. None for non-VL
    /// sessions; populated via [`Self::attach_vision_encoder`]
    /// before [`Self::append_image`] is called. Held by `Arc`
    /// for the same reason as `audio_encoder`.
    vision_encoder: Option<Arc<crate::model::vision_encoder::VisionEncoderWeights>>,
    /// Optional cached GPU vision encoder. When present (and the patch
    /// grid fits the GPU attention kernel), [`Self::append_image_with_opts`]
    /// runs the ViT on the GPU instead of the CPU `vision_encoder`; the
    /// CPU encoder above is always kept as the fallback. Attached via
    /// [`Self::attach_gpu_vision_encoder`].
    gpu_vision_encoder: Option<Arc<dyn crate::model::vision_encoder_gpu::VisionGpuEncode>>,
    /// Session-default cap on the longest side of an appended image
    /// (in pixels), honored by every image-append path — including
    /// [`Self::append_chat_with_images`]. `None` = no cap (native
    /// resolution within the model's pixel budget). Set via
    /// [`Self::set_image_max_long_size`]; [`Self::append_image_with_opts`]
    /// takes an explicit per-call override. Preserved across
    /// [`Self::reset`] — it's a preprocessing preference, not KV state.
    image_max_long_size: Option<u32>,
    /// Cached grammar logit-mask (per-token output bytes + EOS/special flags). Built
    /// lazily on the first grammar-constrained `generate` and reused across calls — it
    /// depends only on the tokenizer, not on the grammar. Taken into a local for the
    /// duration of a `generate` (to avoid borrow conflicts with `model`/`sampler`) and
    /// restored before returning. See [`crate::grammar`].
    grammar_mask: Option<crate::grammar::GrammarMask>,
    /// Reusable throwaway state for [`Self::hidden_states_for_tokens`]. Sized to
    /// the prompt via [`InferenceState::for_prefill`] and `clear_for_reuse`d
    /// between calls, so the per-chunk classifier path does ~0 allocation after
    /// warmup and never allocates a full-context KV cache. Separate from the
    /// generation `state`, so extracting hidden states never disturbs an
    /// in-progress conversation. `hs_scratch_cap` records the token capacity it
    /// was built for (rebuild when a longer prompt arrives).
    hs_scratch: Option<InferenceState>,
    hs_scratch_cap: usize,
    /// Attached LoRA adapter, applied to every forward pass on this session
    /// (generation + hidden-states). `None` ⇒ base model. Set via
    /// [`Self::attach_lora_adapters`]; copied onto `state.lora` (and the
    /// hidden-states scratch) so the CPU projection helpers pick it up.
    /// Preserved across [`Self::reset`], like the vision/audio encoders.
    lora: Option<Arc<crate::lora::LoraAdapterWeights>>,
}

impl Session {
    /// Construct a new session backed by an already-loaded model + tokenizer.
    /// Both are taken by `Arc` — in-process callers typically clone from
    /// [`crate::CeraEngine`] (see [`crate::CeraEngine::new_session`]); FFI
    /// callers wrap owned handles.
    ///
    /// `capabilities` declares what the loaded model accepts / emits.
    /// Direct callers (tests, standalone Model loaders) that don't have
    /// a Manifest handy can pass [`ModalityCapabilities::text_only`].
    pub fn new(
        model: Arc<dyn Model>,
        tokenizer: Arc<BpeTokenizer>,
        capabilities: ModalityCapabilities,
        config: SessionConfig,
    ) -> Self {
        let model_cfg = model.config();
        let max_seq_len = config
            .max_seq_len
            .map(|v| v as usize)
            .unwrap_or(model_cfg.max_seq_len)
            .min(model_cfg.max_seq_len);

        // A `n_keep >= max_seq_len` config can never actually shift —
        // `current_pos` tops out at `max_seq_len` and the shift arm
        // requires `current_pos >= n_keep + shift_needed`. Warn once
        // at construction so users see why their `--n-keep` isn't
        // kicking in instead of discovering it via `ContextOverflow`.
        if config.n_keep > 0 && (config.n_keep as usize) >= max_seq_len {
            tracing::warn!(
                target: "cera::session",
                n_keep = config.n_keep,
                max_seq_len,
                "n_keep >= max_seq_len; context shift will never fire \
                 because there's no room left for shifted cells. Lower \
                 n_keep to enable shifting."
            );
        }
        // Likewise, `n_keep > 0` + TurboQuant is a no-op because the
        // overflow arm gates on `!is_compressed()`. Warn once so the
        // user knows their n_keep value is being silently ignored on
        // overflow.
        if config.n_keep > 0 && !matches!(config.kv_compression, KvCompression::None) {
            tracing::warn!(
                target: "cera::session",
                n_keep = config.n_keep,
                "n_keep configured alongside TurboQuant KV compression; \
                 shift not yet supported for compressed caches, so \
                 overflow will still return ContextOverflow. Disable \
                 compression to enable n_keep."
            );
        }
        // Backend must opt in to shift (CPU LFM2 today; Metal is a
        // follow-up). If the user set `n_keep > 0` on a backend that
        // doesn't implement shift, overflow still returns
        // ContextOverflow — tell them why instead of letting them
        // discover it the hard way.
        if config.n_keep > 0 && !model.supports_kv_shift() {
            tracing::warn!(
                target: "cera::session",
                n_keep = config.n_keep,
                architecture = model_cfg.architecture.as_str(),
                "n_keep configured but this backend doesn't support KV shift; \
                 overflow will still return ContextOverflow. CPU backend \
                 (BackendPreference::Cpu) supports shift today; Metal / GPU \
                 paths land in a follow-up."
            );
        }

        let state = InferenceState::from_config_with_compression(model_cfg, &config.kv_compression);

        let sampler_cfg = SamplerConfig {
            seed: config.seed,
            ..SamplerConfig::default()
        };
        let sampler = Sampler::new(sampler_cfg);

        Self {
            model,
            tokenizer,
            state,
            sampler,
            current_pos: 0,
            position_atomic: Arc::new(AtomicU32::new(0)),
            cancel: Arc::new(AtomicBool::new(false)),
            last_logits: None,
            max_seq_len,
            capabilities,
            config,
            audio_encoder: None,
            vision_encoder: None,
            gpu_vision_encoder: None,
            image_max_long_size: None,
            grammar_mask: None,
            hs_scratch: None,
            hs_scratch_cap: 0,
            lora: None,
        }
    }

    /// Attach an audio encoder so [`Self::append_audio`] can encode
    /// PCM samples into LLM-ready embeddings. Callers load the encoder
    /// from the bundle's `multimodal_projector` GGUF via
    /// [`crate::model::audio_encoder::AudioEncoderWeights::from_gguf`].
    ///
    /// Replaces any previously-attached encoder. Preserved across
    /// [`Self::reset`] — the encoder is independent of KV state.
    ///
    /// Does **not** validate that the encoder's `llm_hidden_size`
    /// matches the LLM's `hidden_size`; that check lives on
    /// [`Self::append_audio`] so a stub encoder used in test setup
    /// doesn't have to wire up matching dimensions just to be
    /// attached. Real callers should always pair the encoder with
    /// the LLM it was trained against.
    pub fn attach_audio_encoder(&mut self, encoder: Arc<AudioEncoderWeights>) {
        self.audio_encoder = Some(encoder);
    }

    /// Attach a vision encoder so [`Self::append_image`] can encode
    /// PNG / JPEG bytes into LLM-ready image embeddings. Callers
    /// load the encoder from the bundle's `multimodal_projector`
    /// GGUF via
    /// [`crate::model::vision_encoder::VisionEncoderWeights::from_gguf`].
    /// Mirrors [`Self::attach_audio_encoder`]'s semantics: replaces
    /// any prior attachment, preserved across `reset()`, no
    /// dimension check at attach time (it lives on `append_image`
    /// where we have a real input to size against).
    pub fn attach_vision_encoder(
        &mut self,
        encoder: Arc<crate::model::vision_encoder::VisionEncoderWeights>,
    ) {
        self.vision_encoder = Some(encoder);
    }

    /// Attach a cached GPU vision encoder. When present,
    /// [`Self::append_image_with_opts`] runs the ViT on the GPU for patch
    /// grids within the GPU kernel's capacity
    /// ([`crate::model::vision_encoder_gpu::MAX_VIT_TOKENS`]), falling back
    /// to the CPU `vision_encoder` otherwise. The CPU encoder must still be
    /// attached via [`Self::attach_vision_encoder`] (it backs the fallback
    /// and the capability/dimension checks). Preserved across `reset()`.
    pub fn attach_gpu_vision_encoder(
        &mut self,
        encoder: Arc<dyn crate::model::vision_encoder_gpu::VisionGpuEncode>,
    ) {
        self.gpu_vision_encoder = Some(encoder);
    }

    /// Attach a LoRA adapter (from [`crate::lora::LoraAdapterWeights`]). It's
    /// applied to every subsequent forward pass — generation **and**
    /// hidden-states extraction — until replaced or removed. Replaces any prior
    /// adapter (hot-swap) and is preserved across [`Self::reset`]. Load the
    /// adapter once and share the `Arc` across sessions.
    ///
    /// The adapter's dimensions are validated against the model up front, so an
    /// adapter built for a different model is rejected with
    /// [`CeraError::LoraDimMismatch`] rather than silently corrupting output.
    ///
    /// Note: this only affects tokens processed **after** the call — it does not
    /// retroactively re-adapt KV already in the cache. Attach before prefilling
    /// the context you want adapted (or [`Self::reset`] first).
    pub fn attach_lora_adapters(
        &mut self,
        adapters: Arc<crate::lora::LoraAdapterWeights>,
    ) -> Result<(), CeraError> {
        adapters
            .validate_dims(self.model.config())
            .map_err(|e| CeraError::LoraDimMismatch(e.to_string()))?;
        self.lora = Some(adapters);
        self.state.lora = self.lora.clone();
        Ok(())
    }

    /// Remove any attached LoRA adapter, returning to base-model inference.
    pub fn remove_lora_adapters(&mut self) {
        self.lora = None;
        self.state.lora = None;
    }

    /// Whether a LoRA adapter is currently attached.
    pub fn has_lora_adapters(&self) -> bool {
        self.lora.is_some()
    }

    /// Set the session-default cap on the longest side of an appended
    /// image, in pixels (`None` = no cap). Every image-append path
    /// honors it — including [`Self::append_chat_with_images`], the
    /// recommended multimodal path — so callers can bound image-encode
    /// cost once instead of per call. [`Self::append_image_with_opts`]
    /// takes an explicit per-call override. See that method for the
    /// cap semantics (shrinks the encoded target, never upscales,
    /// takes precedence over the model's `image_min_pixels` floor).
    pub fn set_image_max_long_size(&mut self, max_long_size: Option<u32>) {
        self.image_max_long_size = max_long_size;
    }

    /// What this session accepts as input / emits as output. Derived
    /// from the model's `inference_type` at construction — see
    /// [`ModalityCapabilities::from_inference_type`] for the mapping.
    pub fn capabilities(&self) -> ModalityCapabilities {
        self.capabilities
    }

    /// Borrow the tokenizer the session was constructed with. Useful
    /// for callers (tests, FFI wrappers) that want to encode / decode
    /// without threading the tokenizer through separately.
    pub fn tokenizer(&self) -> &BpeTokenizer {
        self.tokenizer.as_ref()
    }

    /// Borrow the model the session was constructed with. Primarily
    /// for introspection (vocab size, max_seq_len, etc.); hot-path
    /// forward calls still go through `Session`'s own methods.
    pub fn model(&self) -> &dyn Model {
        self.model.as_ref()
    }

    /// Current KV position — tokens live. Atomic; safe from any thread.
    pub fn position(&self) -> u32 {
        self.position_atomic.load(Ordering::Relaxed)
    }

    /// Shared handle to the position counter. Clone into another thread to
    /// watch an in-flight generate's progress without holding `&self` (which
    /// would block on `generate`'s `&mut self` borrow).
    pub fn position_handle(&self) -> Arc<AtomicU32> {
        Arc::clone(&self.position_atomic)
    }

    /// Shared handle to the cancel flag. Clone it into another thread
    /// and call `.store(true, Relaxed)` to interrupt an in-flight generate.
    /// The convenience `cancel()` method does the same for the owning thread.
    pub fn cancel_handle(&self) -> Arc<AtomicBool> {
        Arc::clone(&self.cancel)
    }

    /// Flip the cancel flag. Safe from any thread.
    pub fn cancel(&self) {
        self.cancel.store(true, Ordering::Relaxed);
    }

    /// Clear KV state and reset position to 0. Rebuilds the sampler from
    /// `SessionConfig::seed` so a seeded session is fully reproducible after
    /// reset. Does NOT touch the engine-level disk prefix cache (which lives
    /// on `CeraEngine`, not `Session`).
    pub fn reset(&mut self) {
        let model_cfg = self.model.config();
        self.state =
            InferenceState::from_config_with_compression(model_cfg, &self.config.kv_compression);
        // Re-apply the attached adapter to the rebuilt state (preserved across reset).
        self.state.lora = self.lora.clone();
        self.current_pos = 0;
        self.position_atomic.store(0, Ordering::Relaxed);
        self.last_logits = None;
        self.cancel.store(false, Ordering::Relaxed);
        // Re-seed the sampler so deterministic runs stay deterministic after reset().
        let sampler_cfg = SamplerConfig {
            seed: self.config.seed,
            ..SamplerConfig::default()
        };
        self.sampler = Sampler::new(sampler_cfg);
    }

    /// The model's hidden dimension `D` — the per-token width of the vectors
    /// returned by [`Self::hidden_states_for_tokens`]. Callers reshape the
    /// flattened `[T*D]` result into `[T][D]` with this.
    pub fn hidden_size(&self) -> usize {
        self.model.config().hidden_size
    }

    /// Extract the model's **per-token** last-layer hidden states (post-final
    /// RMSNorm, matching llama.cpp `--pooling none`) for `tokens`.
    ///
    /// Returns a flattened row-major `[n_tokens * hidden_size]` buffer (token
    /// `t`, channel `c` at `t * hidden_size + c`). This is a **side-effect-free**
    /// one-shot prefill: it uses a reused, prompt-sized scratch state and does
    /// NOT advance or disturb the session's generation KV, so it composes with an
    /// already-primed conversation.
    ///
    /// Errors: [`CeraError::EmptyInput`] on empty input;
    /// [`CeraError::UnsupportedModality`] if the backend doesn't implement
    /// hidden-state extraction (probe via [`Model::supports_hidden_states`]);
    /// [`CeraError::InvalidToken`] if any id is `>= vocab_size`.
    pub fn hidden_states_for_tokens(&mut self, tokens: &[u32]) -> Result<Vec<f32>, CeraError> {
        if tokens.is_empty() {
            return Err(CeraError::EmptyInput);
        }
        // Clone the Arc (cheap refcount bump) so the model borrow doesn't
        // conflict with the `&mut self.hs_scratch` borrow below.
        let model = Arc::clone(&self.model);
        if !model.supports_hidden_states() {
            return Err(CeraError::UnsupportedModality);
        }
        // Validate token ids BEFORE dispatch: the model embedding paths
        // `assert!(id < vocab_size)`, and that panic would unwind through the
        // held FFI mutex (poisoning the whole Session) or trap wasm. A bad id
        // (e.g. from a mismatched external tokenizer) must be a typed error.
        let vocab_size = model.config().vocab_size;
        if let Some(&bad) = tokens.iter().find(|&&t| t as usize >= vocab_size) {
            return Err(CeraError::InvalidToken {
                id: bad,
                vocab_size: vocab_size as u32,
            });
        }
        // A prompt longer than the context window would trip an `assert!` in the
        // GPU backends' `hidden_states` (Metal/wgpu), whose panic would unwind
        // through the held FFI mutex or trap wasm. Return a typed overflow error
        // instead — consistent across all backends. (Unlike generation there's no
        // n_keep shift here: extraction is one-shot, so an over-length chunk is a
        // caller error, not something to silently truncate.)
        let max_seq_len = model.config().max_seq_len;
        if tokens.len() > max_seq_len {
            return Err(CeraError::ContextOverflow {
                max_seq_len: max_seq_len as u32,
                by: (tokens.len() - max_seq_len) as u32,
            });
        }
        let n = tokens.len();
        // Reuse the scratch state when it's big enough; else (re)build it sized to
        // this prompt. Store the RAW `n` (not clamped to max_seq_len): otherwise a
        // prompt longer than max_seq_len would compare `cap < n` true on EVERY
        // call and rebuild each time. The KV Vec grows once past the capped
        // reservation and `clear_for_reuse` keeps that capacity. Never allocates a
        // full-context KV cache up front.
        let rebuild = self.hs_scratch.is_none() || self.hs_scratch_cap < n;
        if rebuild {
            self.hs_scratch = Some(InferenceState::for_prefill(model.config(), n));
            self.hs_scratch_cap = n;
        }
        // `get_or_insert_with` (over `as_mut().unwrap()`) keeps clippy's
        // `unnecessary_unwrap` quiet given the `is_none()` in `rebuild` above;
        // the closure never runs (the slot is `Some` after the rebuild block).
        let state = self
            .hs_scratch
            .get_or_insert_with(|| InferenceState::for_prefill(model.config(), n));
        if !rebuild {
            state.clear_for_reuse();
        }
        // Reflect the attached adapter in the extraction (the coordination point:
        // the CPU per-token path applies it via the decode hooks).
        state.lora = self.lora.clone();
        Ok(model.hidden_states(tokens, state))
    }

    /// Like [`Self::hidden_states_for_tokens`] but **mean-pools** over tokens,
    /// returning a single `[hidden_size]` vector. This is the common classifier
    /// path (their head consumes the mean-pooled hidden state) and avoids
    /// shipping the full `[T*D]` matrix across an FFI/WASM boundary.
    pub fn hidden_states_mean_pooled(&mut self, tokens: &[u32]) -> Result<Vec<f32>, CeraError> {
        let d = self.hidden_size();
        let flat = self.hidden_states_for_tokens(tokens)?;
        let t = flat.len() / d;
        debug_assert_eq!(t * d, flat.len(), "hidden states not a multiple of D");
        let mut pooled = vec![0.0f32; d];
        for row in flat.chunks_exact(d) {
            for (p, &x) in pooled.iter_mut().zip(row) {
                *p += x;
            }
        }
        if t > 0 {
            let inv = 1.0 / t as f32;
            pooled.iter_mut().for_each(|p| *p *= inv);
        }
        Ok(pooled)
    }

    /// Tokenize `text` and return its per-token hidden states. Convenience over
    /// [`Self::hidden_states_for_tokens`] (Swift `hiddenStates(for:)`).
    pub fn hidden_states_for_text(&mut self, text: &str) -> Result<Vec<f32>, CeraError> {
        let tokens = self.tokenizer.encode(text);
        self.hidden_states_for_tokens(&tokens)
    }

    /// Tokenize text and append. Convenience over `append_tokens`.
    pub fn append_text(&mut self, text: &str) -> Result<(), CeraError> {
        if text.is_empty() {
            return Err(CeraError::EmptyInput);
        }
        let tokens = self.tokenizer.encode(text);
        self.append_tokens(&tokens)
    }

    /// Append PCM audio input to the session's context. Runs the
    /// samples through the attached audio encoder (mel + Conformer +
    /// MLP adapter) and prefills the resulting per-frame hidden
    /// states into KV via [`Self::append_embeddings`].
    ///
    /// `samples` is f32 PCM in `[-1, 1]`, mono. `sample_rate` must
    /// match [`crate::model::audio_encoder::SAMPLE_RATE`] (16 kHz);
    /// resampling is out of scope — caller is expected to resample
    /// externally if their source rate differs.
    ///
    /// Errors are checked in the order listed. The first matching
    /// condition wins — e.g. an empty `samples` buffer paired with
    /// an audio-incapable session returns `UnsupportedModality`,
    /// not `EmptyInput`.
    ///
    /// 1. [`CeraError::UnsupportedModality`] when the loaded model
    ///    doesn't support audio input
    ///    ([`Self::capabilities`]`.audio_in == false`).
    /// 2. [`CeraError::Backend`] with a "no encoder attached" message
    ///    when the model supports audio but
    ///    [`Self::attach_audio_encoder`] hasn't been called yet.
    /// 3. [`CeraError::Backend`] when the attached encoder's
    ///    `llm_hidden_size` doesn't match the LLM's `hidden_size`
    ///    (wrong-bundle encoder).
    /// 4. [`CeraError::Backend`] on sample-rate mismatch.
    /// 5. [`CeraError::EmptyInput`] when `samples` is empty *or* the
    ///    audio is too short to produce any encoder frames (less than
    ///    one window after center-padded STFT).
    /// 6. [`CeraError::ContextOverflow`] / [`CeraError::Cancelled`]
    ///    propagated from the underlying [`Self::append_embeddings`]
    ///    call.
    pub fn append_audio(&mut self, samples: &[f32], sample_rate: u32) -> Result<(), CeraError> {
        if !self.capabilities.audio_in {
            return Err(CeraError::UnsupportedModality);
        }
        let Some(encoder) = self.audio_encoder.as_ref() else {
            return Err(CeraError::Backend(
                "Session::append_audio: no audio encoder attached. Call \
                 attach_audio_encoder() with weights loaded via \
                 AudioEncoderWeights::from_gguf(...) on the bundle's \
                 multimodal_projector GGUF before calling append_audio."
                    .to_string(),
            ));
        };
        // Catch encoder/LLM dimension mismatch upfront with a clear
        // message naming both sides. Without this, `append_embeddings`
        // would still reject the resulting buffer downstream — but
        // with a generic shape error that doesn't point at the real
        // cause (encoder loaded from a different bundle than the LLM).
        let llm_hidden = self.model.config().hidden_size;
        let enc_hidden = encoder.config.llm_hidden_size;
        if enc_hidden != llm_hidden {
            return Err(CeraError::Backend(format!(
                "Session::append_audio: attached encoder's llm_hidden_size ({enc_hidden}) \
                 does not match the LLM's hidden_size ({llm_hidden}). \
                 The encoder must be the multimodal_projector trained for the \
                 currently-loaded LLM."
            )));
        }
        if sample_rate != crate::model::audio_encoder::SAMPLE_RATE {
            return Err(CeraError::Backend(format!(
                "Session::append_audio: sample_rate {} != {} required by \
                 encoder (resampling is out of scope; resample externally \
                 before passing samples in)",
                sample_rate,
                crate::model::audio_encoder::SAMPLE_RATE,
            )));
        }
        if samples.is_empty() {
            return Err(CeraError::EmptyInput);
        }
        let (embeddings, n_frames) =
            crate::model::audio_encoder::encode_audio_pcm(samples, encoder.as_ref());
        if n_frames == 0 {
            // Sub-window-length input: log_mel_spectrogram produced
            // zero frames. Caller's audio was too short to encode
            // anything; surface as EmptyInput rather than slicing
            // the empty embedding buffer downstream.
            return Err(CeraError::EmptyInput);
        }
        self.append_embeddings(&embeddings, n_frames)
    }

    /// Append raw token IDs, running a prefill pass from the current position
    /// over just the new tail.
    ///
    /// Prefill runs through [`Model::forward_prefill_chunked`] with
    /// `SessionConfig::ubatch_size` so long prompts can be cancelled
    /// mid-flight. Returns `CeraError::Cancelled` when cancel fires
    /// before the full slice is consumed.
    ///
    /// On cancellation:
    /// - Tokens already fed through the kernel stay in KV; `position()`
    ///   advances to reflect how many were actually consumed.
    /// - `last_logits` is **cleared** (not set to the partial-prefill
    ///   logits). This forces a subsequent `generate()` to return
    ///   `EmptyInput` rather than silently producing tokens from
    ///   mid-prompt state. The caller's contract is to clear the flag
    ///   via [`Self::clear_cancel`] and resume by appending the
    ///   unconsumed tail before generating. Sketch:
    ///
    ///   ```ignore
    ///   let before = session.position() as usize;
    ///   match session.append_tokens(&tokens) {
    ///       Err(CeraError::Cancelled) => {
    ///           let consumed = session.position() as usize - before;
    ///           session.clear_cancel();
    ///           session.append_tokens(&tokens[consumed..])?;
    ///       }
    ///       other => other?,
    ///   }
    ///   ```
    pub fn append_tokens(&mut self, tokens: &[u32]) -> Result<(), CeraError> {
        if tokens.is_empty() {
            return Err(CeraError::EmptyInput);
        }
        let new_end = self
            .current_pos
            .checked_add(tokens.len())
            .ok_or(CeraError::Backend("position overflow".into()))?;
        if new_end > self.max_seq_len {
            // `n_keep` context shift (Phase 1.5): if the backend
            // supports shift, the session was configured with
            // `n_keep > 0`, the state isn't TurboQuant-compressed, and
            // the pinned prefix leaves room to drop — shift to make
            // room. Otherwise fall through to the typed ContextOverflow.
            let n_keep = self.config.n_keep as usize;
            let shift_needed = new_end - self.max_seq_len;
            if !can_shift(
                self.model.supports_kv_shift(),
                n_keep,
                self.state.is_compressed(),
                self.current_pos,
                shift_needed,
            ) {
                return Err(CeraError::ContextOverflow {
                    max_seq_len: self.max_seq_len as u32,
                    by: (new_end - self.max_seq_len) as u32,
                });
            }
            self.model.shift_kv(&mut self.state, n_keep, shift_needed);
            let before = self.current_pos;
            self.current_pos -= shift_needed;
            self.position_atomic
                .store(self.current_pos as u32, Ordering::Relaxed);
            // Pre-shift `last_logits` corresponded to position `before - 1`;
            // the positions they encode don't exist anymore. Clear so a
            // subsequent `generate()` that bypasses the upcoming prefill
            // doesn't silently emit from the wrong context.
            self.last_logits = None;
            tracing::info!(
                target: "cera::kv_shift",
                n_keep = n_keep,
                shift = shift_needed,
                seq_len_before = before,
                seq_len_after = self.current_pos,
                "kv context shift"
            );
        }
        // Pass `ubatch_size` straight through — the trait method treats
        // 0 as "no chunking" (single chunk = whole input), matching the
        // CLI `--ubatch-size 0` opt-out.
        let (consumed, logits) = self.model.forward_prefill_chunked(
            tokens,
            self.current_pos,
            &mut self.state,
            self.config.ubatch_size as usize,
            &self.cancel,
        );
        self.current_pos += consumed;
        self.position_atomic
            .store(self.current_pos as u32, Ordering::Relaxed);
        if consumed < tokens.len() {
            // Don't stash the partial-prefill logits. They correspond to
            // the chunk boundary, not the intended end of prompt — letting
            // a subsequent `generate()` read them would silently produce
            // text from mid-prompt state. Force the caller to re-append
            // (or `reset`) before generating.
            self.last_logits = None;
            Err(CeraError::Cancelled)
        } else {
            self.last_logits = logits;
            Ok(())
        }
    }

    /// Append a sequence of pre-computed hidden-dim embeddings —
    /// the soft-token analog of [`Self::append_tokens`].
    ///
    /// Each row of `embeddings` is fed straight into the model
    /// at the LLM's input-embedding stage, bypassing the
    /// `embed_tokens` lookup. Used for non-text input modalities
    /// where an external encoder produces hidden states directly
    /// (e.g. the LFM2A audio encoder's per-frame output via
    /// [`crate::model::audio_encoder::encode_audio_pcm`]).
    ///
    /// `embeddings` is a flat row-major buffer of length
    /// `n_tokens * hidden_size`. Position advances by `n_tokens`.
    /// Returns `Err(EmptyInput)` for `n_tokens == 0`,
    /// `Err(Backend(...))` for shape mismatch.
    ///
    /// Mirrors `append_tokens`'s context-shift logic
    /// (`n_keep`-aware) and `last_logits` semantics. Cancellation
    /// is checked between `ubatch_size`-sized chunks (granularity:
    /// one chunk); on cancel, `last_logits` is cleared and
    /// `Err(Cancelled)` is returned with the frames processed so
    /// far still in KV (caller can `clear_cancel` and resume from
    /// `position()` like `append_tokens`).
    ///
    /// Dispatches to [`Model::forward_prefill_from_embeddings`]
    /// in `ubatch`-sized chunks, mirroring
    /// [`Model::forward_prefill_chunked`] for tokens. Backends
    /// with a true batched embedding-prefill path (CPU `Lfm2Model`)
    /// process a whole chunk per call and amortize per-layer GEMM
    /// dispatch across frames; the trait default falls back to a
    /// per-frame `forward_from_embedding` loop, preserving
    /// correctness for backends that haven't overridden.
    pub fn append_embeddings(
        &mut self,
        embeddings: &[f32],
        n_tokens: usize,
    ) -> Result<(), CeraError> {
        if n_tokens == 0 {
            return Err(CeraError::EmptyInput);
        }
        // Backend capability check: surface a typed error instead
        // of the default `unimplemented!` panic on backends that
        // don't implement `forward_from_embedding`.
        if !self.model.supports_embedding_input() {
            return Err(CeraError::UnsupportedModality);
        }
        let hidden_size = self.model.config().hidden_size;
        let expected_len = n_tokens.checked_mul(hidden_size).ok_or_else(|| {
            CeraError::Backend("append_embeddings: n_tokens * hidden_size overflow".into())
        })?;
        if embeddings.len() != expected_len {
            return Err(CeraError::Backend(format!(
                "append_embeddings: embeddings.len() ({}) != n_tokens ({n_tokens}) * hidden_size ({hidden_size}) = {expected_len}",
                embeddings.len()
            )));
        }

        let new_end = self
            .current_pos
            .checked_add(n_tokens)
            .ok_or(CeraError::Backend("position overflow".into()))?;
        if new_end > self.max_seq_len {
            // Same `n_keep` context-shift logic as append_tokens.
            let n_keep = self.config.n_keep as usize;
            let shift_needed = new_end - self.max_seq_len;
            if !can_shift(
                self.model.supports_kv_shift(),
                n_keep,
                self.state.is_compressed(),
                self.current_pos,
                shift_needed,
            ) {
                return Err(CeraError::ContextOverflow {
                    max_seq_len: self.max_seq_len as u32,
                    by: (new_end - self.max_seq_len) as u32,
                });
            }
            self.model.shift_kv(&mut self.state, n_keep, shift_needed);
            let before = self.current_pos;
            self.current_pos -= shift_needed;
            self.position_atomic
                .store(self.current_pos as u32, Ordering::Relaxed);
            self.last_logits = None;
            tracing::info!(
                target: "cera::kv_shift",
                n_keep = n_keep,
                shift = shift_needed,
                seq_len_before = before,
                seq_len_after = self.current_pos,
                "kv context shift (append_embeddings)"
            );
        }

        // Chunk over `ubatch_size` frames, calling the batched
        // embedding-prefill once per chunk. Position advances by
        // chunk size after each call. Cancel is checked AFTER each
        // chunk so we always make progress on at least one chunk
        // before observing the flag — mirrors
        // `forward_prefill_chunked`'s "always-one-chunk" guarantee
        // and avoids leaving the session wedged on an entry-time
        // cancel. `ubatch == 0` means "no chunking" (one call
        // covering all frames), matching CLI `--ubatch-size 0`.
        let ubatch = self.config.ubatch_size as usize;
        let chunk_size = if ubatch == 0 { n_tokens } else { ubatch };
        let mut last_logits: Option<Vec<f32>> = None;
        let mut ti = 0usize;
        while ti < n_tokens {
            let end = (ti + chunk_size).min(n_tokens);
            let chunk = &embeddings[ti * hidden_size..end * hidden_size];
            let logits = self.model.forward_prefill_from_embeddings(
                chunk,
                end - ti,
                self.current_pos,
                &mut self.state,
            );
            self.current_pos += end - ti;
            self.position_atomic
                .store(self.current_pos as u32, Ordering::Relaxed);
            last_logits = Some(logits);
            ti = end;
            // Only abort if more frames remain — guarantees ≥ 1
            // chunk of progress before observing the flag.
            if self.cancel.load(Ordering::Relaxed) && ti < n_tokens {
                self.last_logits = None;
                return Err(CeraError::Cancelled);
            }
        }

        self.last_logits = last_logits;
        Ok(())
    }

    /// Clear the cancel flag. Call this after handling a
    /// [`CeraError::Cancelled`] from `append_tokens` / `generate` when
    /// you want to resume work on the same session (append more tokens,
    /// generate again) without rebuilding it via [`Self::reset`].
    pub fn clear_cancel(&self) {
        self.cancel.store(false, Ordering::Relaxed);
    }

    /// Append an image input. Decodes PNG / JPEG bytes, resizes
    /// to the encoder's native input size, normalises with the
    /// encoder's per-channel mean / std, runs the ViT + projector
    /// forward to produce 64 image tokens × `projection_dim`, and
    /// splices them into the LLM prefill stream at the current
    /// position via [`Self::append_embeddings`].
    ///
    /// **Placement matters.** The model was trained on a specific
    /// surrounding-token envelope (LFM2-VL: `<|image_start|>` /
    /// `<|image_end|>` *inside* the user-turn opening
    /// `<|im_start|>user\n…<|im_end|>` block). Calling
    /// `append_image` at the wrong stream position — before the
    /// `<bos>` token, outside the user turn, or without the
    /// model-specific markers — leaves the LLM unable to
    /// interpret the embeddings as visual content; the visible
    /// failure mode is a generic non-image-conditioned
    /// description (e.g. *"I see a complex and abstract scene
    /// with various shapes…"*).
    ///
    /// **Recommended path:**
    /// [`Self::append_chat_with_images`] handles render +
    /// marker-walk + envelope splice in one call. It's the right
    /// path for any LFM2-VL inference driven by the standard chat
    /// template.
    ///
    /// Use this method directly only when you need the manual
    /// splice — e.g. a non-LFM2-VL model with a different envelope
    /// convention, or custom token routing the helper doesn't
    /// support. Manual recipe:
    ///
    /// ```ignore
    /// let img_start = tokenizer.special_token_id("<|image_start|>")?;
    /// let img_end   = tokenizer.special_token_id("<|image_end|>")?;
    /// session.append_tokens(&prefix_tokens)?;          // BOS + <|im_start|>user\n
    /// session.append_tokens(&[img_start])?;
    /// session.append_image(&jpeg_bytes)?;
    /// session.append_tokens(&[img_end])?;
    /// session.append_tokens(&suffix_tokens)?;          // user text + <|im_end|>\n + asst tag
    /// session.generate(&opts, &mut sink)?;
    /// ```
    ///
    /// `cera/tests/vl_bundle_load.rs::vl_bundle_appends_synthetic_image`
    /// is the reference integration recipe (now via the helper).
    ///
    /// Errors:
    /// 1. [`CeraError::EmptyInput`] when `bytes` is empty.
    /// 2. [`CeraError::UnsupportedModality`] if the session
    ///    capabilities don't include `image_in` (non-VL bundle).
    /// 3. [`CeraError::Backend`] when no vision encoder is
    ///    attached (text-only construction of a VL bundle, or
    ///    test setup that skipped `attach_vision_encoder`).
    /// 4. [`CeraError::Backend`] when image decode / resize
    ///    fails (corrupt PNG, unsupported format, etc.).
    /// 5. [`CeraError::Backend`] when the encoder's
    ///    `projection_dim` doesn't match the LLM's `hidden_size`
    ///    (mismatched mmproj loaded against a different LLM).
    /// 6. [`CeraError::ContextOverflow`] / [`CeraError::Cancelled`]
    ///    propagated from [`Self::append_embeddings`].
    pub fn append_image(&mut self, bytes: &[u8]) -> Result<(), CeraError> {
        self.append_image_with_opts(bytes, self.image_max_long_size)
    }

    /// Like [`Self::append_image`], but with an explicit per-call cap
    /// (`max_long_size`) on the longest side of the **encoded** image,
    /// overriding the session default ([`Self::set_image_max_long_size`]).
    ///
    /// When `Some(n)`, the resize target is shrunk (aspect-preserving,
    /// re-aligned) so its longer side is at most `n` pixels — a
    /// caller-controlled quality/cost knob (smaller = fewer image
    /// tokens, faster, less detail). Each dimension is floored at one
    /// aligned patch block (`patch_size · scale_factor`), so a very
    /// small `n` rounds the encoded long side up to that minimum rather
    /// than below it. The cap only ever *shrinks* the target (it never
    /// upscales) and **takes precedence over the model's
    /// `image_min_pixels` floor** — passing a small `n` is an explicit
    /// request to trade detail for cost, down to one aligned patch
    /// block. `None` (or `0`) applies no cap. See
    /// [`crate::model::vision_preprocessor::preprocess_image_with_opts`].
    ///
    /// Errors are identical to [`Self::append_image`].
    #[cfg(feature = "vl-preprocess")]
    pub fn append_image_with_opts(
        &mut self,
        bytes: &[u8],
        max_long_size: Option<u32>,
    ) -> Result<(), CeraError> {
        // No empty-bytes check here: an empty input is caught by
        // `preprocess_image_with_opts` below (which returns
        // `EmptyInput`), so a third copy of the guard would be
        // redundant. The capability/encoder checks run first so a
        // non-VL session still reports `UnsupportedModality`.
        if !self.capabilities.image_in {
            return Err(CeraError::UnsupportedModality);
        }
        let Some(encoder) = self.vision_encoder.as_ref() else {
            return Err(CeraError::Backend(
                "Session::append_image: no vision encoder attached. \
                 Construct via CeraEngine on a VL bundle so the \
                 encoder is auto-attached, or call \
                 attach_vision_encoder(...) in test setup."
                    .into(),
            ));
        };
        let llm_hidden = self.model.config().hidden_size;
        let proj_dim = encoder.config.projection_dim;
        if proj_dim != llm_hidden {
            return Err(CeraError::Backend(format!(
                "Session::append_image: vision encoder's projection_dim \
                 ({proj_dim}) does not match LLM hidden_size ({llm_hidden}). \
                 The mmproj must pair with the LLM it was trained against."
            )));
        }
        let pre = crate::model::vision_preprocessor::preprocess_image_with_opts(
            bytes,
            &encoder.config,
            max_long_size,
        )?;
        // Prefer the cached GPU encoder when one is attached and the patch
        // grid fits the GPU attention kernel's capacity; otherwise (or for
        // oversized grids) use the CPU encoder. The output is identical in
        // shape and numerically equivalent either way.
        let grid_tokens = pre.grid_w.saturating_mul(pre.grid_h);
        let gpu = self
            .gpu_vision_encoder
            .as_ref()
            .filter(|_| grid_tokens <= crate::model::vision_encoder_gpu::MAX_VIT_TOKENS);
        let img_tokens = if let Some(gpu) = gpu {
            match gpu.encode_image(&pre.pixels, pre.grid_w, pre.grid_h) {
                Ok(tokens) => tokens,
                // A GPU runtime failure (device lost, OOM, command-buffer
                // error) must not abort the append: the CPU encoder is always
                // attached as the documented fallback and produces numerically
                // equivalent output. Degrade to it instead of failing.
                Err(e) => {
                    tracing::warn!("gpu vision encode failed ({e:#}); falling back to CPU encoder");
                    encoder
                        .encode_image(&pre.pixels, pre.grid_w, pre.grid_h)
                        .map_err(|e| CeraError::Backend(format!("encode_image: {e:#}")))?
                }
            }
        } else {
            encoder
                .encode_image(&pre.pixels, pre.grid_w, pre.grid_h)
                .map_err(|e| CeraError::Backend(format!("encode_image: {e:#}")))?
        };
        // Sanity-check the encoder output shape before handing off
        // to `append_embeddings`. Integer division below would
        // silently truncate a non-multiple length and surface as a
        // less actionable mismatch error from `append_embeddings`.
        if img_tokens.len() % proj_dim != 0 {
            return Err(CeraError::Backend(format!(
                "Session::append_image: encode_image returned {} f32s, \
                 not a multiple of projection_dim ({proj_dim}) — encoder \
                 produced a malformed image-token tensor",
                img_tokens.len(),
            )));
        }
        let n_tokens = img_tokens.len() / proj_dim;
        if n_tokens == 0 {
            return Err(CeraError::Backend(
                "Session::append_image: encoder produced zero image tokens \
                 (preprocess + encode succeeded but yielded an empty tensor)"
                    .into(),
            ));
        }
        self.append_embeddings(&img_tokens, n_tokens)
    }

    /// Stub `append_image_with_opts` for builds without `vl-preprocess`.
    /// Same signature as the real method so conditionally-compiled
    /// callers (FFI / wasm) still type-check; always returns
    /// `UnsupportedModality`. (`append_image` delegates here, so it
    /// needs no separate stub.)
    #[cfg(not(feature = "vl-preprocess"))]
    pub fn append_image_with_opts(
        &mut self,
        _bytes: &[u8],
        _max_long_size: Option<u32>,
    ) -> Result<(), CeraError> {
        Err(CeraError::UnsupportedModality)
    }

    /// Append a multimodal chat conversation in one call: render the
    /// chat template (which emits `<image>` markers for each
    /// [`crate::tokenizer::ContentItem::Image`] in the messages),
    /// then walk the resulting token stream and splice in
    /// `<|image_start|>` + image embeddings + `<|image_end|>` for
    /// each marker. The `images` slice maps positionally onto
    /// `<image>` markers in render order — the order they appear in
    /// the messages' content lists.
    ///
    /// This is the recommended path for VL inference: it replaces
    /// the manual splicing example documented on
    /// [`Self::append_image`]. The manual path stays available for
    /// callers with non-LFM2-VL chat templates or custom token
    /// routing.
    ///
    /// All validation runs *before* any [`Self::append_tokens`] /
    /// [`Self::append_image`] call, so a failed render or a
    /// marker-count mismatch leaves session state untouched.
    ///
    /// Errors:
    /// 1. [`CeraError::UnsupportedModality`] when the session
    ///    capabilities don't include `image_in` (non-VL bundle).
    /// 2. [`CeraError::Backend`] when the model has no chat
    ///    template, when `<image>` doesn't tokenize to a single
    ///    token (model isn't VL-shaped), when the tokenizer is
    ///    missing the `<|image_start|>` / `<|image_end|>` special
    ///    tokens, or when the marker count doesn't match the
    ///    supplied `images.len()`.
    /// 3. Any error from [`Self::append_tokens`] /
    ///    [`Self::append_image`] propagates once splicing begins.
    #[cfg(feature = "vl-preprocess")]
    pub fn append_chat_with_images(
        &mut self,
        messages: &[crate::tokenizer::ChatMessageMultimodal],
        images: &[&[u8]],
        add_generation_prompt: bool,
    ) -> Result<(), CeraError> {
        if !self.capabilities.image_in {
            return Err(CeraError::UnsupportedModality);
        }

        // 1. Render template.
        let rendered =
            crate::tokenizer::apply_chat_template(&self.tokenizer, messages, add_generation_prompt)
                .map_err(|e| CeraError::Backend(format!("chat template render: {e:#}")))?;

        // 2. Resolve `<image>` token id (probe once, error if not a
        //    single token — that means the vocab doesn't actually
        //    have `<image>` as a merged token, i.e. not a VL model).
        let probed = self.tokenizer.encode("<image>");
        if probed.len() != 1 {
            return Err(CeraError::Backend(format!(
                "tokenizer doesn't have `<image>` as a single token \
                 (got {} tokens) — model isn't VL-shaped",
                probed.len(),
            )));
        }
        let image_marker_id = probed[0];

        // 3. Resolve special tokens for the image envelope.
        let img_start = self
            .tokenizer
            .special_token_id("<|image_start|>")
            .ok_or_else(|| {
                CeraError::Backend(
                    "tokenizer missing `<|image_start|>` special token — \
                     model isn't VL-shaped"
                        .into(),
                )
            })?;
        let img_end = self
            .tokenizer
            .special_token_id("<|image_end|>")
            .ok_or_else(|| {
                CeraError::Backend(
                    "tokenizer missing `<|image_end|>` special token — \
                     model isn't VL-shaped"
                        .into(),
                )
            })?;

        // 4. Tokenize the rendered text + walk for marker positions.
        //    Splice plan is computed eagerly so we can validate the
        //    marker count BEFORE mutating session state.
        let tokens = self.tokenizer.encode(&rendered);
        let segments = splice_image_markers(&tokens, image_marker_id);
        let marker_count = segments
            .iter()
            .filter(|s| matches!(s, ChatTemplateSegment::Image))
            .count();
        if marker_count != images.len() {
            return Err(CeraError::Backend(format!(
                "rendered chat template has {marker_count} `<image>` \
                 markers but caller supplied {} images",
                images.len(),
            )));
        }

        // 5. Walk segments and feed the session. Past this point
        //    state is mutated; failures propagate.
        let mut img_idx = 0;
        for seg in &segments {
            match *seg {
                ChatTemplateSegment::Text { start, end } => {
                    self.append_tokens(&tokens[start..end])?;
                }
                ChatTemplateSegment::Image => {
                    self.append_tokens(&[img_start])?;
                    self.append_image(images[img_idx])?;
                    self.append_tokens(&[img_end])?;
                    img_idx += 1;
                }
            }
        }
        Ok(())
    }

    /// Stub for builds without `vl-preprocess`. Same signature so
    /// shared code (wasm / mobile) that conditionally calls into
    /// VL still type-checks; always returns `UnsupportedModality`.
    #[cfg(not(feature = "vl-preprocess"))]
    pub fn append_chat_with_images(
        &mut self,
        _messages: &[crate::tokenizer::ChatMessageMultimodal],
        _images: &[&[u8]],
        _add_generation_prompt: bool,
    ) -> Result<(), CeraError> {
        Err(CeraError::UnsupportedModality)
    }

    /// Run autoregressive decode, emitting token chunks through the sink.
    /// Returns a summary with timing + finish reason. The sink also receives
    /// `on_done(finish_reason)` at the end; callers can treat the `Result`
    /// as authoritative and use `on_done` for UI cleanup.
    pub fn generate<S: ModalitySink + ?Sized>(
        &mut self,
        opts: &GenerateOpts,
        sink: &mut S,
    ) -> Result<GenerateSummary, CeraError> {
        // Reset cancel at the start of each generate — stale flips from a
        // prior call shouldn't pre-cancel the next one.
        self.cancel.store(false, Ordering::Relaxed);

        let prompt_eval_tokens = self.current_pos as u32;
        // Synthetic prompt-eval time: prefill already happened in append_*.
        // We don't re-time it here. (Real per-chunk timing arrives with 1.4.)
        let prompt_eval_ms: u32 = 0;

        let decode_start = Instant::now();
        let mut finish = FinishReason::MaxTokens;
        let mut generated: u32 = 0;
        let mut pos = self.current_pos;
        let mut pending: Vec<u32> = Vec::with_capacity(opts.flush_every_tokens.max(1) as usize);
        let mut last_flush = Instant::now();

        let flush_n = opts.flush_every_tokens.max(1) as usize;
        let flush_ms = opts.flush_every_ms;

        // Early exit before consuming logits or touching the RNG. A no-op
        // `generate()` at full context or with max_tokens=0 has zero
        // side effects — important for stochastic split-generation
        // reproducibility and for callers polling capacity.
        if opts.max_tokens == 0 {
            sink.on_done(FinishReason::MaxTokens);
            let decode_ms = decode_start.elapsed().as_millis() as u32;
            return Ok(GenerateSummary {
                tokens_generated: 0,
                prompt_eval_tokens,
                prompt_eval_ms,
                decode_ms,
                finish_reason: FinishReason::MaxTokens,
            });
        }
        if self.current_pos >= self.max_seq_len {
            sink.on_done(FinishReason::ContextFull);
            let decode_ms = decode_start.elapsed().as_millis() as u32;
            return Ok(GenerateSummary {
                tokens_generated: 0,
                prompt_eval_tokens,
                prompt_eval_ms,
                decode_ms,
                finish_reason: FinishReason::ContextFull,
            });
        }

        // Take the prefill logits. In stochastic mode we keep them pristine
        // across the whole loop and store back at exit for chainable
        // multi-call `generate()`. In greedy mode, logits are only used
        // for the INITIAL argmax; subsequent tokens come from
        // `forward_greedy()` which skips the vocab-sized GPU→CPU readback
        // and returns the argmax token directly — a real win on Metal
        // (~hundreds of μs per token saved at 64 K vocab).
        let mut logits = self.last_logits.take().ok_or(CeraError::EmptyInput)?;

        // Greedy mode is decided once per generate call: deterministic
        // argmax + `forward_greedy`. Stochastic mode samples with RNG +
        // `forward` (keeps logits, supports chaining).
        //
        // Grammar masking needs the full logit vector at every step, so it is
        // incompatible with the `forward_greedy` fast path (which argmaxes inside the
        // model and never returns logits). When a grammar is active we always take the
        // logits-returning path; `want_greedy` still picks argmax-vs-sample over the
        // *masked* logits, so `--temperature 0 --grammar ...` stays deterministic.
        let want_greedy = opts.temperature <= 0.0 || opts.top_k == 1;
        let greedy = want_greedy && opts.grammar.is_none();

        // Grammar matcher + per-token output-byte mask. The mask depends only on the
        // tokenizer (not the grammar), so build it once (O(vocab)) and cache it on the
        // session; subsequent grammar-constrained calls reuse it. It's `take`n into a
        // local for the loop (so the borrow doesn't conflict with `model`/`sampler`) and
        // restored after. A candidate-pruning trie is a future optimization.
        let grammar_active = opts.grammar.is_some();
        if grammar_active && self.grammar_mask.is_none() {
            let vocab = self.tokenizer.vocab_size();
            let mut token_bytes = Vec::with_capacity(vocab);
            let mut special = Vec::with_capacity(vocab);
            for id in 0..vocab as u32 {
                token_bytes.push(self.tokenizer.token_output_bytes(id));
                special.push(self.tokenizer.is_special_token(id));
            }
            self.grammar_mask = Some(crate::grammar::GrammarMask::new(
                token_bytes,
                self.tokenizer.eos_token(),
                special,
            ));
        }
        let grammar_mask = if grammar_active {
            self.grammar_mask.take()
        } else {
            None
        };
        let mut grammar_state = opts
            .grammar
            .as_ref()
            .map(|g| crate::grammar::GrammarState::new(g.clone()));

        // Stochastic-only state. Allocating the scratch buffer and syncing
        // the sampler are skipped in greedy mode where neither is touched.
        let mut sample_scratch: Vec<f32> = if greedy {
            Vec::new()
        } else {
            self.sync_sampler_from_opts(opts);
            Vec::with_capacity(logits.len())
        };

        // Greedy-mode token state: the first token comes from `cpu_argmax`
        // on the prefill logits; each subsequent iteration's token comes
        // from the previous `forward_greedy()` return value. No RNG is
        // touched in this path — argmax is deterministic.
        let mut greedy_next: u32 = if greedy {
            crate::sampler::cpu_argmax(&logits)
        } else {
            0
        };

        // Decode loop. One body handles both modes, branching on `greedy`:
        //
        //   Stop checks (no RNG, no forward)
        //   ├─ greedy:     token = greedy_next
        //   └─ stochastic: token = sampler.sample(scratch)  (one RNG advance)
        //   EOS check
        //   Emit + flush
        //   ├─ greedy:     greedy_next = forward_greedy(&[token], pos)  (no vocab readback)
        //   └─ stochastic: logits = forward(&[token], pos)              (keeps logits)
        //   pos += 1, second cancel check
        //
        // Stochastic sampling happens INSIDE the loop body so the RNG
        // advances exactly once per emitted token (plus once on EOS).
        // That preserves seeded-split-generation reproducibility: a
        // single `generate(N)` advances RNG the same number of steps as
        // two `generate(N/2)` calls with the same seed.
        loop {
            if self.cancel.load(Ordering::Relaxed) {
                finish = FinishReason::Cancelled;
                break;
            }
            if generated >= opts.max_tokens {
                break;
            }
            if pos >= self.max_seq_len {
                finish = FinishReason::ContextFull;
                break;
            }

            let token = if greedy {
                greedy_next
            } else {
                sample_scratch.clear();
                sample_scratch.extend_from_slice(&logits);
                if let Some(state) = grammar_state.as_ref() {
                    // Mask logits to grammar-allowed tokens (EOS only when complete).
                    let allowed = grammar_mask
                        .as_ref()
                        .expect("grammar_mask present when grammar_state is")
                        .apply(state, &mut sample_scratch);
                    if allowed == 0 {
                        finish = FinishReason::GrammarDeadEnd;
                        break;
                    }
                }
                if want_greedy {
                    crate::sampler::cpu_argmax(&sample_scratch)
                } else {
                    self.sampler.sample(&mut sample_scratch)
                }
            };

            // Stop on EOS or an explicit stop token — but when a grammar is active, only
            // once it permits termination. Otherwise an early stop token could truncate
            // mid-derivation (e.g. exit mid-JSON), breaking the conformance guarantee.
            // (EOS is already mask-gated to `is_complete`; this also gates `stop_tokens`.)
            let stop_allowed = grammar_state.as_ref().is_none_or(|s| s.is_complete());
            if stop_allowed
                && (self.tokenizer.eos_token() == Some(token) || opts.stop_tokens.contains(&token))
            {
                finish = FinishReason::Stop;
                break;
            }

            // Advance the grammar by the chosen (grammar-valid, non-EOS) token's bytes.
            if let Some(state) = grammar_state.as_mut() {
                state.accept(grammar_mask.as_ref().unwrap().token_bytes(token));
            }

            pending.push(token);
            generated += 1;

            let should_flush_n = pending.len() >= flush_n;
            let should_flush_t =
                flush_ms > 0 && last_flush.elapsed().as_millis() >= flush_ms as u128;
            if should_flush_n || should_flush_t {
                sink.on_text_tokens(&pending);
                pending.clear();
                last_flush = Instant::now();
            }

            if greedy {
                // Fast path: argmax on GPU, returns the 4-byte next token.
                // Skips the vocab-sized logits readback. `logits` goes stale
                // — that's fine, greedy mode never reads it after the
                // initial argmax.
                greedy_next = self.model.forward_greedy(&[token], pos, &mut self.state);
            } else {
                // Stochastic: full forward. Logits stay pristine for the
                // next iteration's sample and for chaining across calls.
                logits = self.model.forward(&[token], pos, &mut self.state);
            }
            pos += 1;
            self.position_atomic.store(pos as u32, Ordering::Relaxed);

            if self.cancel.load(Ordering::Relaxed) {
                finish = FinishReason::Cancelled;
                break;
            }
        }

        // Restore the cached grammar mask for reuse by the next grammar-constrained call.
        if grammar_active {
            self.grammar_mask = grammar_mask;
        }

        if !pending.is_empty() {
            sink.on_text_tokens(&pending);
        }

        self.current_pos = pos;
        self.position_atomic
            .store(self.current_pos as u32, Ordering::Relaxed);

        // Chain support:
        //
        // - Stochastic: `logits` holds the most recent `forward()` output
        //   (pristine). Save so the next `generate()` can continue
        //   without an intervening `append_tokens`.
        //
        // - Greedy, `generated > 0`: at least one `forward_greedy()` ran,
        //   advancing state and leaving `logits` stale (never read after
        //   the initial argmax). Clear — honest "nothing to save."
        //   Subsequent greedy `generate()` needs an `append_tokens` first,
        //   matching the standard chat loop (append user → generate →
        //   append next user → generate).
        //
        // - Greedy, `generated == 0`: we broke before any `forward_greedy`
        //   (e.g., cancel-before-first-iter, or the first predicted token
        //   was already EOS). `logits` still holds the untouched prefill
        //   distribution; restoring it keeps the session usable for a
        //   retry without the caller having to re-prefill.
        if greedy && generated > 0 {
            self.last_logits = None;
        } else {
            self.last_logits = Some(logits);
        }

        sink.on_done(finish.clone());

        let decode_ms = decode_start.elapsed().as_millis() as u32;
        Ok(GenerateSummary {
            tokens_generated: generated,
            prompt_eval_tokens,
            prompt_eval_ms,
            decode_ms,
            finish_reason: finish,
        })
    }

    fn sync_sampler_from_opts(&mut self, opts: &GenerateOpts) {
        // `Sampler::new` rebuilds the RNG from the seed; for per-call opts
        // updates within the same session we just replace the config.
        let cfg = SamplerConfig {
            temperature: opts.temperature,
            top_k: opts.top_k as usize,
            top_p: opts.top_p,
            min_p: opts.min_p,
            repetition_penalty: opts.repetition_penalty,
            seed: self.config.seed,
        };
        self.sampler.set_config(cfg);
        // Repetition penalty references tokens emitted this call only — start
        // each generation with a clean slate so penalties don't leak across
        // independent `generate()` calls on a reused session. Note: this makes
        // the split-generation seed equivalence (one `generate(N)` == two
        // `generate(N/2)`) hold only at `repetition_penalty == 1.0`; with a
        // penalty active the chained calls see a smaller history window each.
        self.sampler.reset_history();
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn capabilities_from_inference_type_covers_every_variant() {
        let text = ModalityCapabilities::from_inference_type(&InferenceType::LlamaCppTextToText);
        assert!(text.text_in && text.text_out);
        assert!(!text.audio_in && !text.audio_out && !text.image_in);

        let audio = ModalityCapabilities::from_inference_type(&InferenceType::LlamaCppLfm2AudioV1);
        assert!(audio.text_in && audio.text_out);
        assert!(audio.audio_in && audio.audio_out);
        assert!(!audio.image_in);

        // VL bundles report `text_and_image_in` now that
        // `Session::append_image` is fully wired (Phase 3 slice 1).
        let vl = ModalityCapabilities::from_inference_type(&InferenceType::LlamaCppImageToText);
        assert!(vl.text_in && vl.text_out && vl.image_in);
        assert!(!vl.audio_in && !vl.audio_out);

        // Unknown variants fall back to text-only so an unfamiliar bundle
        // at least reports safe minimums rather than crashing.
        let unknown = ModalityCapabilities::from_inference_type(&InferenceType::Unknown(
            "llama.cpp/x".into(),
        ));
        assert!(unknown.text_in && unknown.text_out);
        assert!(!unknown.audio_in && !unknown.audio_out && !unknown.image_in);
    }

    /// A trivial sink that records text tokens + done calls in order, for
    /// asserting stream shape without needing a real model.
    #[derive(Default)]
    struct RecordingSink {
        tokens: Vec<u32>,
        done: Option<FinishReason>,
        flushes: u32,
    }

    impl ModalitySink for RecordingSink {
        fn on_text_tokens(&mut self, tokens: &[u32]) {
            self.tokens.extend_from_slice(tokens);
            self.flushes += 1;
        }
        fn on_done(&mut self, reason: FinishReason) {
            self.done = Some(reason);
        }
    }

    #[test]
    fn session_config_default_is_sane() {
        let c = SessionConfig::default();
        assert_eq!(c.n_keep, 0);
        assert_eq!(c.ubatch_size, 512);
        assert!(matches!(c.kv_compression, KvCompression::None));
    }

    #[test]
    fn generate_opts_default_batching() {
        let o = GenerateOpts::default();
        assert_eq!(o.flush_every_tokens, 16);
        assert_eq!(o.flush_every_ms, 50);
    }

    #[test]
    fn capabilities_text_only_shape() {
        let c = ModalityCapabilities::text_only();
        assert!(c.text_in && c.text_out);
        assert!(!c.image_in && !c.audio_in && !c.audio_out);
    }

    #[test]
    fn recording_sink_collects_tokens() {
        let mut s = RecordingSink::default();
        s.on_text_tokens(&[1, 2, 3]);
        s.on_text_tokens(&[4]);
        s.on_done(FinishReason::MaxTokens);
        assert_eq!(s.tokens, vec![1, 2, 3, 4]);
        assert_eq!(s.flushes, 2);
        assert!(matches!(s.done, Some(FinishReason::MaxTokens)));
    }

    // Integration tests that need a real model live under
    // `cera/tests/session_chain.rs` (gated behind `#[ignore]` and a
    // `find_model()` helper so they skip silently when no GGUF is
    // available locally). Unit tests here stay dep-free.

    /// Token stream with no `<image>` markers collapses to a single
    /// `Text` segment covering the whole range.
    #[test]
    fn splice_image_markers_no_markers_one_text_run() {
        let segs = splice_image_markers(&[1, 2, 3, 4], 99);
        assert_eq!(segs, vec![ChatTemplateSegment::Text { start: 0, end: 4 }]);
    }

    /// Single mid-stream marker splits into Text - Image - Text.
    #[test]
    fn splice_image_markers_mid_stream() {
        let segs = splice_image_markers(&[1, 2, 99, 3, 4], 99);
        assert_eq!(
            segs,
            vec![
                ChatTemplateSegment::Text { start: 0, end: 2 },
                ChatTemplateSegment::Image,
                ChatTemplateSegment::Text { start: 3, end: 5 },
            ]
        );
    }

    /// Marker at index 0: leading text run is elided so the segment
    /// list stays tight (no zero-length spans).
    #[test]
    fn splice_image_markers_at_start() {
        let segs = splice_image_markers(&[99, 1, 2], 99);
        assert_eq!(
            segs,
            vec![
                ChatTemplateSegment::Image,
                ChatTemplateSegment::Text { start: 1, end: 3 },
            ]
        );
    }

    /// Marker at the final index: trailing text run is elided.
    #[test]
    fn splice_image_markers_at_end() {
        let segs = splice_image_markers(&[1, 2, 99], 99);
        assert_eq!(
            segs,
            vec![
                ChatTemplateSegment::Text { start: 0, end: 2 },
                ChatTemplateSegment::Image,
            ]
        );
    }

    /// Two adjacent markers: empty-text-run between them is elided.
    #[test]
    fn splice_image_markers_adjacent_markers() {
        let segs = splice_image_markers(&[1, 99, 99, 2], 99);
        assert_eq!(
            segs,
            vec![
                ChatTemplateSegment::Text { start: 0, end: 1 },
                ChatTemplateSegment::Image,
                ChatTemplateSegment::Image,
                ChatTemplateSegment::Text { start: 3, end: 4 },
            ]
        );
    }

    /// Two well-separated markers — the canonical multi-image case.
    /// Verifies image count round-trips for caller validation.
    #[test]
    fn splice_image_markers_two_separated() {
        let segs = splice_image_markers(&[1, 99, 2, 99, 3], 99);
        let images = segs
            .iter()
            .filter(|s| matches!(s, ChatTemplateSegment::Image))
            .count();
        assert_eq!(images, 2);
        assert_eq!(
            segs,
            vec![
                ChatTemplateSegment::Text { start: 0, end: 1 },
                ChatTemplateSegment::Image,
                ChatTemplateSegment::Text { start: 2, end: 3 },
                ChatTemplateSegment::Image,
                ChatTemplateSegment::Text { start: 4, end: 5 },
            ]
        );
    }

    /// All-marker stream — no text runs at all.
    #[test]
    fn splice_image_markers_all_markers() {
        let segs = splice_image_markers(&[99, 99, 99], 99);
        assert_eq!(
            segs,
            vec![
                ChatTemplateSegment::Image,
                ChatTemplateSegment::Image,
                ChatTemplateSegment::Image,
            ]
        );
    }

    /// Empty stream — empty segment list.
    #[test]
    fn splice_image_markers_empty() {
        let segs = splice_image_markers(&[], 99);
        assert!(segs.is_empty());
    }
}