|
| 1 | +import os |
| 2 | +import struct |
| 3 | +import argparse |
| 4 | +import torch |
| 5 | +import numpy as np |
| 6 | +from silero_vad import load_silero_vad, __version__ as silero_version |
| 7 | + |
| 8 | +def convert_silero_vad(output_path, print_tensors=True): |
| 9 | + model = load_silero_vad() |
| 10 | + state_dict = model.state_dict() |
| 11 | + |
| 12 | + # Clean up state dict keys - filter out 8k model |
| 13 | + cleaned_dict = {} |
| 14 | + for key, value in state_dict.items(): |
| 15 | + # Skip 8k model |
| 16 | + if "_8k" not in key: |
| 17 | + clean_key = key |
| 18 | + if not key.startswith("_model."): |
| 19 | + clean_key = "_model." + key |
| 20 | + cleaned_dict[clean_key] = value |
| 21 | + |
| 22 | + base, ext = os.path.splitext(output_path) |
| 23 | + output_file = f"{base}-v{silero_version}-ggml{ext}" |
| 24 | + print(f"Saving GGML Silero-VAD model to {output_file}") |
| 25 | + |
| 26 | + print("\nTensor info for debugging:") |
| 27 | + for key, tensor in cleaned_dict.items(): |
| 28 | + print(f" - {key}: {tensor.shape} ({tensor.dtype})") |
| 29 | + print() |
| 30 | + |
| 31 | + with open(output_file, "wb") as fout: |
| 32 | + # Write magic and version |
| 33 | + fout.write(struct.pack("i", 0x67676d6c)) |
| 34 | + |
| 35 | + |
| 36 | + # Write model architecture parameters |
| 37 | + window_size = 512 |
| 38 | + fout.write(struct.pack("i", window_size)) |
| 39 | + context_size = 64 |
| 40 | + fout.write(struct.pack("i", context_size)) |
| 41 | + |
| 42 | + n_encoder_layers = 4 |
| 43 | + fout.write(struct.pack("i", n_encoder_layers)) |
| 44 | + |
| 45 | + # Write encoder dimensions |
| 46 | + input_channels = 129 |
| 47 | + encoder_in_channels = [input_channels, 128, 64, 64] |
| 48 | + encoder_out_channels = [128, 64, 64, 128] |
| 49 | + kernel_size = 3 |
| 50 | + |
| 51 | + for i in range(n_encoder_layers): |
| 52 | + fout.write(struct.pack("i", encoder_in_channels[i])) |
| 53 | + fout.write(struct.pack("i", encoder_out_channels[i])) |
| 54 | + fout.write(struct.pack("i", kernel_size)) |
| 55 | + |
| 56 | + # Write LSTM dimensions |
| 57 | + lstm_input_size = 128 |
| 58 | + lstm_hidden_size = 128 |
| 59 | + fout.write(struct.pack("i", lstm_input_size)) |
| 60 | + fout.write(struct.pack("i", lstm_hidden_size)) |
| 61 | + |
| 62 | + # Write final conv dimensions |
| 63 | + final_conv_in = 128 |
| 64 | + final_conv_out = 1 |
| 65 | + fout.write(struct.pack("i", final_conv_in)) |
| 66 | + fout.write(struct.pack("i", final_conv_out)) |
| 67 | + |
| 68 | + # Define tensor keys to write |
| 69 | + tensor_keys = [] |
| 70 | + |
| 71 | + # Encoder weights |
| 72 | + for i in range(n_encoder_layers): |
| 73 | + weight_key = f"_model.encoder.{i}.reparam_conv.weight" |
| 74 | + bias_key = f"_model.encoder.{i}.reparam_conv.bias" |
| 75 | + if weight_key in cleaned_dict and bias_key in cleaned_dict: |
| 76 | + tensor_keys.append(weight_key) |
| 77 | + tensor_keys.append(bias_key) |
| 78 | + |
| 79 | + # LSTM weights |
| 80 | + lstm_keys = [ |
| 81 | + "_model.decoder.rnn.weight_ih", |
| 82 | + "_model.decoder.rnn.weight_hh", |
| 83 | + "_model.decoder.rnn.bias_ih", |
| 84 | + "_model.decoder.rnn.bias_hh" |
| 85 | + ] |
| 86 | + tensor_keys.extend([k for k in lstm_keys if k in cleaned_dict]) |
| 87 | + |
| 88 | + # Final conv weights |
| 89 | + final_keys = [ |
| 90 | + "_model.decoder.decoder.2.weight", |
| 91 | + "_model.decoder.decoder.2.bias" |
| 92 | + ] |
| 93 | + tensor_keys.extend([k for k in final_keys if k in cleaned_dict]) |
| 94 | + |
| 95 | + # STFT basis - add this last |
| 96 | + stft_tensor = "_model.stft.forward_basis_buffer" |
| 97 | + tensor_keys.append(stft_tensor) |
| 98 | + |
| 99 | + print(f"Writing {len(tensor_keys)} tensors:") |
| 100 | + for key in tensor_keys: |
| 101 | + if key in cleaned_dict: |
| 102 | + print(f" - {key}: {cleaned_dict[key].shape}") |
| 103 | + else: |
| 104 | + print(f" - {key}: MISSING") |
| 105 | + |
| 106 | + # Process each tensor |
| 107 | + for key in tensor_keys: |
| 108 | + if key not in cleaned_dict: |
| 109 | + print(f"Warning: Missing tensor {key}, skipping") |
| 110 | + continue |
| 111 | + |
| 112 | + tensor = cleaned_dict[key] |
| 113 | + |
| 114 | + # Special handling for STFT tensor |
| 115 | + if key == "_model.stft.forward_basis_buffer": |
| 116 | + # Get the original numpy array without squeezing |
| 117 | + data = tensor.detach().cpu().numpy() |
| 118 | + # Ensure it has the expected shape |
| 119 | + print(f"STFT tensor original shape: {data.shape}") |
| 120 | + n_dims = 3 |
| 121 | + tensor_shape = [data.shape[0], data.shape[1], data.shape[2]] |
| 122 | + is_conv_weight = True |
| 123 | + else: |
| 124 | + # For other tensors, we can use standard processing |
| 125 | + data = tensor.detach().cpu().squeeze().numpy() |
| 126 | + tensor_shape = list(data.shape) |
| 127 | + |
| 128 | + # Ensure we have at most 4 dimensions for GGML |
| 129 | + n_dims = min(len(tensor_shape), 4) |
| 130 | + |
| 131 | + # Reverse dimensions for GGML |
| 132 | + tensor_shape = tensor_shape[:n_dims] |
| 133 | + tensor_shape.reverse() |
| 134 | + |
| 135 | + # Check if this is a convolution weight tensor |
| 136 | + is_conv_weight = "weight" in key and ("encoder" in key or "_model.decoder.decoder.2" in key) |
| 137 | + |
| 138 | + # Convert to float16 for convolution weights |
| 139 | + if is_conv_weight: |
| 140 | + data = data.astype(np.float16) |
| 141 | + ftype = 1 # float16 |
| 142 | + else: |
| 143 | + ftype = 0 # float32 |
| 144 | + |
| 145 | + # Debug printing of tensor info |
| 146 | + print(f"\nWriting tensor: {key}") |
| 147 | + print(f" Original shape: {tensor.shape}") |
| 148 | + print(f" Processed shape: {data.shape}") |
| 149 | + print(f" GGML dimensions: {n_dims}") |
| 150 | + print(f" GGML shape: {tensor_shape}") |
| 151 | + print(f" Type: {'float16' if ftype == 1 else 'float32'}") |
| 152 | + |
| 153 | + # Convert tensor name to bytes |
| 154 | + name_bytes = key.encode('utf-8') |
| 155 | + name_length = len(name_bytes) |
| 156 | + |
| 157 | + # Write tensor header |
| 158 | + fout.write(struct.pack("i", n_dims)) |
| 159 | + fout.write(struct.pack("i", name_length)) |
| 160 | + fout.write(struct.pack("i", ftype)) |
| 161 | + |
| 162 | + # Write tensor dimensions |
| 163 | + for i in range(n_dims): |
| 164 | + size = tensor_shape[i] if i < len(tensor_shape) else 1 |
| 165 | + fout.write(struct.pack("i", size)) |
| 166 | + print(f" Writing dimension {i}: {size}") |
| 167 | + |
| 168 | + # Write tensor name |
| 169 | + fout.write(name_bytes) |
| 170 | + |
| 171 | + # Write tensor data |
| 172 | + data.tofile(fout) |
| 173 | + |
| 174 | + print(f" Wrote {data.size * (2 if ftype==1 else 4)} bytes") |
| 175 | + |
| 176 | + print(f"\nDone! Model has been converted to GGML format: {output_file}") |
| 177 | + print(f"File size: {os.path.getsize(output_file)} bytes") |
| 178 | + |
| 179 | +if __name__ == "__main__": |
| 180 | + parser = argparse.ArgumentParser(description="Convert Silero-VAD PyTorch model to GGML format") |
| 181 | + parser.add_argument("--output", type=str, required=True, help="Path to output GGML model file") |
| 182 | + parser.add_argument("--print-tensors", action="store_true", help="Print tensor values", default=True) |
| 183 | + args = parser.parse_args() |
| 184 | + |
| 185 | + convert_silero_vad(args.output, args.print_tensors) |
0 commit comments