Debian Codegraph @

generate/pyannote/convert-pyannote-segmentation-to-ggml.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # generate/whispercpp/convert-pyannote-embedding-to-ggml.py
4 # Anastasia Shchupak, 21 March 2026, 30 May 2026
5
6 # Convert pyannote segmentation-3.0 (PyanNet) model from PyTorch to ggml format
7 #
8 # Prerequisites:
9 # pip install pyannote.audio
10 #
11 # Usage:
12 # # Inspect the model (see all tensor names and shapes):
13 # python convert-pyannote-segmentation-to-ggml.py --inspect path/to/pytorch_model.bin
14 #
15 # # Convert to GGML (default: f16 for large tensors):
16 # python convert-pyannote-segmentation-to-ggml.py path/to/pytorch_model.bin ./output-dir
17 #
18 # # Convert to GGML (all f32):
19 # python convert-pyannote-segmentation-to-ggml.py path/to/pytorch_model.bin ./output-dir use-f32
20 #
21 # You can download pytorch_model.bin from:
22 # https://huggingface.co/pyannote/segmentation-3.0
23 # (requires accepting user conditions + HF token)
24 #
25 # This script loads the model via pyannote.audio, extracts the state_dict,
26 # and writes it in ggml format. The output is a single binary file containing:
27 #
28 # - hparams
29 # - model variables
30 #
31 # For each variable, write the following:
32 #
33 # - Number of dimensions (int)
34 # - Name length (int)
35 # - Dimensions (int[n_dims]) -- in reverse order per ggml convention
36 # - Name (char[name_length])
37 # - Data (float[n_dims])
38 #
39
40 import io
41 import os
42 import sys
43 import struct
44 import torch
45 import numpy as np
46 from pathlib import Path
47
48 # ============================================================================
49 # Inspect mode: load and print all tensors
50 # ============================================================================
51
52 def inspect_model(fname_inp):
53 """Load the PyTorch model via pyannote and print its full tensor inventory."""
54
55 from pyannote.audio import Model
56
57 print(f"Loading: {fname_inp}")
58 print(f"File size: {os.path.getsize(fname_inp)} bytes ({os.path.getsize(fname_inp) / 1024 / 1024:.2f} MB)")
59 print()
60
61 model = Model.from_pretrained(fname_inp)
62 state_dict = model.state_dict()
63
64 print(f"Model class: {type(model).__name__}")
65 print(f"Number of tensors: {len(state_dict)}")
66 print()
67 print(f" {'Name':55s} {'Shape':25s} {'Dtype':10s} {'Elements':>12s} {'Size (KB)':>10s}")
68 print(" " + "-" * 118)
69
70 total_params = 0
71 total_bytes = 0
72 for name in sorted(state_dict.keys()):
73 tensor = state_dict[name]
74 shape_str = str(list(tensor.shape))
75 n_elements = tensor.numel()
76 n_bytes = n_elements * tensor.element_size()
77 total_params += n_elements
78 total_bytes += n_bytes
79 print(f" {name:55s} {shape_str:25s} {str(tensor.dtype):10s} {n_elements:12d} {n_bytes/1024:10.1f}")
80
81 print(" " + "-" * 118)
82 print(f" Total: {total_params:,} parameters, {total_bytes / 1024 / 1024:.2f} MB")
83 print()
84
85 # Print first few values of each tensor for later verification against C++ loader
86 print("Sample values (first 5 elements of each tensor):")
87 for name in sorted(state_dict.keys()):
88 tensor = state_dict[name]
89 flat = tensor.detach().cpu().flatten()
90 vals = flat[:min(5, len(flat))].numpy()
91 vals_str = ", ".join(f"{v:.6f}" for v in vals)
92 print(f" {name:55s} [{vals_str}]")
93
94
95 # ============================================================================
96 # Convert mode
97 # ============================================================================
98
99 def convert_model(fname_inp, dir_out):
100 """Convert the segmentation model to GGML format."""
101
102 from pyannote.audio import Model
103
104 print(f"Loading: {fname_inp}")
105
106 model = Model.from_pretrained(fname_inp)
107 list_vars = model.state_dict()
108
109 print(f"Model class: {type(model).__name__}")
110 print(f"Tensors: {len(list_vars)}")
111
112 # output file
113 dir_out = Path(dir_out)
114 dir_out.mkdir(parents=True, exist_ok=True)
115 fname_out = dir_out / "ggml-segmentation.bin"
116
117 fout = fname_out.open("wb")
118
119 # =========================================================================
120 # Write magic: "ggml"
121 # =========================================================================
122 fout.write(struct.pack("i", 0x67676d6c))
123
124 # =========================================================================
125 # Write hparams
126 # =========================================================================
127 # Modeled after whisper converter lines 268-279.
128 # The C++ loader will read these in exactly this order.
129 #
130 # IMPORTANT: We derive values from the actual tensor shapes rather than
131 # hardcoding, because the pretrained model may differ from source code
132 # defaults. For example, segmentation-3.0 has 4 LSTM layers (not 2),
133 # and the SincNet filterbank has 40 learned parameter pairs (not 80).
134
135 # --- Derive architecture from tensor shapes ---
136
137 # SincNet: n_filters_0 = output channels of first conv block
138 # ParamSincFB stores low_hz_ [n_params, 1] — the actual output is 2*n_params
139 sincnet_n_params = list_vars["sincnet.conv1d.0.filterbank.low_hz_"].shape[0] # 40
140 sincnet_filters_0 = sincnet_n_params * 2 # 80 (ParamSincFB doubles the filters)
141 sincnet_kernel_0 = list_vars["sincnet.conv1d.0.filterbank.window_"].shape[0] * 2 + 1 # 125*2+1=251
142 sincnet_filters_1 = list_vars["sincnet.conv1d.1.weight"].shape[0] # 60
143 sincnet_kernel_1 = list_vars["sincnet.conv1d.1.weight"].shape[2] # 5
144 sincnet_filters_2 = list_vars["sincnet.conv1d.2.weight"].shape[0] # 60
145 sincnet_kernel_2 = list_vars["sincnet.conv1d.2.weight"].shape[2] # 5
146
147 # LSTM: count layers by looking for weight_ih_l{N} keys
148 lstm_layers = 0
149 while f"lstm.weight_ih_l{lstm_layers}" in list_vars:
150 lstm_layers += 1
151 lstm_input_size = list_vars["lstm.weight_ih_l0"].shape[1] # 60
152 lstm_hidden_size = list_vars["lstm.weight_hh_l0"].shape[1] # 128
153 lstm_bidir = 1 if "lstm.weight_ih_l0_reverse" in list_vars else 0 # 1
154
155 # Linear layers: count by looking for linear.{N}.weight keys
156 linear_layers = 0
157 while f"linear.{linear_layers}.weight" in list_vars:
158 linear_layers += 1
159 linear_hidden = list_vars["linear.0.weight"].shape[0] # 128
160
161 # Classifier
162 n_classes = list_vars["classifier.weight"].shape[0] # 7
163
164 # Stride of SincConv — not stored in any tensor, this is an architecture
165 # parameter. PyanNet.SINCNET_DEFAULTS = {"stride": 10} for segmentation-3.0.
166 # If a different model uses a different stride, change this here.
167 sincnet_stride_0 = 10
168
169 print("hparams (derived from model):")
170 print(f" sincnet_filters_0 = {sincnet_filters_0}")
171 print(f" sincnet_kernel_0 = {sincnet_kernel_0}")
172 print(f" sincnet_stride_0 = {sincnet_stride_0}")
173 print(f" sincnet_filters_1 = {sincnet_filters_1}")
174 print(f" sincnet_kernel_1 = {sincnet_kernel_1}")
175 print(f" sincnet_filters_2 = {sincnet_filters_2}")
176 print(f" sincnet_kernel_2 = {sincnet_kernel_2}")
177 print(f" lstm_input_size = {lstm_input_size}")
178 print(f" lstm_hidden_size = {lstm_hidden_size}")
179 print(f" lstm_layers = {lstm_layers}")
180 print(f" lstm_bidirectional = {lstm_bidir}")
181 print(f" linear_hidden = {linear_hidden}")
182 print(f" linear_layers = {linear_layers}")
183 print(f" n_classes = {n_classes}")
184
185 fout.write(struct.pack("i", sincnet_filters_0)) # 80
186 fout.write(struct.pack("i", sincnet_kernel_0)) # 251
187 fout.write(struct.pack("i", sincnet_stride_0)) # 10
188 fout.write(struct.pack("i", sincnet_filters_1)) # 60
189 fout.write(struct.pack("i", sincnet_kernel_1)) # 5
190 fout.write(struct.pack("i", sincnet_filters_2)) # 60
191 fout.write(struct.pack("i", sincnet_kernel_2)) # 5
192 fout.write(struct.pack("i", lstm_input_size)) # 60
193 fout.write(struct.pack("i", lstm_hidden_size)) # 128
194 fout.write(struct.pack("i", lstm_layers)) # 4
195 fout.write(struct.pack("i", lstm_bidir)) # 1
196 fout.write(struct.pack("i", linear_hidden)) # 128
197 fout.write(struct.pack("i", linear_layers)) # 2
198 fout.write(struct.pack("i", n_classes)) # 7
199
200 # =========================================================================
201 # Write model tensors
202 # =========================================================================
203 # Following the exact whisper converter pattern (lines 295-337):
204 #
205 # for name in list_vars.keys():
206 # data = list_vars[name].squeeze().numpy()
207 # n_dims = len(data.shape)
208 # ftype = 1
209 # if use_f16:
210 # if n_dims < 2 or name == ...:
211 # data = data.astype(np.float32)
212 # ftype = 0
213 # str_ = name.encode('utf-8')
214 # fout.write(struct.pack("iii", n_dims, len(str_), ftype))
215 # for i in range(n_dims):
216 # fout.write(struct.pack("i", data.shape[n_dims - 1 - i]))
217 # fout.write(str_)
218 # data.tofile(fout)
219
220 for name in list_vars.keys():
221 data = list_vars[name].squeeze().numpy()
222 print("Processing variable: " , name , " with shape: ", data.shape)
223
224 n_dims = len(data.shape)
225
226 # Write data as-is (f32), same as whisper converter which just writes
227 # whatever dtype the checkpoint already has. The pyannote checkpoint is
228 # all float32. We can add f16 quantization later as an optimization.
229 data = data.astype(np.float32)
230 ftype = 0
231
232 # header
233 str_ = name.encode('utf-8')
234 fout.write(struct.pack("iii", n_dims, len(str_), ftype))
235 for i in range(n_dims):
236 fout.write(struct.pack("i", data.shape[n_dims - 1 - i]))
237 fout.write(str_)
238
239 # data
240 data.tofile(fout)
241
242 fout.close()
243
244 print(f"\nDone. Output file: {fname_out}")
245 print(f"Output size: {os.path.getsize(fname_out)} bytes ({os.path.getsize(fname_out) / 1024 / 1024:.2f} MB)")
246
247
248 # ============================================================================
249 # Main
250 # ============================================================================
251
252 if len(sys.argv) < 2:
253 print("Usage:")
254 print(f" {sys.argv[0]} --inspect model.bin # inspect model tensors")
255 print(f" {sys.argv[0]} model.bin dir-output [use-f32] # convert to GGML")
256 print()
257 print("Prerequisites: pip install pyannote.audio")
258 sys.exit(1)
259
260 if sys.argv[1] == "--inspect":
261 if len(sys.argv) < 3:
262 print("Usage: --inspect model.bin")
263 sys.exit(1)
264 inspect_model(sys.argv[2])
265 else:
266 if len(sys.argv) < 3:
267 print(f"Usage: {sys.argv[0]} model.bin dir-output")
268 sys.exit(1)
269 fname_inp = sys.argv[1]
270 dir_out = sys.argv[2]
271 convert_model(fname_inp, dir_out)