fxtranslate 0.4.2

Rust reimplementation of the Firefox Translations inference engine, validated against the C++ translator-cli.
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
//! Dynamic transformer execution and greedy decoding.
//!
//! Assembles the ops into the Bergamot architecture for arbitrary input: a
//! 6-layer transformer **encoder** (bidirectional self-attention + FFN) runs
//! once; a 4-layer **SSRU decoder** (recurrent cell + cross-attention + FFN)
//! runs per step, carrying one cell-state vector per layer. Greedy decoding
//! argmaxes the tied output projection each step until EOS.
//!
//! All GEMMs go through the shifted int8 affine ([`Weights::affine`]); the clean
//! float parts (layernorm, softmax, attention, elementwise) use [`crate::ops`].
//! Greedy decoding is single-sentence; [`Engine::encode_batch`] adds a padded,
//! mask-attention batched encoder for translating a block of sentences together.

use std::cell::RefCell;
use std::f32::consts::FRAC_PI_2;

use crate::ops;
use crate::shortlist::Shortlist;
use crate::spm::SpmVocab;
use crate::weights::{Config, Weights};

/// Layer-norm epsilon (layers/generic.h:463).
const EPS: f32 = 1e-6;

/// The translation engine: model weights + source/target vocabularies.
pub struct Engine {
    weights: Weights,
    src_vocab: SpmVocab,
    trg_vocab: SpmVocab,
    config: Config,
    /// Sinusoidal positional-encoding frequencies and offsets, length `dim`.
    pe_freq: Vec<f32>,
    pe_offs: Vec<f32>,
    /// Optional lexical shortlist restricting the output vocabulary per sentence.
    shortlist: Option<Shortlist>,
    /// Whether source and target share a vocabulary (affects shortlist candidates).
    shared_vocab: bool,
    /// Worker-thread count for the data-parallel batch path (feature `threads`).
    /// `1` = serial. Set via [`Engine::with_threads`]; the weights are shared, so
    /// more workers cost only per-thread activation scratch, not more model copies.
    #[cfg(feature = "threads")]
    threads: usize,
}

// The engine holds only immutable state after load (weights are packed once and
// read-only; all per-call scratch is thread-local), so it is `Sync` and can be
// shared by reference across the data-parallel workers. Assert it at compile time
// so a future field with interior mutability can't silently break the invariant.
#[cfg(feature = "threads")]
const _: fn() = || {
    fn assert_sync<T: Sync>() {}
    assert_sync::<Engine>();
};

thread_local! {
    /// Per-thread full-vocab logits buffer for the batched projection, so each decode
    /// step doesn't allocate a fresh `[active, vocab]` vector. Thread-local (not an
    /// `Engine` field) so one `Engine` can be shared across worker threads (feature
    /// `threads`) while each thread reuses its own buffer with no contention.
    static LOGITS_SCRATCH: RefCell<Vec<f32>> = const { RefCell::new(Vec::new()) };
}

/// Per-sentence wall-clock timing from [`Engine::translate_timed`], in the spans
/// the perf harness reports: encode, time-to-first-token, and full decode.
pub struct Timing {
    /// Source tokenization + encoder pass.
    pub encode_ms: f64,
    /// Decode time to the first emitted token (excludes encode). TTFT is
    /// `encode_ms + first_token_ms`.
    pub first_token_ms: f64,
    /// Total greedy-loop time.
    pub decode_ms: f64,
    /// Tokens generated (excludes the terminal EOS).
    pub out_tokens: usize,
}

/// Per-block wall-clock timing from [`Engine::translate_batch_timed`].
pub struct BlockTiming {
    /// Batched encode of the whole block.
    pub encode_ms: f64,
    /// Decode time to the block's first token (excludes encode).
    pub first_token_ms: f64,
    /// Total batched decode-loop time for the block.
    pub decode_ms: f64,
    /// Sentences in the block.
    pub sentences: usize,
    /// Total source tokens across the block (spm subwords + EOS per sentence).
    pub src_tokens: usize,
    /// Total tokens generated across the block (excludes EOS).
    pub tokens: usize,
}

/// A phase boundary reported by [`Engine::translate_batch_phased`], so a host
/// without a usable `Instant` (wasm32, where `std::time::Instant` panics) can
/// time each phase itself with its own clock (`performance.now()`). The callback
/// fires at the same boundaries the native `--timing` path measures with
/// `Instant`, so host-timed spans line up with the native ones:
///
/// - [`Phase::EncodeStart`] — before the batched encode.
/// - [`Phase::DecodeStart`] — encode done, before the decode loop (this is the
///   encode/decode split; the decode span includes cross-attention K/V prep, as
///   in [`Engine::translate_batch_timed`]).
/// - [`Phase::FirstToken`] — the first decode step has emitted; the host's
///   `DecodeStart → FirstToken` gap is the block's first-token latency.
/// - [`Phase::DecodeEnd`] — the decode loop finished.
///
/// This exists only to move the *clock* to the host; it computes no durations and
/// touches no math, so the native `Instant`-based `--timing` path is unaffected.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Phase {
    EncodeStart,
    DecodeStart,
    FirstToken,
    DecodeEnd,
}

/// Token counts for one block from [`Engine::translate_batch_phased`] — the
/// numerators/denominators the host needs to turn its own phase timings into
/// words/s, TTFT, and decode tok/s (the host supplies the durations).
pub struct BlockCounts {
    /// Sentences in the block.
    pub sentences: usize,
    /// Total source tokens across the block (spm subwords + EOS per sentence).
    pub src_tokens: usize,
    /// Total tokens generated across the block (excludes EOS).
    pub tokens: usize,
}

/// Encoder output for a batch of sentences: `[batch, seq, dim]` row-major, padded
/// to `seq` = the batch's max source length. `lens[b]` is sentence `b`'s true
/// length, so callers ignore the pad rows.
pub struct BatchedContext {
    pub data: Vec<f32>,
    pub batch: usize,
    pub seq: usize,
    pub dim: usize,
    pub lens: Vec<usize>,
}

impl BatchedContext {
    /// Valid (unpadded) encoder rows for sentence `b`: `[lens[b], dim]`.
    pub fn sentence(&self, b: usize) -> &[f32] {
        let stride = self.seq * self.dim;
        &self.data[b * stride..b * stride + self.lens[b] * self.dim]
    }
}

impl Engine {
    /// Build from a model file and the source/target `.spm` vocabularies. For
    /// most pairs the two vocab paths are identical; for CJK they differ.
    pub fn load(
        model_path: impl AsRef<std::path::Path>,
        src_vocab_path: impl AsRef<std::path::Path>,
        trg_vocab_path: impl AsRef<std::path::Path>,
    ) -> Result<Engine, String> {
        let shared = src_vocab_path.as_ref() == trg_vocab_path.as_ref();
        let weights = Weights::load(model_path)?;
        let src_vocab = SpmVocab::load(src_vocab_path).map_err(|e| e.to_string())?;
        let trg_vocab = SpmVocab::load(trg_vocab_path).map_err(|e| e.to_string())?;
        let mut engine = Engine::new(weights, src_vocab, trg_vocab);
        engine.shared_vocab = shared;
        Ok(engine)
    }

