Kearm commited on
Commit
764e76e
·
verified ·
1 Parent(s): 04e43d3

Move quantization tooling to GitHub

Browse files

Code authority: https://github.com/RESMP-DEV/mimo-asr-fp8

Files changed (3) hide show
  1. README.md +3 -1
  2. quantize_fp8.py +0 -294
  3. quantize_fp8_stream.py +0 -121
README.md CHANGED
@@ -46,7 +46,9 @@ hf download XiaomiMiMo/MiMo-Audio-Tokenizer --local-dir ./models/MiMo-Audio-Toke
46
  hf download Infatoshi/MiMo-V2.5-ASR-FP8 --local-dir ./MiMo-V2.5-ASR-FP8
47
  ```
48
 
49
- Then load with the `FP8Linear` loader (`quantize_fp8.py`, included here as `quantize_fp8.py`):
 
 
50
 
51
  ```python
52
  from quantize_fp8 import load_fp8_model
 
46
  hf download Infatoshi/MiMo-V2.5-ASR-FP8 --local-dir ./MiMo-V2.5-ASR-FP8
47
  ```
48
 
49
+ Then install the maintained loader from
50
+ [`RESMP-DEV/mimo-asr-fp8`](https://github.com/RESMP-DEV/mimo-asr-fp8) and load
51
+ with its `FP8Linear` implementation:
52
 
53
  ```python
54
  from quantize_fp8 import load_fp8_model
