| 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/wespeaker-voxceleb-resnet34-LM embedding model from PyTorch to GGML |
| 7 |
# |
| 8 |
# Prerequisites: |
| 9 |
# pip install pyannote.audio |
| 10 |
# |
| 11 |
# Usage: |
| 12 |
# # Inspect the model: |
| 13 |
# python convert-pyannote-embedding-to-ggml.py --inspect path/to/pytorch_model.bin |
| 14 |
# |
| 15 |
# # Convert to GGML: |
| 16 |
# python convert-pyannote-embedding-to-ggml.py path/to/pytorch_model.bin ./output-dir |
| 17 |
# |
| 18 |
# Download pytorch_model.bin from: |
| 19 |
# https://huggingface.co/pyannote/wespeaker-voxceleb-resnet34-LM |
| 20 |
# |
| 21 |
# Output format: |
| 22 |
# - magic ("ggml") |
| 23 |
# - hparams (architecture parameters) |
| 24 |
# - tensors (same format as segmentation converter) |
| 25 |
# |
| 26 |
# Architecture: WeSpeaker ResNet34 |
| 27 |
# conv1(1->32, k=3, p=1) + bn1 |
| 28 |
# layer1: 3x BasicBlock(32->32) |
| 29 |
# layer2: 4x BasicBlock(32->64, first stride=2, with shortcut) |
| 30 |
# layer3: 6x BasicBlock(64->128, first stride=2, with shortcut) |
| 31 |
# layer4: 3x BasicBlock(128->256, first stride=2, with shortcut) |
| 32 |
# TSTP pooling (no params) |
| 33 |
# seg_1: Linear(5120->256) |
| 34 |
# |
| 35 |
|
| 36 |
import os |
| 37 |
import sys |
| 38 |
import struct |
| 39 |
import numpy as np |
| 40 |
import torch |
| 41 |
from pathlib import Path |
| 42 |
|
| 43 |
|
| 44 |
# ============================================================================ |
| 45 |
# Inspect mode |
| 46 |
# ============================================================================ |
| 47 |
|
| 48 |
def inspect_model(fname_inp): |
| 49 |
from pyannote.audio import Model |
| 50 |
|
| 51 |
print(f"Loading: {fname_inp}") |
| 52 |
print(f"File size: {os.path.getsize(fname_inp)} bytes ({os.path.getsize(fname_inp) / 1024 / 1024:.2f} MB)") |
| 53 |
print() |
| 54 |
|
| 55 |
model = Model.from_pretrained(fname_inp) |
| 56 |
state_dict = model.state_dict() |
| 57 |
|
| 58 |
print(f"Model class: {type(model).__name__}") |
| 59 |
print(f"Number of tensors: {len(state_dict)}") |
| 60 |
print() |
| 61 |
print(f" {'Name':65s} {'Shape':25s} {'Dtype':10s} {'Elements':>12s} {'Size (KB)':>10s}") |
| 62 |
print(" " + "-" * 130) |
| 63 |
|
| 64 |
total_params = 0 |
| 65 |
total_bytes = 0 |
| 66 |
for name in state_dict.keys(): |
| 67 |
tensor = state_dict[name] |
| 68 |
shape_str = str(list(tensor.shape)) |
| 69 |
n_elements = tensor.numel() |
| 70 |
n_bytes = n_elements * tensor.element_size() |
| 71 |
total_params += n_elements |
| 72 |
total_bytes += n_bytes |
| 73 |
print(f" {name:65s} {shape_str:25s} {str(tensor.dtype):10s} {n_elements:12d} {n_bytes/1024:10.1f}") |
| 74 |
|
| 75 |
print(" " + "-" * 130) |
| 76 |
print(f" Total: {total_params:,} parameters, {total_bytes / 1024 / 1024:.2f} MB") |
| 77 |
print() |
| 78 |
|
| 79 |
print("Sample values (first 5 elements):") |
| 80 |
for name in state_dict.keys(): |
| 81 |
tensor = state_dict[name] |
| 82 |
flat = tensor.detach().cpu().flatten() |
| 83 |
vals = flat[:min(5, len(flat))].numpy() |
| 84 |
vals_str = ", ".join(f"{v:.6f}" for v in vals) |
| 85 |
print(f" {name:65s} [{vals_str}]") |
| 86 |
|
| 87 |
|
| 88 |
# ============================================================================ |
| 89 |
# Convert mode |
| 90 |
# ============================================================================ |
| 91 |
|
| 92 |
def convert_model(fname_inp, dir_out): |
| 93 |
from pyannote.audio import Model |
| 94 |
|
| 95 |
print(f"Loading: {fname_inp}") |
| 96 |
|
| 97 |
model = Model.from_pretrained(fname_inp) |
| 98 |
model.eval() |
| 99 |
list_vars = model.state_dict() |
| 100 |
|
| 101 |
print(f"Model class: {type(model).__name__}") |
| 102 |
print(f"Tensors: {len(list_vars)}") |
| 103 |
|
| 104 |
# Output file |
| 105 |
dir_out = Path(dir_out) |
| 106 |
dir_out.mkdir(parents=True, exist_ok=True) |
| 107 |
fname_out = dir_out / "ggml-embedding.bin" |
| 108 |
|
| 109 |
fout = fname_out.open("wb") |
| 110 |
|
| 111 |
# ========================================================================= |
| 112 |
# Write magic: "ggml" |
| 113 |
# ========================================================================= |
| 114 |
fout.write(struct.pack("i", 0x67676d6c)) |
| 115 |
|
| 116 |
# ========================================================================= |
| 117 |
# Write hparams -- derived from tensor shapes |
| 118 |
# ========================================================================= |
| 119 |
|
| 120 |
# Base channels: from conv1 output channels |
| 121 |
m_channels = list_vars["resnet.conv1.weight"].shape[0] # 32 |
| 122 |
|
| 123 |
# Embed dim and feat dim from seg_1 weight |
| 124 |
embed_dim = list_vars["resnet.seg_1.weight"].shape[0] # 256 |
| 125 |
pool_out_dim = list_vars["resnet.seg_1.weight"].shape[1] # 5120 |
| 126 |
# TSTP: pool_out = 2 * stats_dim (mean + std) |
| 127 |
# stats_dim = (feat_dim / 8) * m_channels * 8 = feat_dim * m_channels |
| 128 |
stats_dim = pool_out_dim // 2 # 2560 |
| 129 |
feat_dim = stats_dim // m_channels # 80 |
| 130 |
|
| 131 |
# Count blocks per layer |
| 132 |
num_blocks = [] |
| 133 |
for layer_idx in range(1, 5): |
| 134 |
n = 0 |
| 135 |
while f"resnet.layer{layer_idx}.{n}.conv1.weight" in list_vars: |
| 136 |
n += 1 |
| 137 |
num_blocks.append(n) |
| 138 |
|
| 139 |
# Check for two_emb_layer |
| 140 |
two_emb_layer = 1 if "resnet.seg_2.weight" in list_vars else 0 |
| 141 |
|
| 142 |
print("hparams (derived from model):") |
| 143 |
print(f" m_channels = {m_channels}") |
| 144 |
print(f" feat_dim = {feat_dim}") |
| 145 |
print(f" embed_dim = {embed_dim}") |
| 146 |
print(f" num_blocks = {num_blocks}") |
| 147 |
print(f" two_emb_layer = {two_emb_layer}") |
| 148 |
|
| 149 |
fout.write(struct.pack("i", m_channels)) # 32 |
| 150 |
fout.write(struct.pack("i", feat_dim)) # 80 |
| 151 |
fout.write(struct.pack("i", embed_dim)) # 256 |
| 152 |
fout.write(struct.pack("i", num_blocks[0])) # 3 |
| 153 |
fout.write(struct.pack("i", num_blocks[1])) # 4 |
| 154 |
fout.write(struct.pack("i", num_blocks[2])) # 6 |
| 155 |
fout.write(struct.pack("i", num_blocks[3])) # 3 |
| 156 |
fout.write(struct.pack("i", two_emb_layer)) # 0 |
| 157 |
|
| 158 |
# ========================================================================= |
| 159 |
# Write model tensors |
| 160 |
# ========================================================================= |
| 161 |
n_written = 0 |
| 162 |
n_skipped = 0 |
| 163 |
|
| 164 |
for name in list_vars.keys(): |
| 165 |
tensor = list_vars[name] |
| 166 |
|
| 167 |
# Skip num_batches_tracked -- not needed for inference |
| 168 |
if "num_batches_tracked" in name: |
| 169 |
n_skipped += 1 |
| 170 |
continue |
| 171 |
|
| 172 |
# Don't squeeze 4D conv weights — they need to keep all dimensions |
| 173 |
# (e.g. conv1.weight [32,1,3,3] must NOT become [32,3,3]) |
| 174 |
# Only squeeze truly scalar/1-element tensors |
| 175 |
if tensor.dim() <= 1: |
| 176 |
data = tensor.numpy().astype(np.float32) |
| 177 |
else: |
| 178 |
data = tensor.numpy().astype(np.float32) |
| 179 |
n_dims = len(data.shape) |
| 180 |
|
| 181 |
print(f" Writing: {name:65s} shape={str(list(data.shape)):25s} ({data.size} elements)") |
| 182 |
|
| 183 |
ftype = 0 # f32 |
| 184 |
|
| 185 |
# header |
| 186 |
str_ = name.encode('utf-8') |
| 187 |
fout.write(struct.pack("iii", n_dims, len(str_), ftype)) |
| 188 |
for i in range(n_dims): |
| 189 |
fout.write(struct.pack("i", data.shape[n_dims - 1 - i])) |
| 190 |
fout.write(str_) |
| 191 |
|
| 192 |
# data |
| 193 |
data.tofile(fout) |
| 194 |
n_written += 1 |
| 195 |
|
| 196 |
fout.close() |
| 197 |
|
| 198 |
print(f"\nWritten {n_written} tensors, skipped {n_skipped}") |
| 199 |
print(f"Output file: {fname_out}") |
| 200 |
print(f"Output size: {os.path.getsize(fname_out)} bytes ({os.path.getsize(fname_out) / 1024 / 1024:.2f} MB)") |
| 201 |
|
| 202 |
|
| 203 |
# ============================================================================ |
| 204 |
# Main |
| 205 |
# ============================================================================ |
| 206 |
|
| 207 |
if len(sys.argv) < 2: |
| 208 |
print("Usage:") |
| 209 |
print(f" {sys.argv[0]} --inspect model.bin # inspect model tensors") |
| 210 |
print(f" {sys.argv[0]} model.bin dir-output # convert to GGML") |
| 211 |
print() |
| 212 |
print("Prerequisites: pip install pyannote.audio") |
| 213 |
sys.exit(1) |
| 214 |
|
| 215 |
if sys.argv[1] == "--inspect": |
| 216 |
if len(sys.argv) < 3: |
| 217 |
print("Usage: --inspect model.bin") |
| 218 |
sys.exit(1) |
| 219 |
inspect_model(sys.argv[2]) |
| 220 |
else: |
| 221 |
if len(sys.argv) < 3: |
| 222 |
print(f"Usage: {sys.argv[0]} model.bin dir-output") |
| 223 |
sys.exit(1) |
| 224 |
convert_model(sys.argv[1], sys.argv[2]) |