    /// Like [`Engine::load`] but memory-maps the model file (feature `mmap`, on
    /// under `fast`): weight tensors are views into the mapping rather than owned
    /// heap copies.
    #[cfg(feature = "mmap")]
    pub fn load_mmapped(
        model_path: impl AsRef<std::path::Path>,
        src_vocab_path: impl AsRef<std::path::Path>,
        trg_vocab_path: impl AsRef<std::path::Path>,
    ) -> Result<Engine, String> {
        let shared = src_vocab_path.as_ref() == trg_vocab_path.as_ref();
        let weights = Weights::load_mmapped(model_path)?;
        let src_vocab = SpmVocab::load(src_vocab_path).map_err(|e| e.to_string())?;
        let trg_vocab = SpmVocab::load(trg_vocab_path).map_err(|e| e.to_string())?;
        let mut engine = Engine::new(weights, src_vocab, trg_vocab);
        engine.shared_vocab = shared;
        Ok(engine)
    }

    /// Like [`Engine::load`] but builds from in-memory buffers instead of file
    /// paths: the model and both `.spm` vocabularies are parsed from bytes and the
    /// weight tensors copied to owned heap storage, so the engine borrows nothing
    /// from the passed slices. This is the byte-path entry the wasm build uses,
    /// where the host supplies the model/vocab bytes rather than a filesystem.
    ///
    /// Pass the same slice (or byte-identical content) for `src_vocab` and
    /// `trg_vocab` on shared-vocab pairs; distinct buffers for split-vocab (CJK).
    pub fn from_bytes(model: &[u8], src_vocab: &[u8], trg_vocab: &[u8]) -> Result<Engine, String> {
        let shared = src_vocab == trg_vocab;
        let weights = Weights::from_bytes(model)?;
        let src_vocab = SpmVocab::from_bytes(src_vocab);
        let trg_vocab = SpmVocab::from_bytes(trg_vocab);
        let mut engine = Engine::new(weights, src_vocab, trg_vocab);
        engine.shared_vocab = shared;
        Ok(engine)
    }

    /// Attach a lexical shortlist so decoding restricts the output vocabulary to
    /// the per-sentence candidate set (required for exact reference parity).
    pub fn with_shortlist(mut self, shortlist: Shortlist) -> Engine {
        self.shortlist = Some(shortlist);
        self
    }

    /// Like [`Engine::with_shortlist`] but parses the shortlist from an in-memory
    /// buffer ([`Shortlist::from_bytes`]) — the byte-path counterpart for the wasm
    /// build, where the host supplies the shortlist bytes.
    pub fn with_shortlist_bytes(self, shortlist: &[u8]) -> Engine {
        self.with_shortlist(Shortlist::from_bytes(shortlist))
    }

    pub fn new(weights: Weights, src_vocab: SpmVocab, trg_vocab: SpmVocab) -> Engine {
        let config = weights.config();
        let d = config.dim_emb;
        let t = d / 2;
        // PE(pos)[c] = sin(pos*freq[c] + offs[c]); rotor form (transformer.h:95).
        let mut pe_freq = vec![0.0f32; d];
        let mut pe_offs = vec![0.0f32; d];
        for c in 0..d {
            pe_freq[c] = 1e-4f32.powf((c % t) as f32 / (t as f32 - 1.0));
            pe_offs[c] = (c / t) as f32 * FRAC_PI_2;
        }
        Engine {
            weights,
            src_vocab,
            trg_vocab,
            config,
            pe_freq,
            pe_offs,
            shortlist: None,
            shared_vocab: true,
            #[cfg(feature = "threads")]
            threads: 1,
        }
    }

    /// Set the worker-thread count for the data-parallel batch path
    /// ([`translate_batch`](Engine::translate_batch) / [`greedy_batch`](Engine::greedy_batch)).
    /// `0` auto-detects the machine's parallelism; `1` keeps it serial. The weights
    /// are shared across workers, so this trades cores for throughput at the cost of
    /// only per-thread activation scratch — no extra copy of the model.
    ///
    /// Only present under the `threads` feature. Per-sentence output is identical to
    /// the serial path regardless of thread count (the batch is partitioned into
    /// independent sentences), so this never changes a translation.
    #[cfg(feature = "threads")]
    pub fn with_threads(mut self, n: usize) -> Engine {
        self.threads = match n {
            0 => std::thread::available_parallelism()
                .map(|v| v.get())
                .unwrap_or(1),
            n => n,
        };
        self
    }

    /// Expose source tokenization for debugging.
    pub fn src_ids(&self, text: &str) -> Vec<u32> {
        self.src_vocab.encode_with_eos(text)
    }

    /// Tokenize `text`, run greedy decoding, and detokenize the result.
    ///
    /// This is the raw single-sequence path: `text` is fed to the decoder whole,
    /// so input longer than the model's context window truncates (the decoder
    /// emits EOS early — see `tests/translate.rs`). For long or multi-sentence
    /// input use [`translate_long`](Engine::translate_long), which segments first.
    pub fn translate(&self, text: &str) -> String {
        let src_ids = self.src_vocab.encode_with_eos(text);
        let out_ids = self.greedy(&src_ids);
        self.trg_vocab.decode(&out_ids)
    }

    /// Translate long `text` by splitting it into sentences with `seg` and
    /// translating each within the model's context window, then rejoining with the
    /// original inter-sentence whitespace ([`segment::reassemble`]).
    ///
    /// Each sentence is decoded independently — no context is shared across
    /// sentences. Piped/stdin input can't assume adjacent sentences are related;
    /// a batched document-level translator that exploits cross-sentence context is
    /// future work. A sentence that already fits the window (the common case) is
    /// translated byte-for-byte as [`translate`](Engine::translate) would; only a
    /// single sentence exceeding the window is hard-wrapped (see
    /// [`translate_within_window`](Engine::translate_within_window)).
    ///
    /// [`segment::reassemble`]: crate::segment::reassemble
    pub fn translate_segmented(&self, text: &str, seg: &dyn crate::segment::Segmenter) -> String {
        let spans = seg.sentences(text);
        let outputs: Vec<String> = spans
            .iter()
            .map(|s| self.translate_within_window(s.of(text)))
            .collect();
        crate::segment::reassemble(text, &spans, &outputs)
    }

