forked from mpuig/dictate.sh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstt.py
More file actions
1685 lines (1448 loc) · 61.5 KB
/
stt.py
File metadata and controls
1685 lines (1448 loc) · 61.5 KB
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
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "mlx>=0.22.0",
# "mlx-lm>=0.22.0",
# "numpy",
# "sounddevice",
# "setuptools",
# "transformers",
# "huggingface_hub",
# "webrtcvad",
# "rich",
# ]
# ///
"""
Standalone, low-latency transcription for Apple Silicon.
Uses MLX so inference stays local and fast on macOS.
VAD marks turn boundaries to avoid constant analysis while keeping responses timely.
Design notes:
- Rolling-window ASR trades some stability for low latency.
- VAD reduces GPU work by running ASR only when useful.
- MLX is serialized to avoid concurrency issues on the GPU.
- Logging goes to stderr so transcripts stay clean on stdout.
Troubleshooting:
- If turns split too often: increase --vad-silence-ms or lower --vad-mode.
- If nothing transcribes: check mic permissions or run --list-devices.
- If output feels laggy: reduce --transcribe-interval.
Usage:
uv run stt.py
uv run stt.py --model mlx-community/Qwen3-ASR-1.7B-8bit
uv run stt.py --analyze # opt-in if you want intent analysis
uv run stt.py --vad-mode 3 --vad-silence-ms 700
Models (MLX Qwen3-ASR):
- mlx-community/Qwen3-ASR-0.6B-4bit: fastest, lowest quality.
- mlx-community/Qwen3-ASR-0.6B-8bit: good balance (default).
- mlx-community/Qwen3-ASR-0.6B-bf16: higher quality, more RAM.
- mlx-community/Qwen3-ASR-1.7B-8bit: higher quality, slower.
LLM models for --llm-model (examples; availability may change):
- mlx-community/Qwen3-0.6B-4bit: fastest, lowest RAM (default).
- mlx-community/Qwen3-1.7B-4bit: better quality, slower.
- mlx-community/Mistral-7B-Instruct-v0.2-4bit: heavier.
- mlx-community/Llama-3.1-8B-Instruct-4bit: heavier.
"""
import argparse
import asyncio
import contextlib
import glob
import io
import json
import logging
import math
import os # noqa: E402
import re
import shutil
import signal
import sys
import time
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, Generator, List, Optional, Protocol, Sequence, Tuple
# -----------------------------------------------------------------------------
# Environment setup
# -----------------------------------------------------------------------------
# Keep this before MLX/Transformers imports to reduce noisy warnings and progress
# bars. The # noqa: E402 imports below are intentional for this reason.
# Reduce noisy stderr in a real-time CLI.
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
os.environ["PYTHONWARNINGS"] = "ignore"
os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "1"
# MLX deprecation chatter overwhelms live output.
import mlx.core as mx # noqa: E402
if hasattr(mx, "set_warnings_enabled"):
mx.set_warnings_enabled(False)
import mlx.nn as nn # noqa: E402
import numpy as np # noqa: E402
import sounddevice as sd # noqa: E402
import webrtcvad # noqa: E402
from huggingface_hub import snapshot_download # noqa: E402
from rich.console import Console # noqa: E402
from rich.layout import Layout # noqa: E402
from rich.live import Live # noqa: E402
from rich.logging import RichHandler # noqa: E402
from rich.panel import Panel # noqa: E402
from rich.table import Table # noqa: E402
from rich.text import Text # noqa: E402
# -----------------------------------------------------------------------------
# Defaults
# -----------------------------------------------------------------------------
DEFAULT_ASR_MODEL = "mlx-community/Qwen3-ASR-0.6B-8bit"
DEFAULT_LLM_MODEL = "mlx-community/Qwen3-0.6B-4bit"
DEFAULT_LANGUAGE = "English"
DEFAULT_SAMPLE_RATE = 16000
DEFAULT_TRANSCRIBE_INTERVAL = 0.5
DEFAULT_VAD_FRAME_MS = 30
DEFAULT_VAD_MODE = 2
DEFAULT_VAD_SILENCE_MS = 500
DEFAULT_MIN_WORDS = 3
DEFAULT_MAX_BUFFER_SECONDS = 30
DEFAULT_AUDIO_QUEUE_MAXSIZE = 200
# -----------------------------------------------------------------------------
# Logging
# -----------------------------------------------------------------------------
LOGGER = logging.getLogger("speech")
@contextlib.contextmanager
def _suppress_output():
"""Hide noisy library prints/warnings during background inference."""
devnull = os.open(os.devnull, os.O_WRONLY)
stderr_fd = os.dup(2)
try:
os.dup2(devnull, 2)
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(
io.StringIO()
):
yield
finally:
os.dup2(stderr_fd, 2)
os.close(stderr_fd)
os.close(devnull)
# -----------------------------------------------------------------------------
# Protocols
# -----------------------------------------------------------------------------
class TokenizerLike(Protocol):
def encode(self, text: str, return_tensors: str) -> Any: ...
def decode(self, token_ids: Sequence[int]) -> str: ...
def apply_chat_template(
self,
messages: Sequence[Dict[str, str]],
tokenize: bool,
add_generation_prompt: bool,
) -> str: ...
class FeatureExtractorLike(Protocol):
def __call__(
self,
audio: np.ndarray,
sampling_rate: int,
return_attention_mask: bool,
truncation: bool,
padding: bool,
return_tensors: str,
) -> Dict[str, Any]: ...
# =============================================================================
# Configuration Classes
# =============================================================================
@dataclass
class AudioEncoderConfig:
num_mel_bins: int = 128
encoder_layers: int = 24
encoder_attention_heads: int = 16
encoder_ffn_dim: int = 4096
d_model: int = 1024
scale_embedding: bool = False
max_source_positions: int = 1500
n_window: int = 50
output_dim: int = 2048
n_window_infer: int = 800
conv_chunksize: int = 500
downsample_hidden_size: int = 480
@dataclass
class TextConfig:
vocab_size: int = 151936
hidden_size: int = 2048
intermediate_size: int = 6144
num_hidden_layers: int = 28
num_attention_heads: int = 16
num_key_value_heads: int = 8
head_dim: int = 128
rms_norm_eps: float = 1e-6
tie_word_embeddings: bool = True
rope_theta: float = 1000000.0
@dataclass
class ModelConfig:
audio_config: AudioEncoderConfig = None
text_config: TextConfig = None
audio_token_id: int = 151676
support_languages: List[str] = field(default_factory=list)
def __post_init__(self):
if self.audio_config is None:
self.audio_config = AudioEncoderConfig()
elif isinstance(self.audio_config, dict):
self.audio_config = AudioEncoderConfig(
**{
k: v
for k, v in self.audio_config.items()
if k in AudioEncoderConfig.__dataclass_fields__
}
)
if self.text_config is None:
self.text_config = TextConfig()
elif isinstance(self.text_config, dict):
self.text_config = TextConfig(
**{
k: v
for k, v in self.text_config.items()
if k in TextConfig.__dataclass_fields__
}
)
# =============================================================================
# Model Architecture
# =============================================================================
def create_additive_causal_mask(N: int, offset: int = 0) -> mx.array:
"""Return an additive causal mask to prevent attention to future tokens."""
rinds = mx.arange(offset + N)
linds = mx.arange(offset, offset + N) if offset else rinds
mask = linds[:, None] < rinds[None]
return mask * -1e9
def _floor_div(a: mx.array, b: int) -> mx.array:
"""Floor-divide while keeping MLX tensors, avoiding host/device sync."""
return mx.floor(a.astype(mx.float32) / b).astype(mx.int32)
def _get_feat_extract_output_lengths(input_lengths: mx.array) -> mx.array:
"""Track time-downsampling so chunk masks align with conv output."""
input_lengths_leave = input_lengths % 100
feat_lengths = _floor_div(input_lengths_leave - 1, 2) + 1
output_lengths = (
_floor_div(_floor_div(feat_lengths - 1, 2) + 1 - 1, 2)
+ 1
+ (input_lengths // 100) * 13
)
return output_lengths
class SinusoidalPositionEmbedding(nn.Module):
"""Fixed positions so timing is known without extra learned parameters."""
def __init__(self, length: int, channels: int, max_timescale: float = 10000.0):
super().__init__()
log_timescale_increment = math.log(max_timescale) / (channels // 2 - 1)
inv_timescales = mx.exp(
-log_timescale_increment * mx.arange(channels // 2, dtype=mx.float32)
)
positions = mx.arange(length, dtype=mx.float32)[:, None]
scaled_time = positions * inv_timescales[None, :]
self._positional_embedding = mx.concatenate(
[mx.sin(scaled_time), mx.cos(scaled_time)], axis=1
)
def __call__(self, seqlen: int) -> mx.array:
return self._positional_embedding[:seqlen, :]
class AudioAttention(nn.Module):
"""Self-attention to relate distant audio frames for context."""
def __init__(self, config: AudioEncoderConfig):
super().__init__()
self.embed_dim = config.d_model
self.num_heads = config.encoder_attention_heads
self.head_dim = self.embed_dim // self.num_heads
self.scaling = self.head_dim ** -0.5
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
def __call__(
self, hidden_states: mx.array, mask: Optional[mx.array] = None
) -> mx.array:
bsz, seq_len, _ = hidden_states.shape
queries = self.q_proj(hidden_states) * self.scaling
keys = self.k_proj(hidden_states)
values = self.v_proj(hidden_states)
queries = queries.reshape(
bsz, seq_len, self.num_heads, self.head_dim
).transpose(0, 2, 1, 3)
keys = keys.reshape(bsz, seq_len, self.num_heads, self.head_dim).transpose(
0, 2, 1, 3
)
values = values.reshape(bsz, seq_len, self.num_heads, self.head_dim).transpose(
0, 2, 1, 3
)
attn_output = mx.fast.scaled_dot_product_attention(
queries, keys, values, scale=1.0, mask=mask
)
attn_output = attn_output.transpose(0, 2, 1, 3).reshape(
bsz, seq_len, self.embed_dim
)
return self.out_proj(attn_output)
class AudioEncoderLayer(nn.Module):
"""Transformer block to mix local and global audio features."""
def __init__(self, config: AudioEncoderConfig):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = AudioAttention(config)
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
def __call__(
self, hidden_states: mx.array, mask: Optional[mx.array] = None
) -> mx.array:
residual = hidden_states
hidden_states = self.self_attn_layer_norm(hidden_states)
hidden_states = self.self_attn(hidden_states, mask=mask)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.final_layer_norm(hidden_states)
hidden_states = nn.gelu(self.fc1(hidden_states))
hidden_states = self.fc2(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
class AudioEncoder(nn.Module):
"""Audio encoder that compresses time then builds contextual features."""
def __init__(self, config: AudioEncoderConfig):
super().__init__()
self.config = config
embed_dim = config.d_model
self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
self.n_window = config.n_window
self.n_window_infer = config.n_window_infer
self.conv2d1 = nn.Conv2d(
1, config.downsample_hidden_size, kernel_size=3, stride=2, padding=1
)
self.conv2d2 = nn.Conv2d(
config.downsample_hidden_size,
config.downsample_hidden_size,
kernel_size=3,
stride=2,
padding=1,
)
self.conv2d3 = nn.Conv2d(
config.downsample_hidden_size,
config.downsample_hidden_size,
kernel_size=3,
stride=2,
padding=1,
)
freq_after_conv = ((((config.num_mel_bins + 1) // 2) + 1) // 2 + 1) // 2
self.conv_out = nn.Linear(
config.downsample_hidden_size * freq_after_conv, embed_dim, bias=False
)
self.positional_embedding = SinusoidalPositionEmbedding(
config.max_source_positions, embed_dim
)
self.layers = [AudioEncoderLayer(config) for _ in range(config.encoder_layers)]
self.ln_post = nn.LayerNorm(embed_dim)
self.proj1 = nn.Linear(embed_dim, embed_dim)
self.proj2 = nn.Linear(embed_dim, config.output_dim)
def _create_block_attention_mask(
self, seq_len: int, cu_seqlens: List[int], dtype: mx.Dtype
) -> mx.array:
"""Limit attention to chunk boundaries for stability and speed."""
mask = mx.full((seq_len, seq_len), -1e9, dtype=dtype)
for i in range(len(cu_seqlens) - 1):
start, end = cu_seqlens[i], cu_seqlens[i + 1]
mask[start:end, start:end] = 0.0
return mask
def _compute_chunk_layout(
self, feature_lens: np.ndarray, chunk_size: int
) -> Tuple[np.ndarray, np.ndarray]:
"""Define chunking so long inputs stay bounded in memory/latency."""
chunk_counts = np.ceil(feature_lens / chunk_size).astype(np.int32)
chunk_lengths: List[int] = []
for feat_len, num_chunks in zip(feature_lens, chunk_counts):
feat_len = int(feat_len)
num_chunks = int(num_chunks)
for j in range(num_chunks):
if j == num_chunks - 1:
remainder = feat_len % chunk_size
chunk_lengths.append(chunk_size if remainder == 0 else remainder)
else:
chunk_lengths.append(chunk_size)
return chunk_counts, np.array(chunk_lengths, dtype=np.int32)
def _slice_feature_chunks(
self,
input_features: mx.array,
feature_lens: np.ndarray,
chunk_counts: np.ndarray,
chunk_size: int,
) -> List[mx.array]:
"""Cut features into chunks so conv/attention operate on windows."""
chunks: List[mx.array] = []
for feat, feat_len, num_chunks in zip(
input_features, feature_lens, chunk_counts
):
feat_len = int(feat_len)
num_chunks = int(num_chunks)
pos = 0
remainder = feat_len % chunk_size
for j in range(num_chunks):
clen = (
chunk_size if (j < num_chunks - 1 or remainder == 0) else remainder
)
chunks.append(feat[:, pos: pos + clen])
pos += clen
return chunks
def _pad_chunks(
self, chunks: List[mx.array], chunk_lengths: np.ndarray
) -> Tuple[mx.array, int]:
"""Pad for batching so convs run as a single dense tensor."""
max_chunk_len = int(chunk_lengths.max())
padded_chunks: List[mx.array] = []
for chunk, clen in zip(chunks, chunk_lengths):
clen = int(clen)
if clen < max_chunk_len:
chunk = mx.pad(chunk, [(0, 0), (0, max_chunk_len - clen)])
padded_chunks.append(chunk)
return mx.stack(padded_chunks, axis=0), max_chunk_len
def _build_cu_seqlens(
self, aftercnn_lens: np.ndarray, window_aftercnn: int
) -> List[int]:
"""Provide segment boundaries so attention stays inside windows."""
cu_chunk_lens = [0]
for cnn_len in aftercnn_lens:
cnn_len = int(cnn_len)
full_windows = cnn_len // window_aftercnn
if full_windows:
cu_chunk_lens.extend([window_aftercnn] * full_windows)
remainder = cnn_len % window_aftercnn
if remainder:
cu_chunk_lens.append(remainder)
return np.cumsum(cu_chunk_lens).tolist()
def __call__(
self,
input_features: mx.array,
feature_attention_mask: Optional[mx.array] = None,
) -> mx.array:
"""Encode audio features into sequence embeddings.
Flow:
- determine feature lengths from mask or input shape
- chunk along time, pad to a common chunk length
- run conv downsampling + projection + positional embeddings
- build block attention mask for chunked layout
- apply transformer layers + output projections
"""
if feature_attention_mask is not None:
feature_lens = feature_attention_mask.sum(axis=-1).astype(mx.int32)
else:
feature_lens = mx.array(
[input_features.shape[-1]] * input_features.shape[0], dtype=mx.int32
)
feature_lens_np = np.array(feature_lens)
aftercnn_lens = _get_feat_extract_output_lengths(feature_lens)
chunk_size = self.n_window * 2
chunk_counts, chunk_lengths = self._compute_chunk_layout(
feature_lens_np, chunk_size
)
chunks = self._slice_feature_chunks(
input_features, feature_lens_np, chunk_counts, chunk_size
)
padded_feature, _ = self._pad_chunks(chunks, chunk_lengths)
feature_lens_after_cnn = _get_feat_extract_output_lengths(
mx.array(chunk_lengths)
)
feature_lens_after_cnn_np = np.array(feature_lens_after_cnn)
max_len_after_cnn = int(feature_lens_after_cnn_np.max())
x = padded_feature[:, :, :, None]
x = nn.gelu(self.conv2d1(x))
x = nn.gelu(self.conv2d2(x))
x = nn.gelu(self.conv2d3(x))
b, f, t, c = x.shape
x = x.transpose(0, 2, 3, 1).reshape(b, t, c * f)
x = self.conv_out(x)
x = x + self.positional_embedding(x.shape[1])[None, :, :]
hidden_list = [
x[i, : int(feature_lens_after_cnn_np[i])] for i in range(x.shape[0])
]
hidden_states = mx.concatenate(hidden_list, axis=0)
aftercnn_lens_np = np.array(aftercnn_lens)
window_aftercnn = max_len_after_cnn * (
self.n_window_infer // (self.n_window * 2)
)
cu_seqlens = self._build_cu_seqlens(aftercnn_lens_np, window_aftercnn)
attention_mask = self._create_block_attention_mask(
hidden_states.shape[0], cu_seqlens, hidden_states.dtype
)
attention_mask = attention_mask[None, None, :, :]
hidden_states = hidden_states[None, :, :]
for layer in self.layers:
hidden_states = layer(hidden_states, mask=attention_mask)
hidden_states = self.ln_post(hidden_states[0])
hidden_states = nn.gelu(self.proj1(hidden_states))
return self.proj2(hidden_states)
class TextAttention(nn.Module):
"""Self-attention so text tokens can condition on prior context."""
def __init__(self, config: TextConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.num_heads = config.num_attention_heads
self.num_kv_heads = config.num_key_value_heads
self.head_dim = config.head_dim
self.scale = self.head_dim ** -0.5
self.q_proj = nn.Linear(
config.hidden_size, self.num_heads * self.head_dim, bias=False
)
self.k_proj = nn.Linear(
config.hidden_size, self.num_kv_heads * self.head_dim, bias=False
)
self.v_proj = nn.Linear(
config.hidden_size, self.num_kv_heads * self.head_dim, bias=False
)
self.o_proj = nn.Linear(
self.num_heads * self.head_dim, config.hidden_size, bias=False
)
self.q_norm = nn.RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.k_norm = nn.RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.rope = nn.RoPE(self.head_dim, traditional=False, base=config.rope_theta)
def __call__(
self, hidden_states: mx.array, cache: Optional[Any] = None
) -> mx.array:
B, L, _ = hidden_states.shape
queries = self.q_proj(hidden_states).reshape(
B, L, self.num_heads, self.head_dim
)
keys = self.k_proj(hidden_states).reshape(
B, L, self.num_kv_heads, self.head_dim
)
values = self.v_proj(hidden_states).reshape(
B, L, self.num_kv_heads, self.head_dim
)
queries = self.q_norm(queries).transpose(0, 2, 1, 3)
keys = self.k_norm(keys).transpose(0, 2, 1, 3)
values = values.transpose(0, 2, 1, 3)
offset = cache.offset if cache else 0
queries = self.rope(queries, offset=offset)
keys = self.rope(keys, offset=offset)
if cache:
keys, values = cache.update_and_fetch(keys, values)
mask = create_additive_causal_mask(queries.shape[2], offset=offset).astype(
queries.dtype
)
output = mx.fast.scaled_dot_product_attention(
queries, keys, values, scale=self.scale, mask=mask
)
return self.o_proj(
output.transpose(0, 2, 1, 3).reshape(B, -1, self.num_heads * self.head_dim)
)
class TextMLP(nn.Module):
"""Nonlinear mixing to expand and compress token features."""
def __init__(self, config: TextConfig):
super().__init__()
self.gate_proj = nn.Linear(
config.hidden_size, config.intermediate_size, bias=False
)
self.up_proj = nn.Linear(
config.hidden_size, config.intermediate_size, bias=False
)
self.down_proj = nn.Linear(
config.intermediate_size, config.hidden_size, bias=False
)
def __call__(self, x: mx.array) -> mx.array:
return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x))
class TextDecoderLayer(nn.Module):
"""Decoder block to refine tokens with attention + MLP."""
def __init__(self, config: TextConfig, layer_idx: int):
super().__init__()
self.self_attn = TextAttention(config, layer_idx)
self.mlp = TextMLP(config)
self.input_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = nn.RMSNorm(
config.hidden_size, eps=config.rms_norm_eps
)
def __call__(
self, hidden_states: mx.array, cache: Optional[Any] = None
) -> mx.array:
residual = hidden_states
hidden_states = self.self_attn(self.input_layernorm(hidden_states), cache=cache)
hidden_states = residual + hidden_states
return hidden_states + self.mlp(self.post_attention_layernorm(hidden_states))
class TextModel(nn.Module):
def __init__(self, config: TextConfig):
super().__init__()
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
self.layers = [
TextDecoderLayer(config, i) for i in range(config.num_hidden_layers)
]
self.norm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def __call__(
self,
input_ids: Optional[mx.array] = None,
inputs_embeds: Optional[mx.array] = None,
cache: Optional[List[Any]] = None,
) -> mx.array:
hidden_states = (
inputs_embeds if inputs_embeds is not None else self.embed_tokens(input_ids)
)
cache = cache or [None] * len(self.layers)
for i, layer in enumerate(self.layers):
hidden_states = layer(hidden_states, cache=cache[i])
return self.norm(hidden_states)
class Qwen3ASRModel(nn.Module):
def __init__(self, config: ModelConfig):
super().__init__()
self.config = config
self.audio_tower = AudioEncoder(config.audio_config)
self.model = TextModel(config.text_config)
self.lm_head = (
None
if config.text_config.tie_word_embeddings
else nn.Linear(
config.text_config.hidden_size,
config.text_config.vocab_size,
bias=False,
)
)
def get_audio_features(
self,
input_features: mx.array,
feature_attention_mask: Optional[mx.array] = None,
) -> mx.array:
return self.audio_tower(input_features, feature_attention_mask)
def __call__(
self,
input_ids: mx.array,
input_embeddings: Optional[mx.array] = None,
input_features: Optional[mx.array] = None,
feature_attention_mask: Optional[mx.array] = None,
cache: Optional[List[Any]] = None,
) -> mx.array:
inputs_embeds = (
input_embeddings
if input_embeddings is not None
else self.model.embed_tokens(input_ids)
)
if input_features is not None and (
cache is None or cache[0] is None or cache[0].offset == 0
):
audio_features = self.get_audio_features(
input_features, feature_attention_mask
).astype(inputs_embeds.dtype)
audio_token_mask = input_ids == self.config.audio_token_id
if audio_token_mask.any():
batch_size, seq_len, hidden_dim = inputs_embeds.shape
flat_mask_np = np.array(audio_token_mask.reshape(-1))
audio_indices = np.nonzero(flat_mask_np)[0]
if len(audio_indices) > 0 and audio_features.shape[0] > 0:
num_to_replace = min(len(audio_indices), audio_features.shape[0])
flat_embeds = inputs_embeds.reshape(-1, hidden_dim)
indices = mx.array(audio_indices[:num_to_replace])
replacement = (
mx.zeros_like(flat_embeds)
.at[indices]
.add(audio_features[:num_to_replace])
)
mask = (
mx.zeros((flat_embeds.shape[0],), dtype=flat_embeds.dtype)
.at[indices]
.add(1)
)
flat_embeds = mx.where(mask[:, None] > 0, replacement, flat_embeds)
inputs_embeds = flat_embeds.reshape(batch_size, seq_len, hidden_dim)
hidden_states = self.model(inputs_embeds=inputs_embeds, cache=cache)
return (
self.model.embed_tokens.as_linear(hidden_states)
if self.lm_head is None
else self.lm_head(hidden_states)
)
@property
def layers(self):
return self.model.layers
@property
def sample_rate(self) -> int:
return 16000
def make_cache(self) -> List[Any]:
from mlx_lm.models.cache import KVCache
return [KVCache() for _ in range(self.config.text_config.num_hidden_layers)]
@staticmethod
def sanitize(weights: Dict[str, mx.array]) -> Dict[str, mx.array]:
sanitized = {}
is_formatted = not any(k.startswith("thinker.") for k in weights.keys())
for k, v in weights.items():
if k.startswith("thinker."):
k = k[len("thinker."):]
if k == "lm_head.weight":
continue
if (
not is_formatted
and "conv2d" in k
and "weight" in k
and len(v.shape) == 4
):
v = v.transpose(0, 2, 3, 1)
sanitized[k] = v
return sanitized
# =============================================================================
# Model Loading
# =============================================================================
def load_qwen3_asr(
model_path: str,
) -> Tuple[Qwen3ASRModel, TokenizerLike, FeatureExtractorLike]:
"""Load aligned weights + preprocessing so inference stays consistent."""
import os
os.environ["TRANSFORMERS_VERBOSITY"] = "error"
import transformers
import logging
logging.getLogger("transformers").setLevel(logging.ERROR)
from transformers import AutoTokenizer, WhisperFeatureExtractor
# Ensure artifacts are local so loading is consistent and offline-ready.
local_path = Path(model_path)
if not local_path.exists():
local_path = Path(
snapshot_download(
model_path,
allow_patterns=["*.json", "*.safetensors", "*.model", "*.txt"],
)
)
# Config drives architecture/quantization; keep as source of truth.
with open(local_path / "config.json", encoding="utf-8") as f:
config_dict = json.load(f)
# Support configs that wrap audio/text settings.
if "thinker_config" in config_dict:
thinker = config_dict["thinker_config"]
config_dict["audio_config"] = thinker.get("audio_config", {})
config_dict["text_config"] = thinker.get("text_config", {})
config_dict["audio_token_id"] = thinker.get("audio_token_id", 151676)
config = ModelConfig(
audio_config=config_dict.get("audio_config"),
text_config=config_dict.get("text_config"),
audio_token_id=config_dict.get("audio_token_id", 151676),
support_languages=config_dict.get("support_languages", []),
)
# Instantiate structure before loading weights.
model = Qwen3ASRModel(config)
# Load all shards before sanitizing for layout differences.
weight_files = glob.glob(str(local_path / "*.safetensors"))
weights = {}
for wf in weight_files:
weights.update(mx.load(wf))
weights = Qwen3ASRModel.sanitize(weights)
# Respect model-provided quantization to match weights.
quantization = config_dict.get("quantization")
if quantization:
def class_predicate(p, m):
if not hasattr(m, "to_quantized"):
return False
if hasattr(m, "weight") and m.weight.size % 64 != 0:
return False
if p.startswith("audio_tower"):
return False
return f"{p}.scales" in weights
nn.quantize(
model,
group_size=quantization["group_size"],
bits=quantization["bits"],
class_predicate=class_predicate,
)
model.load_weights(list(weights.items()), strict=False)
mx.eval(model.parameters())
model.eval()
# Match preprocessing to the model artifacts.
prev_verbosity = transformers.logging.get_verbosity()
transformers.logging.set_verbosity_error()
try:
tokenizer = AutoTokenizer.from_pretrained(
str(local_path), trust_remote_code=True
)
feature_extractor = WhisperFeatureExtractor.from_pretrained(str(local_path))
finally:
transformers.logging.set_verbosity(prev_verbosity)
return model, tokenizer, feature_extractor
# =============================================================================
# Transcription
# =============================================================================
def transcribe(
model: Qwen3ASRModel,
tokenizer: TokenizerLike,
feature_extractor: FeatureExtractorLike,
audio: np.ndarray,
language: str = "English",
max_tokens: int = 8192,
) -> Generator[str, None, None]:
"""Stream tokens to keep transcription latency low."""
from mlx_lm.generate import generate_step
# Match the model's expected feature pipeline.
audio_inputs = feature_extractor(
audio,
sampling_rate=16000,
return_attention_mask=True,
truncation=False,
padding=True,
return_tensors="np",
)
input_features = mx.array(audio_inputs["input_features"])
feature_attention_mask = mx.array(audio_inputs["attention_mask"])
# Needed to size the audio pad tokens in the prompt.
audio_lengths = feature_attention_mask.sum(axis=-1)
aftercnn_lens = _get_feat_extract_output_lengths(audio_lengths)
num_audio_tokens = int(aftercnn_lens[0].item())
# Qwen3-ASR expects audio pads inside the chat template.
supported = model.config.support_languages or []
supported_lower = {lang.lower(): lang for lang in supported}
lang_name = supported_lower.get(language.lower(), language)
prompt = (
f"<|im_start|>system\n<|im_end|>\n"
f"<|im_start|>user\n<|audio_start|>{'<|audio_pad|>' * num_audio_tokens}<|audio_end|><|im_end|>\n"
f"<|im_start|>assistant\nlanguage {lang_name}<asr_text>"
)
input_ids = mx.array(tokenizer.encode(prompt, return_tensors="np"))
# Compute audio features once for embedding replacement.
audio_features = model.get_audio_features(input_features, feature_attention_mask)
mx.eval(audio_features)
# Replace audio token embeddings with audio features.
inputs_embeds = model.model.embed_tokens(input_ids)
audio_features = audio_features.astype(inputs_embeds.dtype)
audio_token_mask = input_ids == model.config.audio_token_id
if audio_token_mask.any():
batch_size, seq_len, hidden_dim = inputs_embeds.shape
flat_mask_np = np.array(audio_token_mask.reshape(-1))
audio_indices = np.nonzero(flat_mask_np)[0]
if len(audio_indices) > 0:
num_to_replace = min(len(audio_indices), audio_features.shape[0])
flat_embeds = inputs_embeds.reshape(-1, hidden_dim)
indices = mx.array(audio_indices[:num_to_replace])
replacement = (
mx.zeros_like(flat_embeds)
.at[indices]
.add(audio_features[:num_to_replace])
)
mask = (
mx.zeros((flat_embeds.shape[0],), dtype=flat_embeds.dtype)
.at[indices]
.add(1)
)
flat_embeds = mx.where(mask[:, None] > 0, replacement, flat_embeds)
inputs_embeds = flat_embeds.reshape(batch_size, seq_len, hidden_dim)
mx.eval(inputs_embeds)
input_embeddings = inputs_embeds[0]
prompt_ids = input_ids[0] if input_ids.ndim > 1 else input_ids
eos_token_ids = [151645, 151643]
for token, _ in generate_step(
prompt=prompt_ids,
input_embeddings=input_embeddings,
model=model,
max_tokens=max_tokens,
):
if token in eos_token_ids:
break
yield tokenizer.decode([int(token)])
# =============================================================================
# Real-time Transcriber
# =============================================================================
INTENT_EXPLAIN_PROMPT = """Analyze this speech and respond with exactly 3 lines:
INTENT: <primary intent in 2-3 words>
ENTITIES: <key items or names, comma-separated, or "none">
ACTION: <what should happen next, one short sentence>
Speech: "{text}" /no_think"""
class RealtimeTranscriber:
"""Encapsulates the async pipeline so capture, VAD, and ASR stay coordinated."""
def __init__(
self,
model_path: str = DEFAULT_ASR_MODEL,
language: str = DEFAULT_LANGUAGE,
transcribe_interval: float = DEFAULT_TRANSCRIBE_INTERVAL,
vad_frame_ms: int = DEFAULT_VAD_FRAME_MS,
vad_mode: int = DEFAULT_VAD_MODE,
vad_silence_ms: int = DEFAULT_VAD_SILENCE_MS,
min_words: int = DEFAULT_MIN_WORDS,
analyze: bool = False,
llm_model: Optional[str] = None,
device: Optional[int] = None,
no_ui: bool = False,