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
//! Greedy next-token sampling: the decode loop's per-step choice of which
//! token to emit next, given that step's raw logits — argmax at
//! `temperature == 0`, seeded top-k multinomial otherwise — plus the
//! end-of-decoding finalization step. Ports Swift's `GreedyTokenSampler`
//! (argmax-oss-swift `Sources/WhisperKit/Core/Text/TokenSampler.swift:29-252`).
//!
//! Swift picks between two sampling implementations at runtime by OS
//! availability — `sampleWithMLTensor` (`TokenSampler.swift:40-84`, macOS
//! 15+/iOS 18+) and `sampleWithBNNS` (`TokenSampler.swift:86-213`, the
//! fallback, itself flagged with a `TODO` for replacement) — that
//! collapse into the one plain `f32` path here: the f16→f32 conversion
//! already happened at the backend boundary (spec §4.8; see
//! [`crate::audio::whisper::backend`]), matching [`crate::audio::whisper::decode::filter`]'s convention.
//!
//! **Deliberate mechanical deviation, documented per spec:** Swift's
//! `SamplingResult` clones the whole `tokens`/`logProbs` arrays on every
//! step (`TokenSampler.swift:231-239`); [`SamplingResult`] here carries
//! only the new step's `(token, logprob, completed)`, leaving the decode
//! loop (a later task) to append it — the observable token/logprob
//! sequence is identical, with zero per-step clones.
//!
//! `BeamSearchTokenSampler` (`TokenSampler.swift:254-290`) is not ported:
//! every method it defines is an unconditional `fatalError`, including
//! its own initializer on an invalid beam size/patience, so there is no
//! real behavior to port — a spec non-goal.
//!
//! **Rust-only addition, no Swift equivalent:** [`derive_attempt_seed`]
//! turns one caller-chosen [`DecodingOptions::seed`] into a distinct
//! [`GreedyTokenSampler::with_seed`] seed per (window, attempt), so
//! [`crate::audio::whisper::transcribe::TranscribeTask`]'s temperature-fallback ladder can
//! be both reproducible end to end and free of correlated draws across
//! windows/attempts — see that function's own doc for the exact mixing
//! function and contract (coremlit issue #9).
use NonZeroUsize;
use ;
use crateDecodingOptions;
// ---------------------------------------------------------------------
// SamplingResult
// ---------------------------------------------------------------------
/// One sampling step's outcome: the sampled token id, its log probability
/// under the (possibly temperature-scaled) distribution, and whether that
/// token completes decoding. Ports Swift's `SamplingResult`
/// (`TokenSampler.swift:13-27`) — see the module docs for why this only
/// carries the new step instead of Swift's whole-history clone.
// ---------------------------------------------------------------------
// GreedyTokenSampler
// ---------------------------------------------------------------------
/// Greedy (argmax at `temperature() == 0.0`) / seeded top-k multinomial
/// (otherwise) next-token sampler. Ports Swift's `GreedyTokenSampler`
/// (`TokenSampler.swift:29-252`); see the module docs for the
/// `sampleWithMLTensor`/`sampleWithBNNS` collapse and the
/// [`SamplingResult`] deviation.
// ---------------------------------------------------------------------
// Seed derivation
// ---------------------------------------------------------------------
/// SplitMix64's avalanche finalizer (Steele, Lea & Flood, *Fast Splittable
/// Pseudorandom Number Generators*, OOPSLA 2014): two multiply-xorshift
/// rounds that turn a single-bit input difference into an unrelated
/// (on average half-flipped) 64-bit output. The same finalizer backs
/// `java.util.SplittableRandom`'s stream splitting; [`derive_attempt_seed`]
/// below chains one round of it per coordinate (base seed, worker, window,
/// attempt) to fold all four into a single sub-seed.
const
/// Distinct, nonzero *odd* multipliers — one per coordinate — that spread a
/// coordinate across the full 64-bit width before it is XORed into the
/// running `splitmix64` state in [`derive_attempt_seed`]. Oddness makes
/// `coord.wrapping_mul(GAMMA)` a bijection on `u64` (odd values are units
/// modulo 2^64), so distinct coordinate values never collapse to the same
/// contribution; using a *different* constant per coordinate — applied at a
/// *different* mixing round — is what stops two coordinates from aliasing
/// when their raw values are swapped. `GAMMA_SEED` is SplitMix64's
/// golden-ratio increment; the other three are the MurmurHash3 / SplitMix64
/// finalizer multipliers — all well-known full-period mixing constants.
const GAMMA_SEED: u64 = 0x9E37_79B9_7F4A_7C15;
const GAMMA_WORKER: u64 = 0xD1B5_4A32_D192_ED03;
const GAMMA_WINDOW: u64 = 0xFF51_AFD7_ED55_8CCD;
const GAMMA_ATTEMPT: u64 = 0xC4CE_B9FE_1A85_EC53;
/// Deterministically derives a per-(worker, window, attempt) sampler
/// sub-seed from a caller-chosen base `seed` ([`DecodingOptions::seed`]).
///
/// Reusing `seed` verbatim for every [`GreedyTokenSampler`] the
/// temperature-fallback ladder builds would make every window/attempt draw
/// the exact same RNG stream — wrong the moment two of them share a logits
/// shape, since they would then sample identical sequences. Instead the
/// three coordinates are *domain-separated*: each is folded into the running
/// state in its own `splitmix64` round (this module's private SplitMix64
/// finalizer, above), after an initial round that mixes the base seed with a
/// nonzero constant. With `s` the running state:
///
/// ```text
/// s = splitmix64(seed ^ GAMMA_SEED)
/// s = splitmix64(s ^ worker_index .wrapping_mul(GAMMA_WORKER))
/// s = splitmix64(s ^ window_index .wrapping_mul(GAMMA_WINDOW))
/// s = splitmix64(s ^ attempt_index.wrapping_mul(GAMMA_ATTEMPT))
/// ```
///
/// The coordinates are **never summed or otherwise collapsed into one
/// number**: `worker_index` and `window_index` enter at *different* rounds
/// through *different* multipliers, so `(worker = 0, window = 1)` and
/// `(worker = 1, window = 0)` derive unrelated sub-seeds — the earlier
/// `offset + window_index` sum aliased exactly that pair. And because the
/// first round mixes `seed` with a nonzero constant, `seed = 0` does not
/// collapse to `0`, so cross-seed pairs the earlier XOR mixer folded onto a
/// single value (`(seed = 0, window = 0)` and `(seed = 1, window = 1)` both
/// became `0` under `splitmix64(seed ^ window)`, since `splitmix64(0) == 0`)
/// now differ too.
///
/// Two guaranteed properties:
///
/// * **Reproducible.** This is a pure function of its four arguments, so an
/// identical `(seed, worker_index, window_index, attempt_index)` tuple
/// always reproduces the identical result — which is what lets
/// [`DecodingOptions::seed`] alone reproduce a whole transcription's
/// sampled tokens bit-for-bit across separate runs.
/// * **No single-coordinate collapse.** Changing *exactly one* coordinate
/// (holding the others fixed) is *guaranteed* to change the output, never
/// merely usually: each `splitmix64` round is a bijection, and a
/// coordinate reaches its round through an odd-constant multiply then an
/// XOR — both bijections — so the map from that coordinate to the
/// post-round state is injective and every later round preserves the
/// difference. No coordinate (the base seed included) has a value that
/// aliases another, and none collapses at zero.
///
/// A `u64` result cannot be globally injective over the full four-`u64`
/// input space (pigeonhole), so "collision-free" here means the
/// per-single-coordinate injectivity above plus being empirically
/// collision-free across the realistic worker/window/attempt ranges a
/// transcription reaches — see this module's `derive_attempt_seed` collision
/// test.
///
/// [`crate::audio::whisper::transcribe::TranscribeTask`]'s fallback ladder calls this with
/// `worker_index` the task's own
/// [`window_id_offset`](crate::audio::whisper::transcribe::TranscribeTask::set_window_id_offset)
/// (a genuinely unique per-chunk / per-audio / per-worker id, so distinct
/// chunks and concurrently-running workers now get distinct seed streams as
/// a real guarantee rather than the pre-fix *nudge*), `window_index` a
/// strictly monotonic per-`run` window counter *local* to that task (reset
/// to 0 for every task — precisely why it must be a coordinate separate from
/// `worker_index`), and `attempt_index` the fallback loop's own
/// `0..=temperature_fallback_count` counter. The function itself has no
/// dependency on that caller: it is a pure, public mixing primitive, so a
/// direct [`decode_text`](crate::audio::whisper::decode::decode_text)/
/// [`detect_language`](crate::audio::whisper::decode::detect_language) caller that wants to
/// replicate (or deliberately diverge from) the pipeline's exact seed
/// schedule can call it the same way.
pub const
/// Index of the largest entry in `logits` under IEEE `>` comparison: the
/// FIRST index wins every tie (exact ties and signed-zero ties — IEEE `==`
/// treats `-0.0 == +0.0`), and NaN entries are skipped wherever they sit.
/// Probe-verified Swift parity (tests/whisper_swift_probes/probe_argmax2.out,
/// macOS 26.5/M1 Max): `MLTensor.argmax(alongAxis:)` on the f32-cast logits
/// (the macOS 15+ path, `TokenSampler.swift:45,75`) and
/// `BNNS.ReductionFunction.argMax` at f16 (legacy, `:182-196`) both return
/// the first index on every crafted tie and both skip NaN. All-NaN input is
/// unspecified upstream (MLTensor -> 0, BNNS -> last); this port pins 0,
/// matching the shipping MLTensor path. Empty input returns 0 (unreachable:
/// the decoder always emits `vocab()` logits).