    /// Translate long `text` with the best available segmenter: the Unicode
    /// [`IcuSegmenter`](crate::segment::IcuSegmenter) when the `icu-segmenter`
    /// feature is on, else the built-in [`BasicSegmenter`](crate::segment::BasicSegmenter).
    pub fn translate_long(&self, text: &str) -> String {
        #[cfg(feature = "icu-segmenter")]
        {
            self.translate_segmented(text, &crate::segment::IcuSegmenter::new())
        }
        #[cfg(not(feature = "icu-segmenter"))]
        {
            self.translate_segmented(text, &crate::segment::BasicSegmenter)
        }
    }

    /// Translate one sentence assumed to be a single unit. If it fits the context
    /// window it is translated whole (identical to [`translate`](Engine::translate));
    /// otherwise it is hard-wrapped into window-sized token slices whose
    /// translations are concatenated — accepting a seam. Marian does the same
    /// (`max-length-break` wrapping); a single sentence over ~127 tokens is rare.
    fn translate_within_window(&self, sentence: &str) -> String {
        let mut ids = self.src_vocab.encode(sentence);
        let eos = self.src_vocab.eos_id();
        if ids.len() <= crate::segment::MAX_SOURCE_TOKENS {
            ids.push(eos);
            return self.trg_vocab.decode(&self.greedy(&ids));
        }
        let mut out = String::new();
        for slice in ids.chunks(crate::segment::MAX_SOURCE_TOKENS) {
            let mut piece = slice.to_vec();
            piece.push(eos);
            out.push_str(&self.trg_vocab.decode(&self.greedy(&piece)));
        }
        out
    }

    /// Like [`translate`], but returns wall-clock [`Timing`] for the perf harness
    /// (`--timing`). Mirrors [`greedy`] with `Instant` markers around encode and
    /// the decode loop; the small duplication keeps timing out of the hot path.
    pub fn translate_timed(&self, text: &str) -> (String, Timing) {
        use std::time::Instant;
        let d = self.config.dim_emb;
        let src_ids = self.src_vocab.encode_with_eos(text);
        let seq = src_ids.len();

        let t_enc = Instant::now();
        let context = self.encode(&src_ids);
        let encode_ms = t_enc.elapsed().as_secs_f64() * 1e3;

        let eos = self.trg_vocab.eos_id();
        let mut cells = vec![vec![0.0f32; d]; self.config.dec_depth + 1];
        let max_len = ((2.0 * seq as f32).ceil() as usize + 4).min(256);
        let candidates = self
            .shortlist
            .as_ref()
            .map(|s| s.candidates(&src_ids, self.shared_vocab));

        let t_dec = Instant::now();
        let mut first_token_ms = 0.0;
        let mut out = Vec::new();
        let mut prev = eos;
        for step in 0..max_len {
            let top = self.decode_step(prev, step, &context, seq, &mut cells);
            let next = self.project_argmax(&top, candidates.as_deref());
            if step == 0 {
                first_token_ms = t_dec.elapsed().as_secs_f64() * 1e3;
            }
            if next == eos {
                break;
            }
            out.push(next);
            prev = next;
        }
        let decode_ms = t_dec.elapsed().as_secs_f64() * 1e3;
        let timing = Timing {
            encode_ms,
            first_token_ms,
            decode_ms,
            out_tokens: out.len(),
        };
        (self.trg_vocab.decode(&out), timing)
    }

    /// Greedy decode: encode the source, then argmax the tied projection each
    /// step, carrying SSRU cell state, until EOS or the length cap.
    pub fn greedy(&self, src_ids: &[u32]) -> Vec<u32> {
        let d = self.config.dim_emb;
        let seq = src_ids.len();
        let context = self.encode(src_ids);
        let eos = self.trg_vocab.eos_id();

        // One SSRU cell-state vector per decoder layer (1-based index; slot 0 unused).
        let mut cells = vec![vec![0.0f32; d]; self.config.dec_depth + 1];

        // max output length = ceil(factor * src_len), capped (config max-length-factor 2.0).
        let max_len = ((2.0 * seq as f32).ceil() as usize + 4).min(256);

        // The shortlist candidate set is per-sentence — computed once. Split
        // vocabs (CJK) pass `shared = false`, so source token ids are not copied
        // into the target candidate set; the lexical translations still are.
        let candidates = self
            .shortlist
            .as_ref()
            .map(|s| s.candidates(src_ids, self.shared_vocab));

        let mut out = Vec::new();
        let mut prev = eos; // decoder is seeded with EOS
        for step in 0..max_len {
            let top = self.decode_step(prev, step, &context, seq, &mut cells);
            let next = self.project_argmax(&top, candidates.as_deref());
            if next == eos {
                break;
            }
            out.push(next);
            prev = next;
        }
        out
    }

    /// Pick the next token for each active row of one decode step, updating
    /// `done`/`out`/`prev`. `tops` is `[active.len(), dim]` — already compacted to
    /// the rows still decoding (the decoder body no longer computes finished
    /// rows), and `active[i]` is row `i`'s original batch index. When no shortlist
    /// is attached (the default), the full-vocab projection is batched across all
    /// active rows in one GEMM (streaming the vocab weight once per batch); with a
    /// shortlist, candidate sets differ per row, so it projects per row. Rows are
    /// independent, so the tokens are identical either way.
    fn select_active(
        &self,
        active: &[usize],
        tops: &[f32],
        cands: &[Option<Vec<u32>>],
        eos: u32,
        prev: &mut [u32],
        out: &mut [Vec<u32>],
        done: &mut [bool],
    ) {
        let d = self.config.dim_emb;
        let n = active.len();

        if self.shortlist.is_none() {
            let vocab = self.weights.output_vocab();
            LOGITS_SCRATCH.with_borrow_mut(|logits| {
                self.weights.full_logits_batch_into(tops, n, logits);
                for (i, &b) in active.iter().enumerate() {
                    let next = argmax(&logits[i * vocab..(i + 1) * vocab]);
                    if next == eos {
                        done[b] = true;
                    } else {
                        out[b].push(next);
                        prev[b] = next;
                    }
                }
            });
        } else {
            for (i, &b) in active.iter().enumerate() {
                let next = self.project_argmax(&tops[i * d..(i + 1) * d], cands[b].as_deref());
                if next == eos {
                    done[b] = true;
                } else {
                    out[b].push(next);
                    prev[b] = next;
                }
            }
        }
    }

    /// Project the decoder top and return the argmax token id. With a shortlist
    /// and a quantized `Wemb`, this runs the reference's int8 projection over the
    /// candidate columns (the `SelectColumnsB` path) for exact parity; otherwise
    /// it falls back to the full-vocab float projection.
    fn project_argmax(&self, h: &[f32], candidates: Option<&[u32]>) -> u32 {
        match (candidates, self.weights.output_wemb_qmult()) {
            (Some(cands), Some(qwemb)) => self.project_int8(h, cands, qwemb),
            (Some(cands), None) => argmax_restricted(&self.project(h), cands),
            (None, _) => argmax(&self.project(h)),
        }
    }

