-
Notifications
You must be signed in to change notification settings - Fork 229
/
UnitTests.swift
1287 lines (1061 loc) · 64.4 KB
/
UnitTests.swift
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
// For licensing see accompanying LICENSE.md file.
// Copyright © 2024 Argmax, Inc. All rights reserved.
import AVFoundation
import CoreML
import Tokenizers
import Hub
@testable import WhisperKit
import XCTest
@available(macOS 13, iOS 16, watchOS 10, visionOS 1, *)
final class UnitTests: XCTestCase {
// MARK: - Model Loading Test
func testInit() async throws {
try await XCTUnwrapAsync(
await WhisperKit(prewarm: false, load: false, download: false),
"Failed to init WhisperKit"
)
}
func testInitTiny() async throws {
try await XCTUnwrapAsync(
await WhisperKit(modelFolder: tinyModelPath(), logLevel: .error),
"Failed to init WhisperKit"
)
}
// MARK: - Audio Tests
func testAudioFileLoading() throws {
let audioFilePath = try XCTUnwrap(
Bundle.module.path(forResource: "jfk", ofType: "wav"),
"Audio file not found"
)
let audioBuffer = AudioProcessor.loadAudio(fromPath: audioFilePath)
XCTAssertNotNil(audioBuffer, "Failed to load audio file at path: \(audioFilePath)")
XCTAssertEqual(audioBuffer!.format.sampleRate, 16000)
XCTAssertEqual(audioBuffer!.format.channelCount, 1)
}
func testAudioPad() {
let audioSamples = [Float](repeating: 0.0, count: 1000)
let paddedSamples = AudioProcessor.padOrTrimAudio(fromArray: audioSamples, startAt: 0, toLength: 1600)
XCTAssertNotNil(paddedSamples, "Failed to pad audio samples")
XCTAssertEqual(paddedSamples?.count, 1600, "Padded or trimmed samples count is not as expected")
}
func testAudioTrim() {
let audioSamples = [Float](repeating: 0.0, count: 2000)
let paddedSamples = AudioProcessor.padOrTrimAudio(fromArray: audioSamples, startAt: 0, toLength: 1600)
XCTAssertNotNil(paddedSamples, "Failed to trim audio samples")
XCTAssertEqual(paddedSamples?.count, 1600, "Padded or trimmed samples count is not as expected")
}
func testAudioResample() throws {
let audioFileURL = try XCTUnwrap(
Bundle.module.url(forResource: "jfk", withExtension: "wav"),
"Audio file not found"
)
let audioFile = try AVAudioFile(forReading: audioFileURL)
let targetSampleRate = 44100.0
let targetChannelCount: AVAudioChannelCount = 2
let resampledAudio = AudioProcessor.resampleAudio(
fromFile: audioFile,
toSampleRate: targetSampleRate,
channelCount: 2
)
XCTAssertNotNil(resampledAudio, "Failed to resample audio")
XCTAssertEqual(resampledAudio?.format.sampleRate, targetSampleRate, "Resampled audio sample rate is not as expected")
XCTAssertEqual(resampledAudio?.format.channelCount, targetChannelCount, "Resampled audio channels is not as expected")
}
func testAudioEnergy() {
let samples = [Float](repeating: 0.0, count: 16000)
let silence = samples.map { _ in Float(0.0) }
let energy = AudioProcessor.calculateEnergy(of: silence).avg
XCTAssertEqual(energy, 0.0, "Audio energy is not silent")
let loudNoise = samples.map { _ in Float.random(in: -1...1) }
let energyLoud = AudioProcessor.calculateEnergy(of: loudNoise).avg
XCTAssertGreaterThan(energyLoud, energy, "Audio energy is not loud")
let veryLoudNoise = samples.map { _ in Float.random(in: -10...10) }
let energyVeryLoud = AudioProcessor.calculateEnergy(of: veryLoudNoise).avg
XCTAssertGreaterThan(energyVeryLoud, energyLoud, "Audio energy is not very loud")
}
// MARK: - Feature Extractor Tests
func testLogmelOutput() async throws {
let audioSamples = [Float](repeating: 0.0, count: 16000)
let paddedSamples = try XCTUnwrap(
AudioProcessor.padOrTrimAudio(fromArray: audioSamples, startAt: 0, toLength: 480_000),
"Failed to pad audio samples"
)
var featureExtractor = FeatureExtractor()
let modelPath = try URL(filePath: tinyModelPath()).appending(path: "MelSpectrogram.mlmodelc")
try await featureExtractor.loadModel(at: modelPath, computeUnits: ModelComputeOptions().melCompute)
let melSpectrogram = try await XCTUnwrapAsync(
await featureExtractor.logMelSpectrogram(fromAudio: paddedSamples),
"Failed to produce Mel spectrogram from audio samples"
)
let expectedShape: [NSNumber] = [1, 80, 1, 3000]
XCTAssertNotNil(melSpectrogram, "Failed to produce Mel spectrogram from audio samples")
XCTAssertEqual(melSpectrogram.shape, expectedShape, "Mel spectrogram shape is not as expected")
}
func testCompressionRatioIntArray() {
let uniqueArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let uniqueRatio = compressionRatio(of: uniqueArray)
let repeatedArray = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
let repeatedRatio = compressionRatio(of: repeatedArray)
let repeatedLongArray = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
let repeatedLongRatio = compressionRatio(of: repeatedLongArray)
XCTAssertLessThan(uniqueRatio, repeatedRatio)
XCTAssertLessThan(repeatedRatio, repeatedLongRatio)
}
func testCompressionRatioString() {
let uniqueString = "This is a unique string"
let uniqueRatio = compressionRatio(of: uniqueString)
let repeatedString = String(repeating: "Repeated text string", count: 5)
let repeatedRatio = compressionRatio(of: repeatedString)
let repeatedLongString = String(repeating: "Longer repeated text string", count: 10)
let repeatedLongRatio = compressionRatio(of: repeatedLongString)
XCTAssertLessThan(uniqueRatio, repeatedRatio)
XCTAssertLessThan(repeatedRatio, repeatedLongRatio)
}
// MARK: - Encoder Tests
func testEncoderOutput() async throws {
var audioEncoder = AudioEncoder()
let modelPath = try URL(filePath: tinyModelPath()).appending(path: "AudioEncoder.mlmodelc")
try? await audioEncoder.loadModel(at: modelPath, computeUnits: ModelComputeOptions().audioEncoderCompute)
let encoderInput = try MLMultiArray(shape: [1, 80, 1, 3000], dataType: .float16)
let expectedShape: [NSNumber] = [1, 384, 1, 1500]
let encoderOutput = try await audioEncoder.encodeFeatures(encoderInput)
XCTAssertNotNil(encoderOutput, "Failed to encode features")
XCTAssertEqual(encoderOutput?.shape, expectedShape, "Encoder output shape is not as expected")
}
// MARK: - Decoder Tests
func testDecoderOutput() async throws {
var textDecoder = TextDecoder()
let decodingOptions = DecodingOptions()
let modelPath = try URL(filePath: tinyModelPath()).appending(path: "TextDecoder.mlmodelc")
await XCTAssertNoThrowAsync(
try await textDecoder.loadModel(at: modelPath, computeUnits: ModelComputeOptions().textDecoderCompute),
"Failed to load the model"
)
textDecoder.tokenizer = try await XCTUnwrapAsync(
await loadTokenizer(for: .tiny),
"Failed to load the tokenizer"
)
let tokenSampler = GreedyTokenSampler(
temperature: 0,
eotToken: textDecoder.tokenizer!.specialTokens.endToken,
decodingOptions: decodingOptions
)
let encoderInput = try MLMultiArray(shape: [1, 384, 1, 1500], dataType: .float16)
let inputs = try XCTUnwrap(
textDecoder.prepareDecoderInputs(withPrompt: [textDecoder.tokenizer!.specialTokens.startOfTranscriptToken]),
"Failed to prepare decoder inputs"
)
let expectedShape = 1
let decoderOutput = try await textDecoder.decodeText(
from: encoderInput,
using: inputs,
sampler: tokenSampler,
options: decodingOptions
)
XCTAssertNotNil(decoderOutput, "Failed to decode text")
XCTAssertEqual(decoderOutput.count, expectedShape, "Decoder output shape is not as expected")
}
func testDecoderLogProbThresholdDecodingFallback() async throws {
let decodingOptions = DecodingOptions(
withoutTimestamps: true,
compressionRatioThreshold: nil,
logProbThreshold: 1000.0,
firstTokenLogProbThreshold: nil,
noSpeechThreshold: nil
)
var textDecoder = TextDecoder()
let modelPath = try URL(filePath: tinyModelPath()).appending(path: "TextDecoder.mlmodelc")
try await textDecoder.loadModel(at: modelPath, computeUnits: ModelComputeOptions().textDecoderCompute)
textDecoder.tokenizer = try await loadTokenizer(for: .tiny)
let tokenSampler = GreedyTokenSampler(temperature: 0, eotToken: textDecoder.tokenizer!.specialTokens.endToken, decodingOptions: decodingOptions)
let encoderInput = initMLMultiArray(shape: [1, 384, 1, 1500], dataType: .float16, initialValue: FloatType(0))
let decoderInputs = textDecoder.prepareDecoderInputs(withPrompt: [textDecoder.tokenizer!.specialTokens.startOfTranscriptToken])
let inputs = try XCTUnwrap(decoderInputs, "Failed to prepare decoder inputs")
let decoderOutput = try await textDecoder.decodeText(from: encoderInput, using: inputs, sampler: tokenSampler, options: decodingOptions)
let fallback = try XCTUnwrap(decoderOutput.first?.fallback, "Fallback should not be `nil`")
XCTAssertEqual(fallback.fallbackReason, "logProbThreshold")
XCTAssertTrue(fallback.needsFallback)
}
func testDecoderFirstTokenLogProbThresholdDecodingFallback() async throws {
let decodingOptions = DecodingOptions(
withoutTimestamps: true,
compressionRatioThreshold: nil,
logProbThreshold: nil,
firstTokenLogProbThreshold: 1000.0,
noSpeechThreshold: nil
)
var textDecoder = TextDecoder()
let modelPath = try URL(filePath: tinyModelPath()).appending(path: "TextDecoder.mlmodelc")
try await textDecoder.loadModel(at: modelPath, computeUnits: ModelComputeOptions().textDecoderCompute)
textDecoder.tokenizer = try await loadTokenizer(for: .tiny)
let tokenSampler = GreedyTokenSampler(temperature: 0, eotToken: textDecoder.tokenizer!.specialTokens.endToken, decodingOptions: decodingOptions)
let encoderInput = initMLMultiArray(shape: [1, 384, 1, 1500], dataType: .float16, initialValue: FloatType(0))
let decoderInputs = textDecoder.prepareDecoderInputs(withPrompt: [textDecoder.tokenizer!.specialTokens.startOfTranscriptToken])
let inputs = try XCTUnwrap(decoderInputs, "Failed to prepare decoder inputs")
let decoderOutput = try await textDecoder.decodeText(from: encoderInput, using: inputs, sampler: tokenSampler, options: decodingOptions)
let fallback = try XCTUnwrap(decoderOutput.first?.fallback, "Fallback should not be `nil`")
XCTAssertEqual(fallback.fallbackReason, "firstTokenLogProbThreshold")
XCTAssertTrue(fallback.needsFallback)
}
func testDecodingFallbackInit() throws {
let fallback1 = try XCTUnwrap(
DecodingFallback(
options: DecodingOptions(compressionRatioThreshold: -1.0, logProbThreshold: -1.0, noSpeechThreshold: -1.0),
isFirstTokenLogProbTooLow: true,
noSpeechProb: 0,
compressionRatio: 0,
avgLogProb: -2.0
)
)
XCTAssertEqual(fallback1.fallbackReason, "firstTokenLogProbThreshold")
XCTAssertTrue(fallback1.needsFallback)
let fallback2 = try XCTUnwrap(
DecodingFallback(
options: DecodingOptions(compressionRatioThreshold: -1.0, logProbThreshold: -1.0, noSpeechThreshold: -1.0),
isFirstTokenLogProbTooLow: false,
noSpeechProb: 0,
compressionRatio: 0,
avgLogProb: -2.0
)
)
XCTAssertEqual(fallback2.fallbackReason, "silence")
XCTAssertFalse(fallback2.needsFallback)
let fallback3 = try XCTUnwrap(
DecodingFallback(
options: DecodingOptions(compressionRatioThreshold: -1.0, logProbThreshold: -1.0, noSpeechThreshold: 0.0),
isFirstTokenLogProbTooLow: false,
noSpeechProb: 0,
compressionRatio: 0,
avgLogProb: -2.0
)
)
XCTAssertEqual(fallback3.fallbackReason, "compressionRatioThreshold")
XCTAssertTrue(fallback3.needsFallback)
let fallback4 = try XCTUnwrap(
DecodingFallback(
options: DecodingOptions(compressionRatioThreshold: 0.0, logProbThreshold: -1.0, noSpeechThreshold: 0.0),
isFirstTokenLogProbTooLow: false,
noSpeechProb: 0,
compressionRatio: 0,
avgLogProb: -2.0
)
)
XCTAssertEqual(fallback4.fallbackReason, "logProbThreshold")
XCTAssertTrue(fallback4.needsFallback)
XCTAssertNil(
DecodingFallback(
options: DecodingOptions(compressionRatioThreshold: 0.0, logProbThreshold: 0.0, noSpeechThreshold: 0.0),
isFirstTokenLogProbTooLow: false,
noSpeechProb: 0,
compressionRatio: 0,
avgLogProb: 0
)
)
}
// MARK: - Tokenizer Tests
func testDecoderTokenizer() async throws {
// This token index does not change with v3
let tokenText = "<|startoftranscript|>"
let textDecoder = TextDecoder()
textDecoder.tokenizer = try await loadTokenizer(for: .tiny)
let encodedToken = try XCTUnwrap(textDecoder.tokenizer?.convertTokenToId(tokenText))
let decodedToken = try XCTUnwrap(textDecoder.tokenizer?.decode(tokens: [encodedToken]))
textDecoder.tokenizer = try await loadTokenizer(for: .largev3)
let encodedTokenLarge = try XCTUnwrap(textDecoder.tokenizer?.convertTokenToId(tokenText))
let decodedTokenLarge = try XCTUnwrap(textDecoder.tokenizer?.decode(tokens: [encodedTokenLarge]))
// Test successful tokenizing
XCTAssertEqual(tokenText, decodedToken)
XCTAssertEqual(tokenText, decodedTokenLarge)
XCTAssertEqual(decodedToken, decodedTokenLarge)
// Test non shifted tokens are equal
XCTAssertEqual(encodedToken, encodedTokenLarge)
// This token index changes with v3
let tokenTextShifted = "<|0.00|>"
textDecoder.tokenizer = try await loadTokenizer(for: .tiny)
let encodedTokenShifted = try XCTUnwrap(textDecoder.tokenizer?.convertTokenToId(tokenTextShifted))
let decodedTokenShifted = try XCTUnwrap(textDecoder.tokenizer?.decode(tokens: [encodedTokenShifted]))
textDecoder.tokenizer = try await loadTokenizer(for: .largev3)
let encodedTokenLargeShifted = try XCTUnwrap(textDecoder.tokenizer?.convertTokenToId(tokenTextShifted))
let decodedTokenLargeShifted = try XCTUnwrap(textDecoder.tokenizer?.decode(tokens: [encodedTokenLargeShifted]))
// Test success tokenizing
XCTAssertEqual(tokenTextShifted, decodedTokenShifted)
XCTAssertEqual(tokenTextShifted, decodedTokenLargeShifted)
// Test shifted tokens are not equal
XCTAssertNotEqual(encodedTokenShifted, encodedTokenLargeShifted)
}
func testTokenizerOutput() async throws {
let tokenInputs = [50364, 400, 370, 452, 7177, 6280, 1029, 406, 437, 428, 1941, 393, 360, 337, 291, 1029, 437, 291, 393, 360, 337, 428, 1941, 13, 50889]
let tokenizer = try await loadTokenizer(for: .largev3)
let decodedText = tokenizer.decode(tokens: tokenInputs)
XCTAssertNotNil(decodedText)
XCTAssertEqual(decodedText, "<|notimestamps|> And so my fellow Americans ask not what your country can do for you ask what you can do for your country.<|10.48|>")
}
func testWindowing() async throws {
let computeOptions = ModelComputeOptions(
melCompute: .cpuOnly
)
let whisperKit = try await WhisperKit(
modelFolder: tinyModelPath(),
computeOptions: computeOptions,
verbose: true,
logLevel: .debug
)
let audioFilePath = try XCTUnwrap(
Bundle.module.path(forResource: "jfk", ofType: "wav"),
"Audio file not found"
)
let audioBuffer = try XCTUnwrap(
AudioProcessor.loadAudio(fromPath: audioFilePath),
"Failed to load audio buffer"
)
let audioSamples = AudioProcessor.convertBufferToArray(buffer: audioBuffer)
let silence = [Float](repeating: 0.0, count: 30 * 16000)
let multiWindowSamples = audioSamples + silence + audioSamples
let options = DecodingOptions(usePrefillPrompt: true, withoutTimestamps: false, firstTokenLogProbThreshold: nil)
let transcribeResult = try await whisperKit.transcribe(audioArray: multiWindowSamples, decodeOptions: options)
let result = try XCTUnwrap(transcribeResult)
XCTAssertEqual(result.segments.count, 2, "Expected 3 segments")
// Compare last timestamp to the length of the audio
let endTimestamp = try XCTUnwrap(
result.segments.last?.end,
"Failed to get end time"
)
XCTAssertEqual(endTimestamp, Float(multiWindowSamples.count / 16000), accuracy: 1.0, "Expected last timestamp to be near the length of the audio")
}
func testSplitToWordTokens() async throws {
let tokenizer = try await loadTokenizer(for: .tiny)
// Hello, world! This is a test, isn't it?
let tokenIds = [50364, 2425, 11, 1002, 0, 50414, 50414, 639, 307, 257, 220, 31636, 11, 1943, 380, 309, 30, 50257]
let originalWords = tokenIds.map { tokenizer.convertIdToToken($0) }
let (words, wordTokens) = tokenizer.splitToWordTokens(tokenIds: tokenIds)
let expectedWords = ["<|0.00|>", " Hello", ",", " world", "!", "<|1.00|>", "<|1.00|>", " This", " is", " a", " test", ",", " isn't", " it", "?", "<|endoftext|>"]
let expectedWordTokens = [[50364], [2425], [11], [1002], [0], [50414], [50414], [639], [307], [257], [220, 31636], [11], [1943, 380], [309], [30], [50257]]
XCTAssertNotEqual(originalWords, words, "Should not directly convert into tokens from ids")
XCTAssertEqual(words, expectedWords, "Words did not match expected output.")
XCTAssertEqual(wordTokens, expectedWordTokens, "Word tokens did not match expected output.")
}
func testSplitToWordTokensSpanish() async throws {
let tokenizer = try await loadTokenizer(for: .tiny)
// ¡Hola Mundo! Esta es una prueba, ¿no?
let tokenIds = [50363, 24364, 48529, 376, 6043, 0, 20547, 785, 2002, 48241, 11, 3841, 1771, 30, 50257]
let originalWords = tokenIds.map { tokenizer.convertIdToToken($0) }
let (words, wordTokens) = tokenizer.splitToWordTokens(tokenIds: tokenIds)
let expectedWords = ["<|notimestamps|>", "¡Hola", " Mundo", "!", " Esta", " es", " una", " prueba", ",", " ¿no", "?", "<|endoftext|>"]
let expectedWordTokens = [[50363], [24364, 48529], [376, 6043], [0], [20547], [785], [2002], [48241], [11], [3841, 1771], [30], [50257]]
XCTAssertNotEqual(originalWords, words, "Should not directly convert into tokens from ids")
XCTAssertEqual(words, expectedWords, "Words did not match expected output.")
XCTAssertEqual(wordTokens, expectedWordTokens, "Word tokens did not match expected output.")
}
func testSplitToWordTokensJapanese() async throws {
let tokenizer = try await loadTokenizer(for: .tiny)
// こんにちは、世界!これはテストですよね?
let tokenIds = [50364, 38088, 1231, 24486, 171, 120, 223, 25212, 22985, 40498, 4767, 30346, 171, 120, 253, 50257]
let originalWords = tokenIds.map { tokenizer.convertIdToToken($0) }
let (words, wordTokens) = tokenizer.splitToWordTokens(tokenIds: tokenIds)
let expectedWords = ["<|0.00|>", "こんにちは", "、", "世界", "!", "これは", "テ", "スト", "です", "よね", "?", "<|endoftext|>"]
let expectedWordTokens = [[50364], [38088], [1231], [24486], [171, 120, 223], [25212], [22985], [40498], [4767], [30346], [171, 120, 253], [50257]]
XCTAssertNotEqual(originalWords, words, "Should not directly convert into tokens from ids")
XCTAssertEqual(words, expectedWords, "Words did not match expected output in Unicode split.")
XCTAssertEqual(wordTokens, expectedWordTokens, "Word tokens did not match expected output in Unicode split.")
}
// MARK: - Options Tests
func testSampleLength() async throws {
let desiredDecodingLoops = 5
let targetTokenCount = 7 // Account for the first token and the end of transcript token, which dont require decoding loops
let options = [
DecodingOptions(sampleLength: desiredDecodingLoops, usePrefillPrompt: false, skipSpecialTokens: false),
DecodingOptions(sampleLength: desiredDecodingLoops, usePrefillPrompt: true, skipSpecialTokens: false),
DecodingOptions(sampleLength: desiredDecodingLoops, usePrefillPrompt: false, skipSpecialTokens: true),
DecodingOptions(sampleLength: desiredDecodingLoops, usePrefillPrompt: true, skipSpecialTokens: true),
]
for option in options {
let result = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: option),
"Failed to transcribe"
)
XCTAssertEqual(result.segments.first?.tokens.count, targetTokenCount)
}
}
/// Multilingual Tests
/// NOTE: These are purely for consistency checks and do not reflect the ground truth translations
func testTranslateSpanish() async throws {
let targetLanguage = "es"
let options = DecodingOptions(task: .translate, language: targetLanguage, temperatureFallbackCount: 0)
let result = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: options, audioFile: "es_test_clip.wav"),
"Failed to transcribe"
)
XCTAssertEqual(result.text.split(separator: " ").prefix(2).joined(separator: " "), "This is")
}
func testTranscribeSpanish() async throws {
let sourceLanguage = "es"
let options = DecodingOptions(task: .transcribe, language: sourceLanguage, temperatureFallbackCount: 0)
let result = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: options, audioFile: "es_test_clip.wav"),
"Failed to transcribe"
)
XCTAssertEqual(result.text.split(separator: " ").prefix(4).joined(separator: " "), "Esta es una grabación")
}
func testDetectSpanish() async{
let targetLanguage = "es"
let prefillLanguage = "en"
let optionsNoPrefill = DecodingOptions(task: .transcribe, temperatureFallbackCount: 0, usePrefillPrompt: false)
guard let resultNoPrefill = try? await transcribe(with: .tiny, options: optionsNoPrefill, audioFile: "es_test_clip.wav") else {
XCTFail("Failed to transcribe")
return
}
XCTAssertEqual(resultNoPrefill.language, targetLanguage)
let optionsPrefill = DecodingOptions(task: .transcribe, temperatureFallbackCount: 0, usePrefillPrompt: true)
guard let resultPrefill = try? await transcribe(with: .tiny, options: optionsPrefill, audioFile: "es_test_clip.wav") else {
XCTFail("Failed to transcribe")
return
}
XCTAssertEqual(resultPrefill.language, prefillLanguage)
}
func testTranslateJapanese() async throws {
let targetLanguage = "ja"
let options = DecodingOptions(task: .translate, language: targetLanguage, temperatureFallbackCount: 0)
let result = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: options, audioFile: "ja_test_clip.wav"),
"Failed to transcribe"
)
XCTAssertEqual(result.text.split(separator: " ").first, "Tokyo")
}
func testTranscribeJapanese() async throws {
let sourceLanguage = "ja"
let options = DecodingOptions(task: .transcribe, language: sourceLanguage, temperatureFallbackCount: 0)
let result = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: options, audioFile: "ja_test_clip.wav"),
"Failed to transcribe"
)
XCTAssertEqual(result.text.prefix(3), "東京は")
}
func testDetectJapanese() async{
let targetLanguage = "ja"
let prefillLanguage = "en"
let optionsNoPrefill = DecodingOptions(task: .transcribe, temperatureFallbackCount: 0, usePrefillPrompt: false)
guard let resultNoPrefill = try? await transcribe(with: .tiny, options: optionsNoPrefill, audioFile: "ja_test_clip.wav") else {
XCTFail("Failed to transcribe")
return
}
XCTAssertEqual(resultNoPrefill.language, targetLanguage)
let optionsPrefill = DecodingOptions(task: .transcribe, temperatureFallbackCount: 0, usePrefillPrompt: true)
guard let resultPrefill = try? await transcribe(with: .tiny, options: optionsPrefill, audioFile: "ja_test_clip.wav") else {
XCTFail("Failed to transcribe")
return
}
XCTAssertEqual(resultPrefill.language, prefillLanguage)
}
func testNoTimestamps() async throws {
let options = DecodingOptions(withoutTimestamps: true)
let result = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: options),
"Failed to transcribe"
)
XCTAssertEqual(result.segments.first?.text.normalized, "<|startoftranscript|><|en|><|transcribe|><|notimestamps|> And so my fellow Americans ask not what your country can do for you, ask what you can do for your country.<|endoftext|>".normalized)
}
func testSkipSpecialTokens() async throws {
let options = DecodingOptions(skipSpecialTokens: true, withoutTimestamps: true)
let result = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: options),
"Failed to transcribe"
)
XCTAssertEqual(result.segments.first?.text.normalized, " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country.".normalized)
}
func testPrefill() async throws {
let options = DecodingOptions(usePrefillPrompt: true)
try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: options),
"Failed to transcribe"
)
}
func testNoPrefill() async throws {
let options = DecodingOptions(usePrefillPrompt: false)
let result = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: options),
"Failed to transcribe"
)
XCTAssertNotNil(result.text)
}
func testSilence() async throws {
let whisperKit = try await WhisperKit(modelFolder: tinyModelPath(), verbose: true, logLevel: .debug)
let audioSamples = [Float](repeating: 0.0, count: 30 * 16000)
let options = DecodingOptions(usePrefillPrompt: false, skipSpecialTokens: false)
let result = try await XCTUnwrapAsync(
await whisperKit.transcribe(audioArray: audioSamples, decodeOptions: options),
"Failed to transcribe"
)
XCTAssertTrue(result.segments.first!.tokens.contains(whisperKit.tokenizer!.specialTokens.noSpeechToken))
}
func testTemperatureIncrement() async throws {
let whisperKit = try await WhisperKit(modelFolder: tinyModelPath(), verbose: true, logLevel: .debug)
// Generate random audio samples
let audioSamples = (0..<(30 * 16000)).map { _ in Float.random(in: -0.7...0.7) }
// Define options with temperature increment settings
let initialTemperature: Float = 0
let temperatureIncrement: Float = 0.1
let fallbackCount = 1
let options = DecodingOptions(
temperature: initialTemperature,
temperatureIncrementOnFallback: temperatureIncrement,
temperatureFallbackCount: fallbackCount,
usePrefillPrompt: false,
logProbThreshold: 0
)
// Perform transcription
let result = try await XCTUnwrapAsync(
await whisperKit.transcribe(audioArray: audioSamples, decodeOptions: options),
"Failed to transcribe"
)
let expectedTemperature = initialTemperature + temperatureIncrement * Float(fallbackCount)
XCTAssertEqual(result.segments.first!.temperature, expectedTemperature, "Temperature was not incremented correctly after fallbacks")
}
func testTopK() async throws {
let result10000 = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: DecodingOptions(temperature: 0.5, topK: 10000)),
"Failed to transcribe"
)
let result5 = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: DecodingOptions(temperature: 0.5)),
"Failed to transcribe"
)
XCTAssertLessThan(Float(result5.timings!.decodingSampling), Float(result10000.timings!.decodingSampling), "topK=5 should be faster than topK=10000")
}
func testSeekClips() async throws {
var options = DecodingOptions(withoutTimestamps: true, clipTimestamps: [0])
let resultFull = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: options),
"Failed to transcribe"
)
let seekTime: Float = 3.0
options = DecodingOptions(withoutTimestamps: true, clipTimestamps: [seekTime])
let resultSeek = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: options),
"Failed to transcribe"
)
XCTAssertNotEqual(resultFull.text, resultSeek.text)
XCTAssertTrue(resultFull.text.normalized.contains(resultSeek.text.normalized), "Seeking should be a subset of the full clip")
XCTAssertFalse(resultSeek.text.normalized.contains(resultFull.text.normalized), "Seeking should be a subset of the full clip")
XCTAssertEqual(resultSeek.segments.first?.start, seekTime, "Seek segment should have the input start time")
XCTAssertNotEqual(resultFull.segments.first?.start, resultSeek.segments.first?.start, "Segments should have the different start times")
XCTAssertEqual(resultFull.segments.first?.end, resultSeek.segments.first?.end, "Segments should have the same end time")
}
func testPromptTokens() async throws {
let whisperKit = try await WhisperKit(modelFolder: tinyModelPath(), verbose: true, logLevel: .debug)
let promptText = " prompt to encourage output without any punctuation and without capitalizing americans as if it was already normalized"
let tokenizer = whisperKit.tokenizer!
let promptTokens = tokenizer.encode(text: promptText).filter { $0 < tokenizer.specialTokens.specialTokenBegin }
let options = DecodingOptions(skipSpecialTokens: true, promptTokens: promptTokens)
let result = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: options),
"Failed to transcribe"
)
XCTAssertEqual(result.segments.first?.text, " and so my fellow americans ask not what your country can do for you ask what you can do for your country.")
}
func testPrefixTokens() async throws {
let whisperKit = try await WhisperKit(modelFolder: tinyModelPath(), verbose: true, logLevel: .debug)
// Prefix to encourage output without any punctuation and without capitalizing americans as if it was already normalized
let prefixText = " and so my fellow americans"
let tokenizer = whisperKit.tokenizer!
let prefixTokens = tokenizer.encode(text: prefixText).filter { $0 < tokenizer.specialTokens.specialTokenBegin }
let options = DecodingOptions(skipSpecialTokens: true, prefixTokens: prefixTokens)
let result = try await XCTUnwrapAsync(
await transcribe(with: .tiny, options: options),
"Failed to transcribe"
)
XCTAssertEqual(result.segments.first?.text, " and so my fellow americans ask not what your country can do for you ask what you can do for your country.")
}
// MARK: - Utils Tests
func testFillIndexesWithValue() throws {
let logits = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
logits.fill(indexes: [] as [[NSNumber]], with: -FloatType.infinity)
XCTAssertEqual(logits.data(for: 2), [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let logits2 = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let indexes2: [[NSNumber]] = [[0, 0, 0], [0, 0, 1], [0, 0, 5]]
logits2.fill(indexes: indexes2, with: -FloatType.infinity)
XCTAssertEqual(logits2.data(for: 2), [-.infinity, -.infinity, 0.3, 0.4, 0.5, -.infinity, 0.7])
let logits3 = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
logits3.fillLastDimension(indexes: 0..<1, with: -FloatType.infinity)
XCTAssertEqual(logits3.data(for: 2), [-.infinity, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let logits4 = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
logits4.fillLastDimension(indexes: 2..<5, with: -FloatType.infinity)
XCTAssertEqual(logits4.data(for: 2), [0.1, 0.2, -.infinity, -.infinity, -.infinity, 0.6, 0.7])
}
// MARK: - LogitsFilter Tests
func testSuppressTokensFilter() throws {
let tokensFilter1 = SuppressTokensFilter(suppressTokens: [])
let logits1 = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let result1 = tokensFilter1.filterLogits(logits1, withTokens: [])
XCTAssertEqual(result1.data(for: 2), [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let tokensFilter2 = SuppressTokensFilter(suppressTokens: [0])
let logits2 = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let result2 = tokensFilter2.filterLogits(logits2, withTokens: [])
XCTAssertEqual(result2.data(for: 2), [-.infinity, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let tokensFilter3 = SuppressTokensFilter(suppressTokens: [0, 2, 5, 6])
let logits3 = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let result3 = tokensFilter3.filterLogits(logits3, withTokens: [])
XCTAssertEqual(result3.data(for: 2), [-.infinity, 0.2, -.infinity, 0.4, 0.5, -.infinity, -.infinity])
}
func testSuppressBlankFilter() throws {
let tokensFilter2 = SuppressBlankFilter(
specialTokens: .default(),
sampleBegin: 0
)
let logits2 = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let result2 = tokensFilter2.filterLogits(logits2, withTokens: [])
XCTAssertEqual(result2.data(for: 2), [-.infinity, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let tokensFilter3 = SuppressBlankFilter(
specialTokens: .default(endToken: 0, whitespaceToken: 2),
sampleBegin: 0
)
let logits3 = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let result3 = tokensFilter3.filterLogits(logits3, withTokens: [])
XCTAssertEqual(result3.data(for: 2), [-.infinity, 0.2, -.infinity, 0.4, 0.5, 0.6, 0.7])
let tokensFilter4 = SuppressBlankFilter(
specialTokens: .default(endToken: 0, whitespaceToken: 2),
sampleBegin: 3
)
let logits4 = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let result4 = tokensFilter4.filterLogits(logits4, withTokens: [1, 2, 3])
XCTAssertEqual(result4.data(for: 2), [-.infinity, 0.2, -.infinity, 0.4, 0.5, 0.6, 0.7])
let tokensFilter5 = SuppressBlankFilter(
specialTokens: .default(endToken: 0, whitespaceToken: 2),
sampleBegin: 5
)
let logits5 = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let result5 = tokensFilter5.filterLogits(logits5, withTokens: [1, 2, 3])
XCTAssertEqual(result5.data(for: 2), [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
}
func testLanguageLogitsFilter() throws{
let tokensFilter1 = LanguageLogitsFilter(allLanguageTokens: [2, 4, 6], logitsDim: 7, sampleBegin: 0)
let logits1 = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let result1 = tokensFilter1.filterLogits(logits1, withTokens: [])
XCTAssertEqual(result1.data(for: 2), [-.infinity, -.infinity, 0.3, -.infinity, 0.5, -.infinity, 0.7])
let tokensFilter2 = LanguageLogitsFilter(allLanguageTokens: [2, 4, 6], logitsDim: 7, sampleBegin: 0)
let logits2 = try MLMultiArray.logits([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
let result2 = tokensFilter2.filterLogits(logits2, withTokens: [1])
XCTAssertEqual(result2.data(for: 2), [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
}
func testTimestampRulesFilter() throws {
// NOTE: for non-multilingual models we supress tokens immediately
let tokensFilter1 = TimestampRulesFilter(
specialTokens: .default(
endToken: 3,
noTimestampsToken: 2,
timeTokenBegin: 4,
transcribeToken: 100,
translateToken: 101
),
sampleBegin: 2,
maxInitialTimestampIndex: nil,
isModelMultilingual: false
)
let logits1 = try MLMultiArray.logits([1.1, 5.2, 0.3, 0.4, 0.2, 0.1, 0.2])
let result1 = tokensFilter1.filterLogits(logits1, withTokens: [])
XCTAssertEqual(result1.data(for: 2), [1.1, 5.2, -.infinity, 0.4, 0.2, 0.1, 0.2])
let tokensFilter2 = TimestampRulesFilter(
specialTokens: .default(
endToken: 3,
noTimestampsToken: 2,
timeTokenBegin: 4,
transcribeToken: 100,
translateToken: 101
),
sampleBegin: 2,
maxInitialTimestampIndex: nil,
isModelMultilingual: false
)
let logits2 = try MLMultiArray.logits([1.1, 0.2, 0.3, 0.4, 0.2, 0.1, 0.2])
let result2 = tokensFilter2.filterLogits(logits2, withTokens: [])
XCTAssertEqual(result2.data(for: 2), [-.infinity, -.infinity, -.infinity, -.infinity, 0.2, 0.1, 0.2])
}
func testTimestampRulesFilterMultilingual() throws {
// NOTE: for multilingual models we supress tokens only after transcribe or translate token
let tokensFilter1 = TimestampRulesFilter(
specialTokens: .default(
endToken: 3,
noTimestampsToken: 2,
timeTokenBegin: 4,
transcribeToken: 100,
translateToken: 101
),
sampleBegin: 2,
maxInitialTimestampIndex: nil,
isModelMultilingual: true
)
let logits1 = try MLMultiArray.logits([1.1, 5.2, 0.3, 0.4, 0.2, 0.1, 0.2])
let result1 = tokensFilter1.filterLogits(logits1, withTokens: [])
XCTAssertEqual(result1.data(for: 2), [1.1, 5.2, 0.3, 0.4, 0.2, 0.1, 0.2])
let tokensFilter2 = TimestampRulesFilter(
specialTokens: .default(
endToken: 3,
noTimestampsToken: 2,
timeTokenBegin: 4,
transcribeToken: 100,
translateToken: 101
),
sampleBegin: 2,
maxInitialTimestampIndex: nil,
isModelMultilingual: true
)
let logits2 = try MLMultiArray.logits([1.1, 5.2, 0.3, 0.4, 0.2, 0.1, 0.2])
let result2 = tokensFilter2.filterLogits(logits2, withTokens: [100])
XCTAssertEqual(result2.data(for: 2), [1.1, 5.2, -.infinity, 0.4, 0.2, 0.1, 0.2])
let tokensFilter3 = TimestampRulesFilter(
specialTokens: .default(
endToken: 3,
noTimestampsToken: 2,
timeTokenBegin: 4,
transcribeToken: 100,
translateToken: 101
),
sampleBegin: 2,
maxInitialTimestampIndex: nil,
isModelMultilingual: true
)
let logits3 = try MLMultiArray.logits([1.1, 0.2, 0.3, 0.4, 0.2, 0.1, 0.2])
let result3 = tokensFilter3.filterLogits(logits3, withTokens: [101])
XCTAssertEqual(result3.data(for: 2), [-.infinity, -.infinity, -.infinity, -.infinity, 0.2, 0.1, 0.2])
}
// MARK: - Word Timestamp Tests
func testDynamicTimeWarpingSimpleMatrix() {
let matrix = [
[1.0, 1.0, 1.0],
[5.0, 2.0, 1.0],
[1.0, 5.0, 2.0],
]
let numRows = matrix.count
let numColumns = matrix[0].count
let mlMatrix = try! MLMultiArray(shape: [numRows, numColumns] as [NSNumber], dataType: .double)
let ptr = UnsafeMutablePointer<Double>(OpaquePointer(mlMatrix.dataPointer))
for (i, row) in matrix.enumerated() {
for (j, value) in row.enumerated() {
let linearOffset = mlMatrix.linearOffset(for: [i, j] as [NSNumber])
ptr[linearOffset] = value
}
}
let segmentSeeker = SegmentSeeker()
do {
let result = try segmentSeeker.dynamicTimeWarping(withMatrix: mlMatrix)
let expected = (
textIndices: [0, 1, 1, 2, 2],
timeIndices: [0, 0, 1, 1, 2]
)
XCTAssertEqual(result.textIndices, expected.textIndices, "dynamicTimeWarping function did not return the expected path.")
XCTAssertEqual(result.timeIndices, expected.timeIndices, "dynamicTimeWarping function did not return the expected path.")
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func testDynamicTimeWarpingLargeMatrix() {
// Create a large matrix with non-linear characteristics
let numberOfRows: NSNumber = 448
let numberOfColumns: NSNumber = 1500
// Populate the matrix with some non-linear data
let matrix = try! MLMultiArray(shape: [numberOfRows, numberOfColumns], dataType: .float16)
for i in 0..<numberOfRows.intValue {
for j in 0..<numberOfColumns.intValue {
matrix[i * numberOfColumns.intValue + j] = NSNumber(value: Double.random(in: 0...1))
}
}
let segmentSeeker = SegmentSeeker()
do {
let result = try segmentSeeker.dynamicTimeWarping(withMatrix: matrix)
// Validate the output dimensions
XCTAssertFalse(result.textIndices.isEmpty, "Result should not be empty.")
XCTAssertFalse(result.timeIndices.isEmpty, "Result should not be empty.")
// Validate start and end points
XCTAssertEqual(result.textIndices.first, 0, "Path should start at (0, 0).")
XCTAssertEqual(result.timeIndices.first, 0, "Path should start at (0, 0).")
XCTAssertEqual(result.textIndices.last, numberOfRows.intValue - 1, "Path should end at (N-1, M-1).")
XCTAssertEqual(result.timeIndices.last, numberOfColumns.intValue - 1, "Path should end at (N-1, M-1).")
// Check path continuity and bounds
for i in 1..<result.textIndices.count {
let (prevRow, prevCol) = (result.textIndices[i - 1], result.timeIndices[i - 1])
let (currentRow, currentCol) = (result.textIndices[i], result.timeIndices[i])
let rowDiff = currentRow - prevRow
let colDiff = currentCol - prevCol
// Assert that the row difference is 0 or 1
XCTAssertTrue(rowDiff == 0 || rowDiff == 1, "Row difference should be 0 or 1")
// Assert that the column difference is 0 or 1
XCTAssertTrue(colDiff == 0 || colDiff == 1, "Column difference should be 0 or 1")
// Assert that at least one of rowDiff or colDiff is 1
XCTAssertTrue(rowDiff == 1 || colDiff == 1, "At least one of rowDiff or colDiff should be 1")
// Assert that rowDiff and colDiff are not both 0
XCTAssertFalse(rowDiff == 0 && colDiff == 0, "Both rowDiff and colDiff should not be 0 at the same time")
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func testFindAlignment() async throws {
let numberOfRows: NSNumber = 448
let numberOfColumns: NSNumber = 1500
// Populate the matrix with some non-linear data
let matrix = try MLMultiArray(shape: [numberOfRows, numberOfColumns], dataType: .float16)
let tokenProbs = Array(repeating: 0.0, count: numberOfRows.intValue).map { _ in Float.random(in: -1..<0) }
for i in 0..<numberOfRows.intValue {
for j in 0..<numberOfColumns.intValue {
matrix[i * numberOfColumns.intValue + j] = NSNumber(value: Double.random(in: 0...1))
}
}
let tokenizer = try await loadTokenizer(for: .tiny)
let wordTokenIds = [400, 370, 452, 7177, 6280, 11, 1029, 406, 437, 428, 1941, 393, 360, 337, 291, 11, 1029, 437, 291, 393, 360, 337, 428, 1941, 13]
let result = try SegmentSeeker().findAlignment(
wordTokenIds: wordTokenIds,
alignmentWeights: matrix,
tokenLogProbs: tokenProbs,
tokenizer: tokenizer
)
XCTAssertFalse(result.isEmpty, "Result should not be empty.")
var previousEndTime: Float = -1.0
for wordTiming in result {
XCTAssertFalse(wordTiming.word.isEmpty, "Word should not be empty.")
XCTAssertFalse(wordTiming.tokens.isEmpty, "Tokens should not be empty.")
XCTAssert(wordTiming.tokens.allSatisfy { $0 >= 0 }, "All token IDs should be non-negative.")
XCTAssertLessThanOrEqual(wordTiming.start, wordTiming.end, "Start should be less than or equal to end.")
XCTAssertGreaterThanOrEqual(wordTiming.start, previousEndTime, "Start time should not be earlier than the previous end time.")