quantize_fp8.py DELETED
@@ -1,294 +0,0 @@
1
- """
2
- MiMo-V2.5-ASR -> FP8 e4m3fn (per-channel weight quant, dynamic activation quant)
3
-
4
- Quantize entrypoint loads MiMoAudioForCausalLM directly (no audio tokenizer / no
5
- flash-attn needed -- the LLM is pure Qwen2). Verify/load paths still go through the
6
- full MimoAudio stack and DO require flash-attn + the audio tokenizer.
7
- """
8
-
9
- import os
10
- import sys
11
- import json
12
- import shutil
13
- import argparse
14
- from pathlib import Path
15
-
16
- import torch
17
- import torch.nn as nn
18
- from safetensors.torch import save_file, safe_open
19
-
20
- REPO_ROOT = Path(__file__).resolve().parent
21
- if str(REPO_ROOT) not in sys.path:
22
- sys.path.insert(0, str(REPO_ROOT))
23
-
24
- # ----- constants -----
25
- FP8_DTYPE = torch.float8_e4m3fn
26
- FP8_MAX = torch.finfo(FP8_DTYPE).max # 448.0
27
- SCALE_DTYPE = torch.float32
28
- SKIP_TYPES = (nn.Embedding, nn.LayerNorm, nn.GroupNorm,
29
- nn.BatchNorm1d, nn.BatchNorm2d, nn.RMSNorm)
30
-
31
- CONFIG_FILES = [
32
- "config.json", "tokenizer_config.json", "tokenizer.json",
33
- "special_tokens_map.json", "generation_config.json",
34
- "added_tokens.json", "merges.txt", "vocab.json", "chat_template.jinja",
35
- ]
36
-
37
- SPECIAL_TOKENS = ["<|sosp|>", "<|eosp|>", "<|empty|>", "<|Human|>",
38
- "<|SpeechLM|>", "<|sostm|>", "<|eostm|>", "<|eot|>"]
39
-
40
-
41
- # ----- weight quantization -----
42
- def quantize_weight_per_channel(weight: torch.Tensor):
43
- """Per output-channel absmax scaling. weight: [out, in]"""
44
- w = weight.float()
45
- amax = w.abs().amax(dim=1, keepdim=True).clamp(min=1e-12)
46
- scale = (amax / FP8_MAX).to(SCALE_DTYPE)
47
- w_fp8 = (w / scale).clamp(-FP8_MAX, FP8_MAX).to(FP8_DTYPE)
48
- return w_fp8, scale
49
-
50
-
51
- class FP8Linear(nn.Module):
52
- """FP8 e4m3fn weights + per-channel scales; dynamic per-tensor activation quant."""
53
-
54
- def __init__(self, linear: nn.Linear):
55
- super().__init__()
56
- with torch.no_grad():
57
- w_fp8, w_scale = quantize_weight_per_channel(linear.weight)
58
- self.register_buffer("weight_fp8", w_fp8.contiguous()) # [out, in]
59
- self.register_buffer("weight_scale", w_scale.squeeze(1)) # [out]
60
- if linear.bias is not None:
61
- self.register_buffer("bias", linear.bias.detach().clone())
62
- else:
63
- self.bias = None
64
- self.in_features = linear.in_features
65
- self.out_features = linear.out_features
66
-
67
- def forward(self, x: torch.Tensor) -> torch.Tensor:
68
- leading = x.shape[:-1]
69
- x2d = x.reshape(-1, self.in_features)
70
- x_scale = (x2d.float().abs().max().clamp(min=1e-12) / FP8_MAX).to(SCALE_DTYPE)
71
- x_fp8 = (x2d.float() / x_scale).clamp(-FP8_MAX, FP8_MAX).to(FP8_DTYPE)
72
- w_scale_scalar = self.weight_scale.max().to(SCALE_DTYPE)
73
- out = torch._scaled_mm(
74
- x_fp8, self.weight_fp8.t(),
75
- scale_a=x_scale, scale_b=w_scale_scalar,
76
- out_dtype=torch.bfloat16, use_fast_accum=True,
77
- )
78
- correction = (self.weight_scale / w_scale_scalar).to(torch.bfloat16)
79
- out = out * correction.unsqueeze(0)
80
- if self.bias is not None:
81
- out = out + self.bias.to(out.dtype)
82
- return out.reshape(*leading, self.out_features)
83
-
84
- def extra_repr(self):
85
- return f"in={self.in_features}, out={self.out_features}, fp8=e4m3fn"
86
-
87
-
88
- # ----- model walk -----
89
- def quantize_model(model: nn.Module, verbose: bool = True):
90
- stats = {"converted": 0, "skipped": 0, "bytes_before": 0, "bytes_after": 0}
91
-
92
- def _walk(parent, prefix=""):
93
- for name, module in list(parent.named_children()):
94
- full = f"{prefix}.{name}" if prefix else name
95
- if isinstance(module, nn.Linear) and not isinstance(module, SKIP_TYPES):
96
- b_before = module.weight.numel() * module.weight.element_size()
97
- if module.bias is not None:
98
- b_before += module.bias.numel() * module.bias.element_size()
99
- fp8mod = FP8Linear(module)
100
- b_after = fp8mod.weight_fp8.numel() + fp8mod.weight_scale.numel() * 4
101
- if fp8mod.bias is not None:
102
- b_after += fp8mod.bias.numel() * fp8mod.bias.element_size()
103
- setattr(parent, name, fp8mod)
104
- stats["converted"] += 1
105
- stats["bytes_before"] += b_before
106
- stats["bytes_after"] += b_after
107
- if verbose:
108
- print(f" [FP8] {full:<70} {b_before/max(b_after,1):.1f}x")
109
- elif isinstance(module, SKIP_TYPES):
110
- stats["skipped"] += 1
111
- else:
112
- _walk(module, full)
113
-
114
- _walk(model)
115
- return model, stats
116
-
117
-
118
- # ----- save -----
119
- def save_fp8(model, out_dir: Path, stats: dict, model_path: Path):
120
- out_dir.mkdir(parents=True, exist_ok=True)
121
- state = {k: v.contiguous().cpu() for k, v in model.state_dict().items()}
122
- st_path = out_dir / "model.safetensors"
123
- save_file(state, str(st_path), metadata={"format": "pt"})
124
-
125
- copied = []
126
- for cfg in CONFIG_FILES:
127
- src = model_path / cfg
128
- if src.exists():
129
- shutil.copy2(src, out_dir / cfg)
130
- copied.append(cfg)
131
- if copied:
132
- print(f" Copied config: {', '.join(copied)}")
133
-
134
- gb_before = stats["bytes_before"] / 1e9
135
- gb_after = stats["bytes_after"] / 1e9
136
- ratio = round(stats["bytes_before"] / max(stats["bytes_after"], 1), 3)
137
- meta = {
138
- "dtype": "float8_e4m3fn", "weight_scaling": "per_channel_absmax",
139
- "activation_scaling": "dynamic_per_tensor", "matmul_op": "torch._scaled_mm",
140
- "output_dtype": "bfloat16", "converted_layers": stats["converted"],
141
- "skipped_layers": stats["skipped"], "weight_gb_before": round(gb_before, 3),
142
- "weight_gb_after": round(gb_after, 3), "compression_ratio": ratio,
143
- }
144
- with open(out_dir / "fp8_meta.json", "w") as f:
145
- json.dump(meta, f, indent=2)
146
-
147
- actual_gb = st_path.stat().st_size / 1e9
148
- print(f"\nOK {st_path} ({actual_gb:.2f} GB on disk)")
149
- print(f" weight bytes: {gb_before:.2f} GB -> {gb_after:.2f} GB ({ratio}x)")
150
- print(f" {stats['converted']} layers converted, {stats['skipped']} skipped")
151
-
152
-
153
- def _build_args_and_tokenizer(model_path: str):
154
- from transformers import AutoTokenizer
155
- from src.mimo_audio.modeling_mimo_audio import MiMoAudioArguments
156
- tok = AutoTokenizer.from_pretrained(model_path)
157
- for t in SPECIAL_TOKENS:
158
- if t not in tok.get_vocab():
159
- tok.add_tokens([t], special_tokens=True)
160
- gid = lambda t: tok.convert_tokens_to_ids(t)
161
- args = MiMoAudioArguments(
162
- model_name_or_path=model_path,
163
- sosp_idx=gid("<|sosp|>"), eosp_idx=gid("<|eosp|>"),
164
- empty_idx=gid("<|empty|>"), sostm_idx=gid("<|sostm|>"),
165
- eostm_idx=gid("<|eostm|>"), eot_idx=gid("<|eot|>"),
166
- )
167
- return args, tok
168
-
169
-
170
- # ----- quantize entrypoint (direct LLM load, no audio tokenizer / flash-attn) -----
171
- def run_quantize(args):
172
- from src.mimo_audio.modeling_mimo_audio import MiMoAudioForCausalLM
173
-
174
- print(f"Loading MiMoAudioForCausalLM from {args.model_path} on {args.device} ...")
175
- model_args, _ = _build_args_and_tokenizer(args.model_path)
176
- model = MiMoAudioForCausalLM.from_pretrained(
177
- args.model_path,
178
- args=model_args,
179
- torch_dtype=torch.bfloat16,
180
- device_map={"": args.device},
181
- attn_implementation="sdpa",
182
- )
183
- model.eval()
184
- print("OK loaded\n")
185
-
186
- print("Quantizing to FP8 e4m3fn ...")
187
- with torch.no_grad():
188
- model, stats = quantize_model(model, verbose=not args.quiet)
189
- save_fp8(model, Path(args.out_dir), stats, Path(args.model_path))
190
- print("\nDone.")
191
-
192
-
193
- # ----- load FP8 model (for inference / verify) -----
194
- def load_fp8_model(fp8_dir: str, tokenizer_path: str, repo_root: str, device: str = "cuda"):
195
- """
196
- Load the FP8 checkpoint for inference, returning a MimoAudio wrapper exposing .asr_sft().
197
-
198
- Strategy: instantiate the real architecture via from_pretrained on the ORIGINAL repo
199
- weights is NOT required -- instead we build the bf16 architecture from config (correct
200
- rotary init), replace Linears with FP8Linear shells, then load the FP8 state dict.
201
-
202
- repo_root must be the cloned MiMo-V2.5-ASR repo (contains src/).
203
- fp8_dir must contain model.safetensors + config/tokenizer files.
204
- """
205
- rr = Path(repo_root).resolve()
206
- if str(rr) not in sys.path:
207
- sys.path.insert(0, str(rr))
208
-
209
- from src.mimo_audio.mimo_audio import MimoAudio
210
- from src.mimo_audio.modeling_mimo_audio import MiMoAudioForCausalLM
211
- from src.mimo_audio_tokenizer import MiMoAudioTokenizer
212
- from transformers import AutoTokenizer, AutoConfig, GenerationConfig
213
-
214
- fp8_dir = Path(fp8_dir)
215
- model_args, tokenizer = _build_args_and_tokenizer(str(fp8_dir))
216
-
217
- # Build architecture with real init (correct rotary inv_freq), no pretrained shards.
218
- print("Building architecture (config init) ...")
219
- cfg = AutoConfig.from_pretrained(str(fp8_dir))
220
- model = MiMoAudioForCausalLM(cfg, model_args).to(torch.bfloat16)
221
-
222
- print("Installing FP8 modules ...")
223
- with torch.no_grad():
224
- quantize_model(model, verbose=False)
225
- model = model.to(device)
226
-
227
- print("Loading FP8 weights ...")
228
- state = {}
229
- with safe_open(str(fp8_dir / "model.safetensors"), framework="pt", device=device) as f:
230
- for key in f.keys():
231
- state[key] = f.get_tensor(key)
232
- model.load_state_dict(state, strict=True)
233
- model.eval()
234
-
235
- # Wrap in MimoAudio without re-running its __init__ (which would reload weights).
236
- mimo = object.__new__(MimoAudio)
237
- mimo.device = device
238
- mimo.path = str(fp8_dir)
239
- mimo.mimo_audio_tokenizer_path = tokenizer_path
240
- mimo.tokenizer = tokenizer
241
- mimo.padding_idx = int(tokenizer.pad_token_id)
242
- mimo.sosp_idx = model_args.sosp_idx
243
- mimo.eosp_idx = model_args.eosp_idx
244
- mimo.empty_token = model_args.empty_idx
245
- mimo.sostm_idx = model_args.sostm_idx
246
- mimo.eostm_idx = model_args.eostm_idx
247
- mimo.eot_idx = model_args.eot_idx
248
- mimo.im_start_idx = tokenizer.convert_tokens_to_ids("<|im_start|>")
249
- mimo.im_end_idx = tokenizer.convert_tokens_to_ids("<|im_end|>")
250
- mimo.model = model
251
- mimo.group_size = model.config.group_size
252
- mimo.audio_channels = model.config.audio_channels
253
- mimo.delay_pattern = model.config.delay_pattern
254
- mimo.vocab_size = model.config.vocab_size
255
- mimo.speech_zeroemb_idx = model.speech_empty_ids
256
-
257
- from src.mimo_audio.modeling_mimo_audio import MiMoSampler
258
- mimo.default_global_sampler = MiMoSampler(do_sample=True, temperature=0.6, top_k=50, top_p=0.95)
259
- mimo.default_local_sampler = MiMoSampler(do_sample=True, temperature=0.9, top_k=50, top_p=0.95)
260
- mimo.task_sampler_configs = {
261
- "asr": {"global": MiMoSampler(do_sample=False, temperature=1.0, top_p=1.0),
262
- "local": MiMoSampler(do_sample=True, temperature=0.9, top_p=0.95)},
263
- }
264
- mimo.generate_kwargs = {
265
- "max_length": 8192,
266
- "eos_token_id": tokenizer.eos_token_id,
267
- "pad_token_id": tokenizer.pad_token_id,
268
- }
269
-
270
- mimo.mimo_audio_tokenizer = MiMoAudioTokenizer.from_pretrained(tokenizer_path)
271
- mimo.mimo_audio_tokenizer.eval().bfloat16().to(device)
272
- from torchaudio.transforms import MelSpectrogram
273
- tcfg = mimo.mimo_audio_tokenizer.config
274
- mimo.mel_transform = MelSpectrogram(
275
- sample_rate=tcfg.sampling_rate, n_fft=tcfg.nfft, hop_length=tcfg.hop_length,
276
- win_length=tcfg.window_size, f_min=tcfg.fmin, f_max=tcfg.fmax,
277
- n_mels=tcfg.n_mels, power=1.0, center=True,
278
- ).to(device)
279
- print("FP8 model ready\n")
280
- return mimo
281
-
282
-
283
- def main():
284
- ap = argparse.ArgumentParser()
285
- ap.add_argument("--model-path", required=True)
286
- ap.add_argument("--out-dir", default="./MiMo-V2.5-ASR-FP8")
287
- ap.add_argument("--device", default="cuda")
288
- ap.add_argument("--quiet", action="store_true")
289
- args = ap.parse_args()
290
- run_quantize(args)
291
-
292
-
293
- if __name__ == "__main__":
294
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
quantize_fp8_stream.py DELETED
@@ -1,121 +0,0 @@
1
- """
2
- Streaming CPU FP8 quantizer for MiMo-V2.5-ASR.
3
-
4
- Avoids loading the full model into RAM and never uses CUDA (works around the lack of
5
- sm_120 / Blackwell kernels in torch 2.6+cu124). Reads the original safetensors shards,
6
- quantizes every nn.Linear weight to float8_e4m3fn (per-out-channel absmax), leaves
7
- embeddings / norms / biases in bf16, and writes a single model.safetensors whose keys
8
- match the FP8Linear loader (`*.weight_fp8`, `*.weight_scale`).
9
- """
10
- import sys, json, shutil, argparse
11
- from pathlib import Path
12
- import torch
13
- import torch.nn as nn
14
- from safetensors.torch import save_file, safe_open
15
-
16
- REPO = Path(__file__).resolve().parent
17
- sys.path.insert(0, str(REPO))
18
- from quantize_fp8 import (
19
- quantize_weight_per_channel, CONFIG_FILES, _build_args_and_tokenizer, FP8_DTYPE,
20
- )
21
-
22
-
23
- def linear_weight_names(model_path: str) -> set:
24
- """Build the model on meta and collect '<path>.weight' for every nn.Linear."""
25
- from src.mimo_audio.modeling_mimo_audio import MiMoAudioForCausalLM
26
- from transformers import AutoConfig
27
- args, _ = _build_args_and_tokenizer(model_path)
28
- cfg = AutoConfig.from_pretrained(model_path)
29
- with torch.device("meta"):
30
- model = MiMoAudioForCausalLM(cfg, args)
31
- names = set()
32
- for name, mod in model.named_modules():
33
- if isinstance(mod, nn.Linear):
34
- names.add(name + ".weight")
35
- return names
36
-
37
-
38
- def main():
39
- ap = argparse.ArgumentParser()
40
- ap.add_argument("--model-path", required=True)
41
- ap.add_argument("--out-dir", required=True)
42
- ap.add_argument("--dry-run", action="store_true")
43
- a = ap.parse_args()
44
- mp = Path(a.model_path)
45
- out = Path(a.out_dir)
46
-
47
- lin = linear_weight_names(str(mp))
48
- print(f"quantizable Linear weights: {len(lin)}")
49
-
50
- idx = json.loads((mp / "model.safetensors.index.json").read_text())
51
- weight_map = idx["weight_map"]
52
- shards = {}
53
- for k, sh in weight_map.items():
54
- shards.setdefault(sh, []).append(k)
55
- all_keys = set(weight_map)
56
- matched = lin & all_keys
57
- missing = lin - all_keys
58
- print(f"checkpoint keys: {len(all_keys)} | linear matched: {len(matched)} | linear missing in ckpt: {len(missing)}")
59
- if missing:
60
- print(" MISSING (first 10):", sorted(missing)[:10])
61
-
62
- if a.dry_run:
63
- # show a few non-linear keys for sanity
64
- nonlin = sorted(all_keys - lin)
65
- print("sample NON-linear keys kept as-is:", nonlin[:8])
66
- print("total params:", len(all_keys), "-> fp8:", len(matched), "kept:", len(all_keys) - len(matched))
67
- return
68
-
69
- out.mkdir(parents=True, exist_ok=True)
70
- new_state = {}
71
- bytes_before = bytes_after = 0
72
- conv = 0
73
- for shard in sorted(shards):
74
- with safe_open(str(mp / shard), framework="pt", device="cpu") as f:
75
- for k in shards[shard]:
76
- t = f.get_tensor(k)
77
- if k in lin:
78
- w_fp8, scale = quantize_weight_per_channel(t) # scale [out,1]
79
- base = k[:-len(".weight")]
80
- new_state[base + ".weight_fp8"] = w_fp8.contiguous()
81
- new_state[base + ".weight_scale"] = scale.squeeze(1).contiguous()
82
- bytes_before += t.numel() * t.element_size()
83
- bytes_after += w_fp8.numel() + scale.numel() * 4
84
- conv += 1
85
- else:
86
- bytes_before += t.numel() * t.element_size()
87
- # kept tensors (embeddings/norms/biases): store bf16 to match the
88
- # bf16 model the FP8Linear loader builds, and to shrink the file.
89
- if t.is_floating_point():
90
- t = t.to(torch.bfloat16)
91
- new_state[k] = t.contiguous()
92
- bytes_after += t.numel() * t.element_size()
93
- print(f" done {shard} (running fp8 layers: {conv})")
94
-
95
- st = out / "model.safetensors"
96
- save_file(new_state, str(st), metadata={"format": "pt"})
97
-
98
- copied = []
99
- for cfg in CONFIG_FILES:
100
- src = mp / cfg
101
- if src.exists():
102
- shutil.copy2(src, out / cfg); copied.append(cfg)
103
-
104
- ratio = round(bytes_before / max(bytes_after, 1), 3)
105
- meta = {
106
- "dtype": "float8_e4m3fn", "weight_scaling": "per_channel_absmax",
107
- "activation_scaling": "dynamic_per_tensor", "matmul_op": "torch._scaled_mm",
108
- "output_dtype": "bfloat16", "converted_layers": conv,
109
- "weight_gb_before": round(bytes_before / 1e9, 3),
110
- "weight_gb_after": round(bytes_after / 1e9, 3), "compression_ratio": ratio,
111
- "quantizer": "streaming_cpu",
112
- }
113
- (out / "fp8_meta.json").write_text(json.dumps(meta, indent=2))
114
- gb = st.stat().st_size / 1e9
115
- print(f"\nOK {st} ({gb:.2f} GB on disk)")
116
- print(f" {conv} layers -> fp8 | {round(bytes_before/1e9,2)}GB -> {round(bytes_after/1e9,2)}GB ({ratio}x)")
117
- print(f" copied config: {', '.join(copied)}")
118
-
119
-
120
- if __name__ == "__main__":
121
- main()