    /// The int8 tied output projection restricted to `candidates`, matching the
    /// reference's `intgemmSelectColumnsB` + affine. Returns the best candidate's
    /// full-vocabulary id.
    fn project_int8(&self, h: &[f32], candidates: &[u32], qwemb: f32) -> u32 {
        let d = self.config.dim_emb;
        let n = candidates.len();
        // qA for the decoder-top activation feeding the tied projection.
        let qa = self.weights.output_qa();
        let unquant = 1.0 / (qa * qwemb);

        // Gather candidate embedding rows as the [N, K] weight (out of the packed
        // buffer when the raw copy has been freed), and their biases.
        let bias_full = self
            .weights
            .f32("decoder_ff_logit_out_b")
            .unwrap_or_else(|| vec![0.0; self.weights.output_vocab()]);
        let mut b_transposed = vec![0i8; n * d];
        let mut raw_bias = vec![0.0f32; n];
        for (j, &c) in candidates.iter().enumerate() {
            self.weights
                .output_wemb_int8_row(c, &mut b_transposed[j * d..(j + 1) * d]);
            raw_bias[j] = bias_full[c as usize];
        }
        let prepared = ops::prepare_bias(&b_transposed, n, d, &raw_bias, unquant);
        let a = ops::prepare_a(h, qa);
        let logits = ops::intgemm_affine(&a, 1, d, &b_transposed, n, unquant, &prepared);

        // argmax over candidates -> map back to the vocabulary id.
        let mut best = 0usize;
        for j in 1..n {
            if logits[j] > logits[best] {
                best = j;
            }
        }
        candidates[best]
    }

    // --- encoder -------------------------------------------------------------

    /// Run the encoder over the source ids, returning the context `[seq, dim]`.
    pub fn encode(&self, src_ids: &[u32]) -> Vec<f32> {
        let seq = src_ids.len();
        let mut x = self.embed(src_ids, 0, Side::Source);
        for layer in 1..=self.config.enc_depth {
            x = self.encoder_layer(layer, &x, seq);
        }
        x
    }

    fn encoder_layer(&self, layer: usize, x: &[f32], seq: usize) -> Vec<f32> {
        let p = format!("encoder_l{layer}");
        // Self-attention sublayer: LayerNorm(x + SelfAttn(x)).
        let attn = self.multihead(&format!("{p}_self"), x, x, seq, seq);
        let x = self.postnorm(&attn, x, seq, &format!("{p}_self_Wo"));
        // FFN sublayer.
        self.ffn(&format!("{p}_ffn"), &x, seq)
    }

    /// Batched encoder over a block of sentences (the production unit). Sentences
    /// are padded to the batch's max source length; padded key positions are
    /// masked out of self-attention, so each sentence's valid rows are computed
    /// exactly as if it were encoded alone. The affines and FFN/layernorm are
    /// per-row and run over `batch·seq` rows unchanged; only attention needs the
    /// padding mask.
    pub fn encode_batch(&self, sentences: &[Vec<u32>]) -> BatchedContext {
        let d = self.config.dim_emb;
        let batch = sentences.len();
        let seq = sentences.iter().map(Vec::len).max().unwrap_or(0);
        let lens: Vec<usize> = sentences.iter().map(Vec::len).collect();

        // Embed into [batch, seq, dim]; pad rows stay zero (masked in attention).
        let mut x = vec![0.0f32; batch * seq * d];
        for (b, ids) in sentences.iter().enumerate() {
            let base = b * seq * d;
            self.embed_into(ids, 0, Side::Source, &mut x[base..base + ids.len() * d]);
        }
        for layer in 1..=self.config.enc_depth {
            x = self.encoder_layer_batched(layer, &x, batch, seq, &lens);
        }
        BatchedContext {
            data: x,
            batch,
            seq,
            dim: d,
            lens,
        }
    }

    fn encoder_layer_batched(
        &self,
        layer: usize,
        x: &[f32],
        batch: usize,
        seq: usize,
        lens: &[usize],
    ) -> Vec<f32> {
        let p = format!("encoder_l{layer}");
        let rows = batch * seq;
        let attn = self.multihead_batched(&format!("{p}_self"), x, x, batch, seq, seq, lens);
        let x = self.postnorm(&attn, x, rows, &format!("{p}_self_Wo"));
        self.ffn(&format!("{p}_ffn"), &x, rows)
    }

    // --- decoder -------------------------------------------------------------

    /// One decoder step for the token `prev_id` at output position `pos`.
    /// Updates the per-layer SSRU cell states and returns the top output `[dim]`.
    pub fn decode_step(
        &self,
        prev_id: u32,
        pos: usize,
        context: &[f32],
        seq: usize,
        cells: &mut [Vec<f32>],
    ) -> Vec<f32> {
        let mut x = self.embed(&[prev_id], pos, Side::Target);
        for layer in 1..=self.config.dec_depth {
            let p = format!("decoder_l{layer}");
            // SSRU autoregressive sublayer.
            let cand = self.weights.affine(&format!("{p}_rnn_W"), &x, 1, None); // x̃ = u·W
            let gate =
                self.weights
                    .affine(&format!("{p}_rnn_Wf"), &x, 1, Some(&format!("{p}_rnn_bf"))); // f = u·Wf + bf
                                                                                          // c = σ(f)·c_prev + (1−σ(f))·x̃ ; h = ReLU(c)
            let c = ops::highway(&cells[layer], &cand, &gate);
            cells[layer] = c.clone();
            let h = ops::relu(&c);
            let x_self = self.postnorm(&h, &x, 1, &format!("{p}_rnn_ffn"));
            // Cross-attention to the encoder context.
            let attn = self.multihead(&format!("{p}_context"), &x_self, context, 1, seq);
            let x_ctx = self.postnorm(&attn, &x_self, 1, &format!("{p}_context_Wo"));
            // FFN.
            x = self.ffn(&format!("{p}_ffn"), &x_ctx, 1);
        }
        x
    }

