Reza2kn commited on
Commit
39cc6cd
Β·
verified Β·
1 Parent(s): 4746d89

LiteRT dynamic_int4 block32 Qwen3-ASR-1.7B

Browse files
Files changed (1) hide show
  1. README.md +217 -0
README.md ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ - zh
6
+ - ja
7
+ - ko
8
+ - multilingual
9
+ library_name: ai-edge-litert
10
+ tags:
11
+ - litert
12
+ - ai-edge-litert
13
+ - litert-torch
14
+ - tflite
15
+ - quantized
16
+ - dynamic-int4
17
+ - block32
18
+ - qwen3
19
+ - qwen3-asr
20
+ - mega-asr
21
+ - automatic-speech-recognition
22
+ - asr
23
+ - speech-recognition
24
+ - robust-asr
25
+ - android
26
+ - mobile
27
+ - edge
28
+ base_model: zhifeixie/Mega-ASR
29
+ base_model_relation: quantized
30
+ ---
31
+
32
+ # Mega-ASR β€” LiteRT (TFLite) dynamic INT4, block 32
33
+
34
+ [LiteRT](https://ai.google.dev/edge/litert) (formerly TFLite) deployment of
35
+ the LLM portion of [zhifeixie/Mega-ASR](https://huggingface.co/zhifeixie/Mega-ASR),
36
+ converted via [`litert-torch`](https://github.com/google-ai-edge/litert-torch)
37
+ (formerly `ai-edge-torch`) with the `dynamic_int4` recipe at block size 32.
38
+
39
+ **Targets Android, ChromeOS, embedded Linux, and any LiteRT runtime.**
40
+ Apple platforms get better results from the CoreML variant; NVIDIA GPUs get
41
+ better results from NVFP4 β€” this artifact exists for the LiteRT ecosystem.
42
+
43
+ ## What's in this repo
44
+
45
+ | File | Size | Role |
46
+ | --- | ---: | --- |
47
+ | `litert/mega-asr-llm_embeds_q4_block32_ekv1024.tflite` | **975 MB** | Main ASR artifact. Takes pre-computed `inputs_embeds` (audio embeds scattered at `<\|audio_pad\|>` positions). Signatures: `prefill_512` + `decode`. KV cache external, max length 1024. |
48
+ | `litert/mega-asr-llm_q4_block32_ekv512.tflite` | 972 MB | Pure-text Qwen3-1.7B variant. Takes int32 token IDs; embed_tokens baked into the graph. Use this for LiteRT-LM bundling or pure-text Qwen3 inference. **Not directly usable for ASR** β€” the audio path needs external embedding scatter. |
49
+ | `onnx/audio_encoder_fp32.onnx` | 1.27 GB | 24-layer Whisper-style audio encoder (ONNX fp32, runs via onnxruntime; LiteRT port not done β€” its op coverage gap on the audio encoder is wider than the LLM and the runtime savings are marginal). |
50
+ | `tokenizer/*` | β€” | Qwen3-ASR tokenizer (`<\|audio_pad\|>`, `<asr_text>`, …) |
51
+ | `examples/*.wav` | ~3 MB | 8 noisy benchmark clips from Voices-in-the-Wild-Bench |
52
+ | `litert_convert_embeds.py` | β€” | The conversion script (litert-torch + dynamic_int4 block 32) |
53
+ | `inference_bench.py` | β€” | End-to-end ASR pipeline + 8-clip VITW bench (used to produce the numbers below) |
54
+
55
+ ## Quality (bench)
56
+
57
+ 8-clip [Voices-in-the-Wild-Bench](https://github.com/xzf-thu/Voices-in-the-Wild-Bench)
58
+ agreement (1 βˆ’ WER), prompt forced to `language English`, run on the same ONNX
59
+ fp32 audio encoder as the other backends. LiteRT runtime via XNNPACK delegate
60
+ (CPU on stallion x86_64 β€” Android/ARM would run the same .tflite via the same
61
+ delegate at lower latency-per-watt):
62
+
63
+ | Per-sample | LiteRT (this repo) | ONNX GPTQ | MLX 8/4 | CoreML 8/4 | NVFP4 |
64
+ | --- | ---: | ---: | ---: | ---: | ---: |
65
+ | distortion | 100% | 100% | 100% | 100% | 100% |
66
+ | dropout | 100% | 100% | 100% | 100% | 100% |
67
+ | echo (hard, reverb) | 58.8% | 82.4% | 64.7% | 64.7% | 64.7% |
68
+ | far_field | 100% | 100% | 100% | 100% | 100% |
69
+ | mixed | 100% | 100% | 100% | 100% | 100% |
70
+ | noise | 100% | 100% | 100% | 100% | 100% |
71
+ | obstructed | 94.1% | 100% | 94.1% | 100% | 100% |
72
+ | recording (hard, truncated) | 33.3% | 60.0% | 60.0% | 60.0% | **66.7%** |
73
+ | **AVERAGE** | **85.8%** | **92.7%** | **92.2%** | **90.6%** | **91.4%** |
74
+
75
+ LiteRT lands ~5-7 pts behind the other 4-bit backends, with both losses
76
+ concentrated on the two hard clips:
77
+
78
+ - `recording` (truncated audio): 33.3% β€” the dynamic-range INT4 quantization
79
+ with no calibration is the harshest setting here, and the truncated-audio
80
+ decode pattern (where context-aware confidence really matters) is the most
81
+ sensitive to weight precision loss. AWQ-style activation-aware scaling
82
+ (NVFP4) or per-column GPTQ (ONNX) recover ~25-30 pts on this clip; pure
83
+ dynamic-range quant doesn't have the headroom.
84
+ - `echo` (heavy reverb): 58.8% β€” same pattern, smaller gap (~6 pts vs MLX/CoreML).
85
+
86
+ The clean clips are all 100% β€” the quantization is fine for the easy cases;
87
+ it's the hard cases where the activation/weight precision interaction kicks in.
88
+
89
+ ## How LiteRT dynamic INT4 block 32 works (quick)
90
+
91
+ - Weights are stored as **INT4 symmetric**, one scale per **block of 32**
92
+ consecutive elements along the input dimension (so a Linear layer with
93
+ in_features=2048 has 64 scales per output row).
94
+ - Scales are **FP32** (no second-level FP8 like NVFP4; LiteRT's runtime
95
+ uses XNNPACK's INT4 GEMM kernel, which expects FP32 block scales).
96
+ - At inference, the XNNPACK delegate dequantizes blocks on-the-fly into
97
+ FP32 / FP16 (depending on accumulator) and runs the GEMM. No native INT4
98
+ tensor cores on commodity Android SoCs β€” the win is **memory bandwidth**
99
+ (4 bits/weight + tiny scale overhead vs 16 bits/weight).
100
+
101
+ "Dynamic" means activations stay FP32; only the weights are quantized. This
102
+ trades some quality for simplicity (no calibration needed) and ops coverage
103
+ (every Linear op the LiteRT runtime knows can take INT4 weights, no special
104
+ calibrated activation observers required).
105
+
106
+ ## Inference
107
+
108
+ ```bash
109
+ pip install ai-edge-litert onnxruntime transformers safetensors soundfile librosa numpy
110
+ git clone https://huggingface.co/Reza2kn/mega-asr-litert
111
+ cd mega-asr-litert
112
+ python inference_bench.py \
113
+ --tflite litert/mega-asr-llm_embeds_q4_block32_ekv1024.tflite \
114
+ --encoder onnx/audio_encoder_fp32.onnx \
115
+ --examples-dir examples
116
+ ```
117
+
118
+ The bench script runs the full ASR pipeline:
119
+
120
+ 1. Audio file β†’ mel-spectrogram (`AutoFeatureExtractor`).
121
+ 2. mel β†’ ONNX audio encoder β†’ audio embeddings of shape `(T_audio, 2048)`.
122
+ 3. Build prompt with `<|audio_pad|>` expanded to `T_audio` positions; tokenize
123
+ the chat-style prefix.
124
+ 4. Look up text token embeddings from the `embed_tokens` weight in the
125
+ accompanying safetensors (this is the embedding layer that's **not** baked
126
+ into the inputs_embeds variant β€” by design).
127
+ 5. Scatter audio embeds at the `<|audio_pad|>` positions in the embed sequence.
128
+ 6. Pad to 512 and call the `prefill_512` signature; KV cache is external
129
+ (28 layers Γ— 2 K/V Γ— float32, shape `(1, 1024, 8, 128)`).
130
+ 7. Greedy decode loop on the `decode` signature until EOS (`151645`).
131
+
132
+ ## Conversion details
133
+
134
+ ```python
135
+ from litert_torch._convert import interface as converter_utils
136
+ from litert_torch.generative.examples.qwen import qwen3
137
+ from litert_torch.generative.layers import kv_cache as kv_utils
138
+ from litert_torch.generative.quantize import quant_attrs, quant_recipes
139
+
140
+ model = qwen3.build_1_7b_model(
141
+ checkpoint_path="Mega-ASR-LLM/", # safetensors of the merged LLM portion
142
+ mask_cache_size=1024,
143
+ )
144
+
145
+ class EmbedsForward(torch.nn.Module):
146
+ """Bypass tok_embedding β€” public forward takes inputs_embeds instead of tokens."""
147
+ def __init__(self, inner):
148
+ super().__init__()
149
+ self.m, self.cfg = inner, inner.config
150
+ def forward(self, inputs_embeds, input_pos, kv_cache):
151
+ attn = self.cfg.block_config(0).attn_config
152
+ n_elem = int(attn.rotary_percentage * attn.head_dim)
153
+ rope = self.cfg.build_rope(input_pos, n_elem, attn.rotary_base)
154
+ mask = self.m.mask_cache.index_select(2, input_pos)
155
+ mask = mask[:, :, :, :kv_cache.get_max_seq_len()]
156
+ return self.m._forward_with_embeds(
157
+ inputs_embeds, rope, mask, input_pos, kv_cache, None, None
158
+ )
159
+
160
+ wrapper = EmbedsForward(model).eval()
161
+ qcfg = quant_recipes.full_dynamic_recipe(
162
+ mcfg=model.config,
163
+ weight_dtype=quant_attrs.Dtype.INT4,
164
+ granularity=quant_attrs.Granularity.BLOCKWISE_32,
165
+ )
166
+
167
+ converter = converter_utils.Converter()
168
+ converter.add_signature("prefill_512", wrapper, sample_kwargs={
169
+ "inputs_embeds": torch.zeros(1, 512, 2048), "input_pos": torch.arange(512, dtype=torch.int),
170
+ "kv_cache": kv_utils.KVCache.from_model_config(1024, model.config),
171
+ })
172
+ converter.add_signature("decode", wrapper, sample_kwargs={
173
+ "inputs_embeds": torch.zeros(1, 1, 2048), "input_pos": torch.tensor([0], dtype=torch.int),
174
+ "kv_cache": kv_utils.KVCache.from_model_config(1024, model.config),
175
+ })
176
+ litert_model = converter.convert(quant_config=qcfg)
177
+ litert_model.export("mega-asr-llm_embeds_q4_block32_ekv1024.tflite")
178
+ ```
179
+
180
+ Conversion takes ~2 minutes on an x86 box but requires ~30 GB RAM peak (we
181
+ added 24 GB swap on top of the host's 32 GB physical RAM to survive the
182
+ "Write Model to Bytes" step β€” the intermediate fp32 model size is ~6.4 GB
183
+ and the flatbuffer writer needs ~3-4Γ— that in headroom).
184
+
185
+ ## Why two .tflite files?
186
+
187
+ The default `litert-torch` `convert_v3_to_tflite` script produces a tflite
188
+ whose `prefill` signature takes int32 **token IDs** β€” `embed_tokens` lives
189
+ inside the graph. That's fine for pure text generation (and is what LiteRT-LM
190
+ expects). But ASR needs to inject **audio embeddings** at the `<|audio_pad|>`
191
+ positions **before** the LLM, which requires bypassing the internal embed
192
+ layer.
193
+
194
+ So we ship both:
195
+
196
+ - `mega-asr-llm_embeds_q4_block32_ekv1024.tflite` β€” the ASR artifact. Takes
197
+ pre-computed `inputs_embeds` (float32, shape `(1, 512, 2048)` for prefill,
198
+ `(1, 1, 2048)` for decode). The bench above runs against this file.
199
+ - `mega-asr-llm_q4_block32_ekv512.tflite` β€” the pure-text artifact. Same
200
+ Mega-ASR LLM weights, same INT4 quantization, but takes int32 token IDs.
201
+ Use this if you want to drop the LLM into a LiteRT-LM bundle or run
202
+ Qwen3-style chat generation without the audio encoder.
203
+
204
+ ## Companion repos
205
+
206
+ - [Reza2kn/mega-asr-onnx](https://huggingface.co/Reza2kn/mega-asr-onnx) β€” full ONNX pipeline (GPTQ-INT4, 92.7%)
207
+ - [Reza2kn/mega-asr-mlx](https://huggingface.co/Reza2kn/mega-asr-mlx) β€” MLX 4-bit (mixed 8/4, 92.2%)
208
+ - [Reza2kn/mega-asr-nvfp4](https://huggingface.co/Reza2kn/mega-asr-nvfp4) β€” NVFP4 AWQ-Lite (Blackwell, 91.4%)
209
+ - [Reza2kn/mega-asr-coreml](https://huggingface.co/Reza2kn/mega-asr-coreml) β€” CoreML 4-bit (mixed 8/4, 90.6%)
210
+ - [Reza2kn/mega-asr-bench](https://huggingface.co/spaces/Reza2kn/mega-asr-bench) β€” browser demo (WebGPU)
211
+
212
+ ## Credits
213
+
214
+ - Original model: [zhifeixie/Mega-ASR](https://huggingface.co/zhifeixie/Mega-ASR) (1.7B, Apache-2.0)
215
+ - Conversion: [google-ai-edge/litert-torch](https://github.com/google-ai-edge/litert-torch) v0.6 (`dynamic_int4` block 32)
216
+ - Runtime: [ai-edge-litert](https://pypi.org/project/ai-edge-litert/)
217
+ - Benchmark: [Voices-in-the-Wild-Bench](https://github.com/xzf-thu/Voices-in-the-Wild-Bench)