    /// One batched decoder step over the **active** rows only. `active[i]` is the
    /// original batch index of the `i`-th still-decoding sentence; `prev[b]` /
    /// `cells[..][b·dim..]` are indexed by original batch id, so finished rows are
    /// simply skipped — the affines run at `m = active.len()`, not the full batch
    /// (finished sentences would otherwise cost redundant GEMM work every step).
    /// Cross-attention attends to each active sentence's own encoder context
    /// (`cross_kv`, indexed by original id, masked to its source length). Updates
    /// the active rows' SSRU cell state in place and returns the tops
    /// `[active.len(), dim]`. Decoder rows are independent (no decoder
    /// self-attention), so a row's output matches single-sentence decoding.
    fn decode_step_batch(
        &self,
        active: &[usize],
        prev: &[u32],
        pos: usize,
        ctx: &BatchedContext,
        cross_kv: &[(Vec<f32>, Vec<f32>)],
        cells: &mut [Vec<f32>],
    ) -> Vec<f32> {
        let d = self.config.dim_emb;
        let n = active.len();
        let mut x = vec![0.0f32; n * d];
        for (i, &b) in active.iter().enumerate() {
            self.embed_into(&[prev[b]], pos, Side::Target, &mut x[i * d..(i + 1) * d]);
        }
        for layer in 1..=self.config.dec_depth {
            let p = format!("decoder_l{layer}");
            let cand = self.weights.affine(&format!("{p}_rnn_W"), &x, n, None);
            let gate =
                self.weights
                    .affine(&format!("{p}_rnn_Wf"), &x, n, Some(&format!("{p}_rnn_bf")));
            // Gather the active rows' previous cell state, run the (elementwise)
            // highway/ReLU over the compacted [n, dim], then scatter c back.
            let mut cell_prev = vec![0.0f32; n * d];
            for (i, &b) in active.iter().enumerate() {
                cell_prev[i * d..(i + 1) * d].copy_from_slice(&cells[layer][b * d..(b + 1) * d]);
            }
            let c = ops::highway(&cell_prev, &cand, &gate);
            for (i, &b) in active.iter().enumerate() {
                cells[layer][b * d..(b + 1) * d].copy_from_slice(&c[i * d..(i + 1) * d]);
            }
            let h = ops::relu(&c);
            let x_self = self.postnorm(&h, &x, n, &format!("{p}_rnn_ffn"));
            // Cross-attention: one query per active row over its own context. K/V
            // are the per-layer cache (indexed by original batch id); Q is per-step.
            let (k, v) = &cross_kv[layer - 1];
            let attn = self.attend_cross(
                &format!("{p}_context"),
                &x_self,
                k,
                v,
                active,
                ctx.seq,
                &ctx.lens,
            );
            let x_ctx = self.postnorm(&attn, &x_self, n, &format!("{p}_context_Wo"));
            x = self.ffn(&format!("{p}_ffn"), &x_ctx, n);
        }
        x
    }

    /// Cross-attention for the active decoder rows: like [`attend_batched`] with
    /// one query per active row, but the cached K/V span the full batch, so row
    /// `i`'s query attends to `k`/`v` rows of its *original* batch id `active[i]`
    /// (masked to that sentence's source length). Returns `[active.len(), dim]`.
    #[allow(clippy::too_many_arguments)]
    fn attend_cross(
        &self,
        prefix: &str,
        q_in: &[f32],
        k: &[f32],
        v: &[f32],
        active: &[usize],
        kv_len: usize,
        kv_lens: &[usize],
    ) -> Vec<f32> {
        let d = self.config.dim_emb;
        let h = self.config.heads;
        let dk = d / h;
        let scale = 1.0 / (dk as f32).sqrt();
        let n = active.len();

        let q = self.weights.affine(
            &format!("{prefix}_Wq"),
            q_in,
            n,
            Some(&format!("{prefix}_bq")),
        );

        let mut joined = vec![0.0f32; n * d];
        let mut scores = vec![0.0f32; kv_len];
        for (i, &b) in active.iter().enumerate() {
            let klen = kv_lens[b];
            for head in 0..h {
                let off = head * dk;
                let qh = &q[i * d + off..i * d + off + dk];
                for j in 0..kv_len {
                    if j < klen {
                        let kh = &k[(b * kv_len + j) * d + off..(b * kv_len + j) * d + off + dk];
                        scores[j] = qh.iter().zip(kh).map(|(&a, &b)| a * b).sum::<f32>() * scale;
                    } else {
                        scores[j] = f32::NEG_INFINITY;
                    }
                }
                ops::softmax_in_place(&mut scores, 1, kv_len);
                let out = &mut joined[i * d + off..i * d + off + dk];
                for (j, &w) in scores.iter().enumerate() {
                    if w == 0.0 {
                        continue;
                    }
                    let vh = &v[(b * kv_len + j) * d + off..(b * kv_len + j) * d + off + dk];
                    for c in 0..dk {
                        out[c] += w * vh[c];
                    }
                }
            }
        }
        self.weights.affine(
            &format!("{prefix}_Wo"),
            &joined,
            n,
            Some(&format!("{prefix}_bo")),
        )
    }

    /// Precompute per-decoder-layer cross-attention K/V over the encoder context.
    /// The context is fixed for the whole decode, so `K = Wk·ctx` and `V = Wv·ctx`
    /// are constant across steps; projecting them once here (instead of every
    /// decode step) removes the largest redundant GEMM in the decoder. Indexed by
    /// `layer - 1`. Bit-identical to projecting per step — pure memoization.
    fn cross_attn_kv(&self, ctx: &BatchedContext) -> Vec<(Vec<f32>, Vec<f32>)> {
        (1..=self.config.dec_depth)
            .map(|layer| {
                self.project_kv(
                    &format!("decoder_l{layer}_context"),
                    &ctx.data,
                    ctx.batch * ctx.seq,
                )
            })
            .collect()
    }

    /// Greedy-decode a block of sentences together (batched encode + batched
    /// decode with per-row EOS). Returns each sentence's output token ids, in
    /// input order. Sentences that hit EOS or their length cap are kept in the
    /// batch and masked out (their tops ignored) until the whole block finishes.
    pub fn greedy_batch(&self, sentences: &[Vec<u32>]) -> Vec<Vec<u32>> {
        // Data-parallel path (feature `threads`): the sentences of a batch are
        // independent, so split them into contiguous chunks and translate the chunks
        // on separate worker threads that share `&self` (the weights are read-only;
        // each worker uses its own thread-local scratch). Concatenating in chunk
        // order preserves input order, and each sentence is still batched within its
        // chunk, so the tokens are bit-identical to the serial path.
        #[cfg(feature = "threads")]
        {
            if self.threads > 1 && sentences.len() > 1 {
                let n = self.threads.min(sentences.len());
                let chunk = sentences.len().div_ceil(n);
                let mut out: Vec<Vec<u32>> = Vec::with_capacity(sentences.len());
                std::thread::scope(|s| {
                    let handles: Vec<_> = sentences
                        .chunks(chunk)
                        .map(|c| s.spawn(move || self.greedy_batch_serial(c)))
                        .collect();
                    for h in handles {
                        out.extend(h.join().expect("greedy_batch worker panicked"));
                    }
                });
                return out;
            }
        }
        self.greedy_batch_serial(sentences)
    }

    /// Serial batched greedy decode of a block of sentences — one batched encode +
    /// batched decode with per-row EOS. [`greedy_batch`] calls this directly (serial
    /// build / `threads == 1`) or once per worker chunk (data-parallel).
    fn greedy_batch_serial(&self, sentences: &[Vec<u32>]) -> Vec<Vec<u32>> {
        let d = self.config.dim_emb;
        let batch = sentences.len();
        let ctx = self.encode_batch(sentences);
        let eos = self.trg_vocab.eos_id();

        let max_len: Vec<usize> = sentences
            .iter()
            .map(|s| ((2.0 * s.len() as f32).ceil() as usize + 4).min(256))
            .collect();
        let cap = max_len.iter().copied().max().unwrap_or(0);
        // Per-sentence shortlist candidate sets (None when no shortlist attached).
        let cands: Vec<Option<Vec<u32>>> = sentences
            .iter()
            .map(|s| {
                self.shortlist
                    .as_ref()
                    .map(|sl| sl.candidates(s, self.shared_vocab))
            })
            .collect();

        let mut cells = vec![vec![0.0f32; batch * d]; self.config.dec_depth + 1];
        let mut prev = vec![eos; batch];
        let mut out = vec![Vec::new(); batch];
        let mut done = vec![false; batch];
        let cross_kv = self.cross_attn_kv(&ctx);

        for step in 0..cap {
            let active = active_rows(&done, &max_len, step);
            if active.is_empty() {
                break;
            }
            let tops = self.decode_step_batch(&active, &prev, step, &ctx, &cross_kv, &mut cells);
            self.select_active(&active, &tops, &cands, eos, &mut prev, &mut out, &mut done);
        }
        out
    }

    /// Tokenize a block of sentences, batch-translate, and detokenize each.
    pub fn translate_batch(&self, texts: &[&str]) -> Vec<String> {
        let ids: Vec<Vec<u32>> = texts
            .iter()
            .map(|t| self.src_vocab.encode_with_eos(t))
            .collect();
        self.greedy_batch(&ids)
            .iter()
            .map(|o| self.trg_vocab.decode(o))
            .collect()
    }

    /// Like [`translate_batch`], but returns per-block [`BlockTiming`] for the
    /// block benchmark. Mirrors [`greedy_batch`] with `Instant` markers around the
    /// batched encode and decode loop.
    pub fn translate_batch_timed(&self, texts: &[&str]) -> (Vec<String>, BlockTiming) {
        use std::time::Instant;
        let d = self.config.dim_emb;
        let sentences: Vec<Vec<u32>> = texts
            .iter()
            .map(|t| self.src_vocab.encode_with_eos(t))
            .collect();
        let batch = sentences.len();

        let t_enc = Instant::now();
        let ctx = self.encode_batch(&sentences);
        let encode_ms = t_enc.elapsed().as_secs_f64() * 1e3;

        let eos = self.trg_vocab.eos_id();
        let max_len: Vec<usize> = sentences
            .iter()
            .map(|s| ((2.0 * s.len() as f32).ceil() as usize + 4).min(256))
            .collect();
        let cap = max_len.iter().copied().max().unwrap_or(0);
        let cands: Vec<Option<Vec<u32>>> = sentences
            .iter()
            .map(|s| {
                self.shortlist
                    .as_ref()
                    .map(|sl| sl.candidates(s, self.shared_vocab))
            })
            .collect();

        let mut cells = vec![vec![0.0f32; batch * d]; self.config.dec_depth + 1];
        let mut prev = vec![eos; batch];
        let mut out = vec![Vec::new(); batch];
        let mut done = vec![false; batch];

        let t_dec = Instant::now();
        // Counted as decode work: it replaces the per-step cross-attention K/V.
        let cross_kv = self.cross_attn_kv(&ctx);
        let mut first_token_ms = 0.0;
        for step in 0..cap {
            let active = active_rows(&done, &max_len, step);
            if active.is_empty() {
                break;
            }
            let tops = self.decode_step_batch(&active, &prev, step, &ctx, &cross_kv, &mut cells);
            if step == 0 {
                first_token_ms = t_dec.elapsed().as_secs_f64() * 1e3;
            }
            self.select_active(&active, &tops, &cands, eos, &mut prev, &mut out, &mut done);
        }
        let decode_ms = t_dec.elapsed().as_secs_f64() * 1e3;
        let timing = BlockTiming {
            encode_ms,
            first_token_ms,
            decode_ms,
            sentences: batch,
            src_tokens: sentences.iter().map(Vec::len).sum(),
            tokens: out.iter().map(Vec::len).sum(),
        };
        (
            out.iter().map(|o| self.trg_vocab.decode(o)).collect(),
            timing,
        )
    }

    /// Like [`translate_batch_timed`], but the *host* keeps the clock: `on_phase`
    /// fires at each [`Phase`] boundary so a caller with no usable `Instant`
    /// (wasm32) can time encode vs. decode vs. first-token with its own timer
    /// (`performance.now()`), then combine the returned [`BlockCounts`] into
    /// words/s / TTFT / decode-tok/s exactly as the native perf harness does.
    ///
    /// The decode logic is identical to [`translate_batch_timed`]; only the timing
    /// mechanism differs (a closure the host times, vs. `Instant` spans). Native
    /// code keeps using `translate_batch_timed`, so the `--timing` path is
    /// untouched.
    pub fn translate_batch_phased(
        &self,
        texts: &[&str],
        mut on_phase: impl FnMut(Phase),
    ) -> (Vec<String>, BlockCounts) {
        let d = self.config.dim_emb;
        let sentences: Vec<Vec<u32>> = texts
            .iter()
            .map(|t| self.src_vocab.encode_with_eos(t))
            .collect();
        let batch = sentences.len();

        on_phase(Phase::EncodeStart);
        let ctx = self.encode_batch(&sentences);
        on_phase(Phase::DecodeStart);

        let eos = self.trg_vocab.eos_id();
        let max_len: Vec<usize> = sentences
            .iter()
            .map(|s| ((2.0 * s.len() as f32).ceil() as usize + 4).min(256))
            .collect();
        let cap = max_len.iter().copied().max().unwrap_or(0);
        let cands: Vec<Option<Vec<u32>>> = sentences
            .iter()
            .map(|s| {
                self.shortlist
                    .as_ref()
                    .map(|sl| sl.candidates(s, self.shared_vocab))
            })
            .collect();

        let mut cells = vec![vec![0.0f32; batch * d]; self.config.dec_depth + 1];
        let mut prev = vec![eos; batch];
        let mut out = vec![Vec::new(); batch];
        let mut done = vec![false; batch];

        // Counted as decode work (as in `translate_batch_timed`): it replaces the
        // per-step cross-attention K/V, so it sits inside the decode span.
        let cross_kv = self.cross_attn_kv(&ctx);
        for step in 0..cap {
            let active = active_rows(&done, &max_len, step);
            if active.is_empty() {
                break;
            }
            let tops = self.decode_step_batch(&active, &prev, step, &ctx, &cross_kv, &mut cells);
            if step == 0 {
                on_phase(Phase::FirstToken);
            }
            self.select_active(&active, &tops, &cands, eos, &mut prev, &mut out, &mut done);
        }
        on_phase(Phase::DecodeEnd);

        let counts = BlockCounts {
            sentences: batch,
            src_tokens: sentences.iter().map(Vec::len).sum(),
            tokens: out.iter().map(Vec::len).sum(),
        };
        (
            out.iter().map(|o| self.trg_vocab.decode(o)).collect(),
            counts,
        )
    }

    /// Tied output projection over the full target vocabulary,
    /// `logits[v] = h · Wemb[v] + b_out[v]`. Delegates to
    /// [`Weights::full_logits`], whose representation (resident f32 table vs.
    /// on-the-fly int8) is chosen by the `lean-embed` feature.
    pub fn project(&self, h: &[f32]) -> Vec<f32> {
        self.weights.full_logits(h)
    }

    // --- shared sublayers ----------------------------------------------------

    /// Multi-head attention. `q_in` is `[q_len, dim]`, `kv_in` is `[kv_len, dim]`.
    /// `prefix` supplies `{prefix}_W{q,k,v,o}` and `{prefix}_b{q,k,v,o}`.
    fn multihead(
        &self,
        prefix: &str,
        q_in: &[f32],
        kv_in: &[f32],
        q_len: usize,
        kv_len: usize,
    ) -> Vec<f32> {
        let d = self.config.dim_emb;
        let h = self.config.heads;
        let dk = d / h;
        let scale = 1.0 / (dk as f32).sqrt();

        let q = self.weights.affine(
            &format!("{prefix}_Wq"),
            q_in,
            q_len,
            Some(&format!("{prefix}_bq")),
        );
        let k = self.weights.affine(
            &format!("{prefix}_Wk"),
            kv_in,
            kv_len,
            Some(&format!("{prefix}_bk")),
        );
        let v = self.weights.affine(
            &format!("{prefix}_Wv"),
            kv_in,
            kv_len,
            Some(&format!("{prefix}_bv")),
        );

        let mut joined = vec![0.0f32; q_len * d];
        let mut scores = vec![0.0f32; kv_len];
        for head in 0..h {
            let off = head * dk;
            for i in 0..q_len {
                let qh = &q[i * d + off..i * d + off + dk];
                // scaled dot-product scores over all kv positions
                for j in 0..kv_len {
                    let kh = &k[j * d + off..j * d + off + dk];
                    let dot: f32 = qh.iter().zip(kh).map(|(&a, &b)| a * b).sum();
                    scores[j] = dot * scale;
                }
                ops::softmax_in_place(&mut scores, 1, kv_len);
                // weighted sum of values
                let out = &mut joined[i * d + off..i * d + off + dk];
                for (j, &w) in scores.iter().enumerate() {
                    let vh = &v[j * d + off..j * d + off + dk];
                    for c in 0..dk {
                        out[c] += w * vh[c];
                    }
                }
            }
        }
        // output projection
        self.weights.affine(
            &format!("{prefix}_Wo"),
            &joined,
            q_len,
            Some(&format!("{prefix}_bo")),
        )
    }

    /// Batched multi-head attention over `[batch, q_len, dim]` / `[batch, kv_len,
    /// dim]`. `kv_lens[b]` is sentence `b`'s valid key count; keys at positions
    /// `>= kv_lens[b]` are masked (scored −∞ → zero weight), so a query never
    /// attends to padding. Q/K/V/O affines are per-row and run over the whole
    /// `batch·*_len`; only the scaled-dot-product is per-(batch, head).
    #[allow(clippy::too_many_arguments)]
    fn multihead_batched(
        &self,
        prefix: &str,
        q_in: &[f32],
        kv_in: &[f32],
        batch: usize,
        q_len: usize,
        kv_len: usize,
        kv_lens: &[usize],
    ) -> Vec<f32> {
        let (k, v) = self.project_kv(prefix, kv_in, batch * kv_len);
        self.attend_batched(prefix, q_in, &k, &v, batch, q_len, kv_len, kv_lens)
    }

    /// Project the K and V of an attention block from `kv_in` `[rows_kv, dim]`,
    /// returning `(k, v)` each `[rows_kv, dim]`. Split out from [`attend_batched`]
    /// so cross-attention — whose `kv_in` is the encoder context, fixed for the
    /// whole decode — can project once and reuse (see [`Engine::cross_attn_kv`]).
    fn project_kv(&self, prefix: &str, kv_in: &[f32], rows_kv: usize) -> (Vec<f32>, Vec<f32>) {
        let k = self.weights.affine(
            &format!("{prefix}_Wk"),
            kv_in,
            rows_kv,
            Some(&format!("{prefix}_bk")),
        );
        let v = self.weights.affine(
            &format!("{prefix}_Wv"),
            kv_in,
            rows_kv,
            Some(&format!("{prefix}_bv")),
        );
        (k, v)
    }

    /// Batched multi-head attention given already-projected `k`/`v` `[rows_kv,
    /// dim]`. Projects `q` from `q_in`, runs the masked scaled-dot-product per
    /// `(batch, head)`, and applies the output projection. Splitting the Q path
    /// from K/V lets the decoder reuse cached cross-attention K/V across steps.
    #[allow(clippy::too_many_arguments)]
    fn attend_batched(
        &self,
        prefix: &str,
        q_in: &[f32],
        k: &[f32],
        v: &[f32],
        batch: usize,
        q_len: usize,
        kv_len: usize,
        kv_lens: &[usize],
    ) -> Vec<f32> {
        let d = self.config.dim_emb;
        let h = self.config.heads;
        let dk = d / h;
        let scale = 1.0 / (dk as f32).sqrt();
        let rows_q = batch * q_len;

        let q = self.weights.affine(
            &format!("{prefix}_Wq"),
            q_in,
            rows_q,
            Some(&format!("{prefix}_bq")),
        );

        let mut joined = vec![0.0f32; rows_q * d];
        let mut scores = vec![0.0f32; kv_len];
        for b in 0..batch {
            let klen = kv_lens[b];
            for head in 0..h {
                let off = head * dk;
                for i in 0..q_len {
                    let qh = &q[(b * q_len + i) * d + off..(b * q_len + i) * d + off + dk];
                    for j in 0..kv_len {
                        if j < klen {
                            let kh =
                                &k[(b * kv_len + j) * d + off..(b * kv_len + j) * d + off + dk];
                            scores[j] =
                                qh.iter().zip(kh).map(|(&a, &b)| a * b).sum::<f32>() * scale;
                        } else {
                            scores[j] = f32::NEG_INFINITY;
                        }
                    }
                    ops::softmax_in_place(&mut scores, 1, kv_len);
                    let out =
                        &mut joined[(b * q_len + i) * d + off..(b * q_len + i) * d + off + dk];
                    for (j, &w) in scores.iter().enumerate() {
                        if w == 0.0 {
                            continue;
                        }
                        let vh = &v[(b * kv_len + j) * d + off..(b * kv_len + j) * d + off + dk];
                        for c in 0..dk {
                            out[c] += w * vh[c];
                        }
                    }
                }
            }
        }
        self.weights.affine(
            &format!("{prefix}_Wo"),
            &joined,
            rows_q,
            Some(&format!("{prefix}_bo")),
        )
    }

    /// FFN sublayer: `LayerNorm(x + W2·ReLU(W1·x))`. `prefix` e.g. `encoder_l1_ffn`.
    fn ffn(&self, prefix: &str, x: &[f32], seq: usize) -> Vec<f32> {
        let hidden = self.weights.affine(
            &format!("{prefix}_W1"),
            x,
            seq,
            Some(&format!("{prefix}_b1")),
        );
        let hidden = ops::relu(&hidden);
        let inner = self.config.dim_ffn;
        let rows = hidden.len() / inner;
        debug_assert_eq!(rows, seq);
        let out = self.weights.affine(
            &format!("{prefix}_W2"),
            &hidden,
            seq,
            Some(&format!("{prefix}_b2")),
        );
        self.postnorm(&out, x, seq, &format!("{prefix}_ffn"))
    }

    /// Post-norm residual: `LayerNorm(branch + residual)` with the `{ln}_ln_*`
    /// scale/bias params.
    fn postnorm(&self, branch: &[f32], residual: &[f32], rows: usize, ln: &str) -> Vec<f32> {
        let d = self.config.dim_emb;
        let sum: Vec<f32> = branch.iter().zip(residual).map(|(&a, &b)| a + b).collect();
        let (gamma, beta) = self
            .weights
            .layer_norm(ln)
            .unwrap_or_else(|| panic!("missing {ln}_ln_scale"));
        ops::layer_normalization(&sum, gamma, beta, rows, d, EPS)
    }

    // --- embeddings ----------------------------------------------------------

    /// Embed a run of token ids at consecutive positions starting at `start`:
    /// `x_t = √d · Wemb[id_t] + PE(start + t)`. `side` selects the source
    /// (encoder) or target (decoder) embedding — the same matrix for shared-vocab
    /// models, distinct for split-vocab (CJK) ones.
    fn embed(&self, ids: &[u32], start: usize, side: Side) -> Vec<f32> {
        let mut out = vec![0.0f32; ids.len() * self.config.dim_emb];
        self.embed_into(ids, start, side, &mut out);
        out
    }

    /// [`embed`] directly into `out` (`[ids.len(), dim]`): write the looked-up /
    /// dequantized embedding row into each token's slice, then fold in `√d` and
    /// the positional encoding in place — no per-token or per-call allocation, so
    /// batched callers embed straight into their activation buffer.
    fn embed_into(&self, ids: &[u32], start: usize, side: Side, out: &mut [f32]) {
        let d = self.config.dim_emb;
        let scale = (d as f32).sqrt();
        for (t, &id) in ids.iter().enumerate() {
            let dst = &mut out[t * d..(t + 1) * d];
            match side {
                Side::Source => self.weights.src_embed_row_into(id, dst),
                Side::Target => self.weights.trg_embed_row_into(id, dst),
            }
            let pos = (start + t) as f32;
            for c in 0..d {
                dst[c] = scale * dst[c] + (pos * self.pe_freq[c] + self.pe_offs[c]).sin();
            }
        }
    }
}

/// A ready translation for a language pair: either one [`Engine`] for a direct
/// pair, or two chained for a pivot (`src`→`pivot`→`trg`). Both engines stay
/// resident for the session — [`translate`](Translation::translate) hands the
/// detokenized intermediate text from the first to the second, mirroring how
/// Firefox pivots outside the engine (Marian itself has no pivot logic).
pub enum Translation {
    /// A single model translates the pair directly.
    Direct(Engine),
    /// Two models chained through a pivot language; `first` is `src`→`pivot`,
    /// `second` is `pivot`→`trg`. `pivot` is kept for reporting the hop.
    Pivot {
        pivot: String,
        first: Engine,
        second: Engine,
    },
}

impl Translation {
    /// Translate `text`, pivoting through the intermediate language when the pair
    /// has no direct model.
    pub fn translate(&self, text: &str) -> String {
        match self {
            Translation::Direct(engine) => engine.translate(text),
            Translation::Pivot { first, second, .. } => second.translate(&first.translate(text)),
        }
    }

    /// Long-input-safe translate: each leg segments and translates per sentence
    /// ([`Engine::translate_long`]). For a pivot, the first leg's rejoined output
    /// is re-segmented by the second leg.
    pub fn translate_long(&self, text: &str) -> String {
        match self {
            Translation::Direct(engine) => engine.translate_long(text),
            Translation::Pivot { first, second, .. } => {
                second.translate_long(&first.translate_long(text))
            }
        }
    }

    /// The pivot language, if this is a two-leg pivot (for status reporting).
    pub fn pivot(&self) -> Option<&str> {
        match self {
            Translation::Direct(_) => None,
            Translation::Pivot { pivot, .. } => Some(pivot),
        }
    }
}

/// Which embedding matrix a lookup uses.
#[derive(Clone, Copy)]
enum Side {
    Source,
    Target,
}

/// Original batch indices still decoding at `step`: not finished (`!done`) and
/// within their length cap (`step < max_len`). Rows past their cap are never
/// active again (step only grows), so they need no explicit "done" flag; the loop
/// stops when this returns empty.
fn active_rows(done: &[bool], max_len: &[usize], step: usize) -> Vec<usize> {
    (0..done.len())
        .filter(|&b| !done[b] && step < max_len[b])
        .collect()
}

/// Index of the maximum element (first on ties).
fn argmax(v: &[f32]) -> u32 {
    let mut best = 0usize;
    for i in 1..v.len() {
        if v[i] > v[best] {
            best = i;
        }
    }
    best as u32
}

/// Argmax over only the candidate ids (the shortlist restriction), returning a
/// full-vocabulary id.
fn argmax_restricted(logits: &[f32], candidates: &[u32]) -> u32 {
    let mut best = candidates[0];
    let mut best_val = logits[best as usize];
    for &c in &candidates[1..] {
        let val = logits[c as usize];
        if val > best_val {
            best_val = val;
            best = c;
        }
    }
    best
}