| 1 | /* diarize.cpp |
| 2 | * |
| 3 | * Copyright (C) 2026 Anastasia Shchupak |
| 4 | * |
| 5 | * This code is free software; you can redistribute it and/or modify |
| 6 | * it under the terms of the GNU General Public License as published by |
| 7 | * the Free Software Foundation; either version 3 of the License, or (at |
| 8 | * your option) any later version. |
| 9 | * |
| 10 | * This code is distributed in the hope that it will be useful, but |
| 11 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 13 | * See the GNU General Public License for more details. |
| 14 | * |
| 15 | * You should have received a copy of the GNU General Public License |
| 16 | * along with this work. If not, see <http://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | |
| 19 | /* Speaker diarization pipeline in C++. |
| 20 | * ------------------------------------ |
| 21 | * Reimplements pyannote.audio SpeakerDiarization pipeline: |
| 22 | * Segmentation (pyannote/segmentation-3.0): |
| 23 | * WavNorm -> SincNet (ggml graph) -> LSTM (plain C++) -> Linear -> Classifier -> Log-softmax |
| 24 | * Input: 10s waveform at 16kHz -> Output: 589 frames × 7 powerset classes |
| 25 | * |
| 26 | * Embedding (wespeaker-voxceleb-resnet34-LM): |
| 27 | * Fbank -> ResNet34 (ggml conv2d + plain C++) -> TSTP pooling -> Linear |
| 28 | * Input: variable-length waveform -> Output: 256-d speaker embedding |
| 29 | * |
| 30 | * Clustering: |
| 31 | * AgglomerativeClustering (centroid linkage, threshold=0.7046) |
| 32 | * |
| 33 | * Pipeline flow: |
| 34 | * 1. Sliding window segmentation (10s chunks, 90% overlap) |
| 35 | * 2. Powerset -> multilabel conversion (7 classes -> 3 speakers) |
| 36 | * 3. Embedding extraction per (chunk, speaker) pair with mask |
| 37 | * 4. Filter embeddings (activity ≥ 20%, no NaN) |
| 38 | * 5. Agglomerative clustering (L2-norm -> centroid linkage -> fcluster) |
| 39 | * 6. Assign all embeddings to clusters |
| 40 | * 7. Reconstruct: remap local -> global speakers |
| 41 | * 8. Aggregate overlapping windows |
| 42 | * 9. Top-N speaker selection per frame |
| 43 | * 10. Frame-level -> time-stamped speaker segments |
| 44 | */ |
| 45 | |
| 46 | #include <cstdio> |
| 47 | #include <cstdlib> |
| 48 | #include <cstdint> |
| 49 | #include <cstring> |
| 50 | #include <cmath> |
| 51 | #include <fstream> |
| 52 | #include <string> |
| 53 | #include <vector> |
| 54 | #include <map> |
| 55 | #include <algorithm> |
| 56 | #include <chrono> |
| 57 | #include <atomic> |
| 58 | #include <thread> |
| 59 | |
| 60 | #include "ggml.h" |
| 61 | #include "ggml-alloc.h" |
| 62 | #include "ggml-backend.h" |
| 63 | #include "ggml-cpu.h" |
| 64 | #include "diarize.h" |
| 65 | #include "melder.h" |
| 66 | |
| 67 | #define GGML_FILE_MAGIC 0x67676d6c |
| 68 | |
| 69 | /* |
| 70 | Maximum size for ggml computation graphs. |
| 71 | sincnet_forward builds a graph with 58 nodes (44 nodes and 14 leafs). |
| 72 | conv2d_forward builds a graph with 9 nodes (7 nodes and 2 leafs). |
| 73 | These numbers were found out by including the following print after ggml_build_forward_expand(): |
| 74 | GGML_LOG_INFO("sincnet_forward: graph nodes = %d, leafs = %d\n", ggml_graph_n_nodes(gf), gf->n_leafs); |
| 75 | These number of nodes are rounded up to the next power of 2. |
| 76 | */ |
| 77 | #define SINCNET_MAX_NODES 64 |
| 78 | #define CONV2D_MAX_NODES 16 |
| 79 | |
| 80 | /* |
| 81 | Performance counters for diarization timing breakdown. |
| 82 | These atomic accumulators record how much time each phase of segmentation |
| 83 | and embedding takes (in microseconds), summed across all operations of |
| 84 | a single diarize_full() run. They are reset at the start of each run and |
| 85 | printed if (Melder_debug == 2004) at the end. Atomic types are used to support multithreading. |
| 86 | */ |
| 87 | static std::atomic <int64_t> g_seg_sincnet_us {0}; // ggml SincNet forward |
| 88 | static std::atomic <int64_t> g_seg_lstm_us {0}; // plain-C++ bidirectional LSTM |
| 89 | static std::atomic <int64_t> g_seg_linear_us {0}; // plain-C++ linear layers + classifier |
| 90 | static std::atomic <int> g_seg_calls {0}; // number of segmentation_forward() calls |
| 91 | |
| 92 | static std::atomic <int64_t> g_emb_fbank_us {0}; // plain-C++ fbank feature extraction |
| 93 | static std::atomic <int64_t> g_emb_conv1bn1relu_us {0}; // ResNet stem (ggml conv + plain-C++ BN/ReLU) |
| 94 | static std::atomic <int64_t> g_emb_resnet_us {0}; // ResNet layers 1–4 (mix of ggml and plain C++) |
| 95 | static std::atomic <int64_t> g_emb_tail_us {0}; // TSTP pooling + final linear layer |
| 96 | static std::atomic <int> g_emb_calls {0}; // number of embedding_forward() calls |
| 97 | |
| 98 | // ============================================================================ |
| 99 | // Big-endian support |
| 100 | // ============================================================================ |
| 101 | #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ |
| 102 | template<typename T> |
| 103 | static T byteswap(T value) { |
| 104 | T swapped; |
| 105 | char * src = reinterpret_cast<char *>(&value); |
| 106 | char * dst = reinterpret_cast<char *>(&swapped); |
| 107 | for (int i = 0; i < (int)sizeof(T); i++) { |
| 108 | dst[sizeof(T) - 1 - i] = src[i]; |
| 109 | } |
| 110 | return swapped; |
| 111 | } |
| 112 | |
| 113 | #define BYTESWAP_VALUE(d) d = byteswap(d) |
| 114 | |
| 115 | static void byteswap_tensor(ggml_tensor * tensor) { |
| 116 | if (tensor->type == GGML_TYPE_F32) { |
| 117 | auto * data = reinterpret_cast<float *>(tensor->data); |
| 118 | for (int i = 0; i < ggml_nelements(tensor); i++) data[i] = byteswap(data[i]); |
| 119 | } else if (tensor->type == GGML_TYPE_F16) { |
| 120 | auto * data = reinterpret_cast<ggml_fp16_t *>(tensor->data); |
| 121 | for (int i = 0; i < ggml_nelements(tensor); i++) data[i] = byteswap(data[i]); |
| 122 | } else if (tensor->type == GGML_TYPE_I32) { |
| 123 | auto * data = reinterpret_cast<int32_t *>(tensor->data); |
| 124 | for (int i = 0; i < ggml_nelements(tensor); i++) data[i] = byteswap(data[i]); |
| 125 | } |
| 126 | // GGML_TYPE_I8 needs no swap |
| 127 | } |
| 128 | |
| 129 | #define BYTESWAP_TENSOR(t) byteswap_tensor(t) |
| 130 | #else |
| 131 | #define BYTESWAP_VALUE(d) do {} while (0) |
| 132 | #define BYTESWAP_TENSOR(t) do {} while (0) |
| 133 | #endif |
| 134 | |
| 135 | // ============================================================================ |
| 136 | // Model loading |
| 137 | // ============================================================================ |
| 138 | template<typename T> |
| 139 | static void read_safe(diarize_model_loader * loader, T & dest) { |
| 140 | loader->read(loader->context, &dest, sizeof(T)); |
| 141 | BYTESWAP_VALUE(dest); |
| 142 | } |
| 143 | |
| 144 | // ============================================================================ |
| 145 | // Segmentation: Model structs |
| 146 | // ============================================================================ |
| 147 | // Hyperparameters of the PyanNet segmentation model. |
| 148 | // Values are read from the model file header and overwrite these defaults. |
| 149 | // Defaults here match pyannote/segmentation-3.0. |
| 150 | struct segmentation_hparams { |
| 151 | // SincNet block 0 (SincConv — learned bandpass filterbank): |
| 152 | // 80 bandpass filters (40 cos + 40 sin), each 251 samples long, applied with stride 10. |
| 153 | int32_t sincnet_filters_0 = 80; |
| 154 | int32_t sincnet_kernel_0 = 251; |
| 155 | int32_t sincnet_stride_0 = 10; |
| 156 | |
| 157 | // SincNet block 1 (regular Conv1d): |
| 158 | // Standard convolution 80→60 channels, kernel 5, stride 1. |
| 159 | int32_t sincnet_filters_1 = 60; |
| 160 | int32_t sincnet_kernel_1 = 5; |
| 161 | |
| 162 | // SincNet block 2 (regular Conv1d): |
| 163 | // Standard convolution 60→60 channels, kernel 5, stride 1. |
| 164 | int32_t sincnet_filters_2 = 60; |
| 165 | int32_t sincnet_kernel_2 = 5; |
| 166 | |
| 167 | // LSTM: processes the 589×60 SincNet output as a sequence. |
| 168 | int32_t lstm_input_size = 60; |
| 169 | int32_t lstm_hidden_size = 128; // hidden state size per direction |
| 170 | int32_t lstm_layers = 4; // number of stacked LSTM layers |
| 171 | int32_t lstm_bidirectional = 1; // 1 = bidirectional (forward + reverse)\ |
| 172 | |
| 173 | // Feed-forward layers after LSTM: |
| 174 | int32_t linear_hidden = 128; // hidden size of each linear layer |
| 175 | int32_t linear_layers = 2; // number of linear layers (each with LeakyReLU) |
| 176 | |
| 177 | // Powerset classifier (final output layer, no activation — log-softmax applied after): |
| 178 | int32_t n_classes = 7; // powerset classes for up to 3 speakers |
| 179 | |
| 180 | // Derived |
| 181 | int n_filters() const { return sincnet_filters_0; } // 80 |
| 182 | int n_sinc_params() const { return sincnet_filters_0 / 2; } // 40 (learned frequency pairs) |
| 183 | int half_kernel() const { return sincnet_kernel_0 / 2; } // 125 (symmetric kernel half) |
| 184 | int lstm_output_size() const { return lstm_hidden_size * (lstm_bidirectional ? 2 : 1); } // 256 features per frame |
| 185 | }; |
| 186 | |
| 187 | struct segmentation_model { |
| 188 | segmentation_hparams hparams; |
| 189 | |
| 190 | // Waveform normalization (InstanceNorm1d on raw input, 1 channel) |
| 191 | struct ggml_tensor * sincnet_wav_norm_w; // [1] |
| 192 | struct ggml_tensor * sincnet_wav_norm_b; // [1] |
| 193 | |
| 194 | // SincConv learned filterbank parameters (block 0) |
| 195 | struct ggml_tensor * sincnet_low_hz; // [40] low cutoff frequency per filter pair |
| 196 | struct ggml_tensor * sincnet_band_hz; // [40] bandwidth per filter pair |
| 197 | struct ggml_tensor * sincnet_window; // [125] Hamming window (half-kernel) |
| 198 | struct ggml_tensor * sincnet_n; // [125] normalized frequency grid (half-kernel) |
| 199 | |
| 200 | // Conv1d weights (blocks 1–2; block 0 kernel is computed from the params above) |
| 201 | struct ggml_tensor * sincnet_conv1_w; // [5, 80, 60] |
| 202 | struct ggml_tensor * sincnet_conv1_b; // [60] |
| 203 | struct ggml_tensor * sincnet_conv2_w; // [5, 60, 60] |
| 204 | struct ggml_tensor * sincnet_conv2_b; // [60] |
| 205 | |
| 206 | // InstanceNorm affine parameters (one per block) |
| 207 | struct ggml_tensor * sincnet_norm0_w; // [80] |
| 208 | struct ggml_tensor * sincnet_norm0_b; // [80] |
| 209 | struct ggml_tensor * sincnet_norm1_w; // [60] |
| 210 | struct ggml_tensor * sincnet_norm1_b; // [60] |
| 211 | struct ggml_tensor * sincnet_norm2_w; // [60] |
| 212 | struct ggml_tensor * sincnet_norm2_b; // [60] |
| 213 | |
| 214 | // LSTM (4 layers × 2 directions, hsd = 4*hidden_size = 512) |
| 215 | // Forward direction |
| 216 | struct ggml_tensor * lstm_weight_ih[4]; // [in, 512] input-to-hidden (in=60 for layer 0, 256 for layers 1–3) |
| 217 | struct ggml_tensor * lstm_weight_hh[4]; // [128, 512] hidden-to-hidden |
| 218 | struct ggml_tensor * lstm_bias_ih[4]; // [512] |
| 219 | struct ggml_tensor * lstm_bias_hh[4]; // [512] |
| 220 | // Reverse direction |
| 221 | struct ggml_tensor * lstm_weight_ih_rev[4]; // [in, 512] |
| 222 | struct ggml_tensor * lstm_weight_hh_rev[4]; // [128, 512] |
| 223 | struct ggml_tensor * lstm_bias_ih_rev[4]; // [512] |
| 224 | struct ggml_tensor * lstm_bias_hh_rev[4]; // [512] |
| 225 | |
| 226 | // Feed-forward layers (2 layers with LeakyReLU) |
| 227 | struct ggml_tensor * linear_w[2]; // [256, 128] for layer 0, [128, 128] for layer 1 |
| 228 | struct ggml_tensor * linear_b[2]; // [128] |
| 229 | |
| 230 | // Powerset classifier |
| 231 | struct ggml_tensor * classifier_w; // [128, 7] |
| 232 | struct ggml_tensor * classifier_b; // [7] |
| 233 | |
| 234 | // Bookkeeping |
| 235 | std::map<std::string, struct ggml_tensor *> tensors; |
| 236 | int n_loaded = 0; |
| 237 | std::vector<ggml_context *> ctxs; |
| 238 | std::vector<ggml_backend_buffer_t> buffers; |
| 239 | }; |
| 240 | |
| 241 | struct segmentation_context { |
| 242 | segmentation_model model; |
| 243 | |
| 244 | // Pre-computed SincNet filters [n_filters * kernel_size] |
| 245 | std::vector<float> sinc_filters; |
| 246 | |
| 247 | // GGML backend for SincNet |
| 248 | ggml_backend_t backend = nullptr; |
| 249 | }; |
| 250 | |
| 251 | // ============================================================================ |
| 252 | // Segmentation: Model loading |
| 253 | // ============================================================================ |
| 254 | static void segmentation_load_model(diarize_model_loader * loader, segmentation_model & model) { |
| 255 | //TRACE |
| 256 | uint32_t magic; |
| 257 | read_safe(loader, magic); |
| 258 | if (magic != GGML_FILE_MAGIC) |
| 259 | Melder_throw(U"Invalid model data (bad magic)."); |
| 260 | |
| 261 | auto & hp = model.hparams; |
| 262 | read_safe(loader, hp.sincnet_filters_0); |
| 263 | read_safe(loader, hp.sincnet_kernel_0); |
| 264 | read_safe(loader, hp.sincnet_stride_0); |
| 265 | read_safe(loader, hp.sincnet_filters_1); |
| 266 | read_safe(loader, hp.sincnet_kernel_1); |
| 267 | read_safe(loader, hp.sincnet_filters_2); |
| 268 | read_safe(loader, hp.sincnet_kernel_2); |
| 269 | read_safe(loader, hp.lstm_input_size); |
| 270 | read_safe(loader, hp.lstm_hidden_size); |
| 271 | read_safe(loader, hp.lstm_layers); |
| 272 | read_safe(loader, hp.lstm_bidirectional); |
| 273 | read_safe(loader, hp.linear_hidden); |
| 274 | read_safe(loader, hp.linear_layers); |
| 275 | read_safe(loader, hp.n_classes); |
| 276 | |
| 277 | trace (U"sincnet=", hp.sincnet_filters_0, U"/", hp.sincnet_kernel_0, U"/", hp.sincnet_stride_0, |
| 278 | U" lstm=", hp.lstm_layers, U"x", hp.lstm_hidden_size, U"(bidir=", hp.lstm_bidirectional, U")", |
| 279 | U" linear=", hp.linear_layers, U"x", hp.linear_hidden, |
| 280 | U" classes=", hp.n_classes, U""); |
| 281 | |
| 282 | const int nsp = hp.n_sinc_params(); |
| 283 | const int hk = hp.half_kernel(); |
| 284 | const int hsd = hp.lstm_hidden_size * 4; |
| 285 | const size_t nt = 16 + 8 * hp.lstm_layers + 2 * hp.linear_layers + 2; |
| 286 | |
| 287 | std::map<ggml_backend_buffer_type_t, ggml_context*> ctx_map; |
| 288 | auto cpu_buft = ggml_backend_cpu_buffer_type(); |
| 289 | |
| 290 | auto get_ctx = [&](ggml_backend_buffer_type_t buft) -> ggml_context* { |
| 291 | auto it = ctx_map.find(buft); |
| 292 | if (it == ctx_map.end()) { |
| 293 | ggml_init_params p = { |
| 294 | nt * ggml_tensor_overhead(), |
| 295 | nullptr, |
| 296 | true |
| 297 | }; |
| 298 | auto c = ggml_init(p); |
| 299 | ctx_map[buft] = c; |
| 300 | model.ctxs.push_back(c); |
| 301 | return c; |
| 302 | } |
| 303 | return it->second; |
| 304 | }; |
| 305 | |
| 306 | auto CT = [&](const std::string & name, ggml_tensor * meta) -> ggml_tensor* { |
| 307 | auto c = get_ctx(cpu_buft); |
| 308 | auto t = ggml_dup_tensor(c, meta); |
| 309 | ggml_set_name(t, name.c_str()); |
| 310 | model.tensors[name] = t; |
| 311 | return t; |
| 312 | }; |
| 313 | |
| 314 | { |
| 315 | ggml_init_params mp = { |
| 316 | nt * ggml_tensor_overhead(), |
| 317 | nullptr, |
| 318 | true |
| 319 | }; |
| 320 | auto ctx = ggml_init(mp); |
| 321 | |
| 322 | // SincNet |
| 323 | model.sincnet_wav_norm_w = CT("sincnet.wav_norm1d.weight", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1)); |
| 324 | model.sincnet_wav_norm_b = CT("sincnet.wav_norm1d.bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1)); |
| 325 | model.sincnet_low_hz = CT("sincnet.conv1d.0.filterbank.low_hz_", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nsp)); |
| 326 | model.sincnet_band_hz = CT("sincnet.conv1d.0.filterbank.band_hz_", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nsp)); |
| 327 | model.sincnet_window = CT("sincnet.conv1d.0.filterbank.window_", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hk)); |
| 328 | model.sincnet_n = CT("sincnet.conv1d.0.filterbank.n_", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hk)); |
| 329 | |
| 330 | model.sincnet_conv1_w = CT("sincnet.conv1d.1.weight", ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hp.sincnet_kernel_1, hp.sincnet_filters_0, hp.sincnet_filters_1)); |
| 331 | model.sincnet_conv1_b = CT("sincnet.conv1d.1.bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_1)); |
| 332 | model.sincnet_conv2_w = CT("sincnet.conv1d.2.weight", ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hp.sincnet_kernel_2, hp.sincnet_filters_1, hp.sincnet_filters_2)); |
| 333 | model.sincnet_conv2_b = CT("sincnet.conv1d.2.bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_2)); |
| 334 | |
| 335 | model.sincnet_norm0_w = CT("sincnet.norm1d.0.weight", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_0)); |
| 336 | model.sincnet_norm0_b = CT("sincnet.norm1d.0.bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_0)); |
| 337 | model.sincnet_norm1_w = CT("sincnet.norm1d.1.weight", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_1)); |
| 338 | model.sincnet_norm1_b = CT("sincnet.norm1d.1.bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_1)); |
| 339 | model.sincnet_norm2_w = CT("sincnet.norm1d.2.weight", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_2)); |
| 340 | model.sincnet_norm2_b = CT("sincnet.norm1d.2.bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_2)); |
| 341 | |
| 342 | // LSTM |
| 343 | for (int l = 0; l < hp.lstm_layers; l++) { |
| 344 | int in_sz = (l == 0) ? hp.lstm_input_size : hp.lstm_output_size(); |
| 345 | std::string ls = std::to_string(l); |
| 346 | model.lstm_weight_ih[l] = CT("lstm.weight_ih_l"+ls, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, in_sz, hsd)); |
| 347 | model.lstm_weight_hh[l] = CT("lstm.weight_hh_l"+ls, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, hp.lstm_hidden_size, hsd)); |
| 348 | model.lstm_bias_ih[l] = CT("lstm.bias_ih_l"+ls, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hsd)); |
| 349 | model.lstm_bias_hh[l] = CT("lstm.bias_hh_l"+ls, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hsd)); |
| 350 | model.lstm_weight_ih_rev[l] = CT("lstm.weight_ih_l"+ls+"_reverse", ggml_new_tensor_2d(ctx, GGML_TYPE_F32, in_sz, hsd)); |
| 351 | model.lstm_weight_hh_rev[l] = CT("lstm.weight_hh_l"+ls+"_reverse", ggml_new_tensor_2d(ctx, GGML_TYPE_F32, hp.lstm_hidden_size, hsd)); |
| 352 | model.lstm_bias_ih_rev[l] = CT("lstm.bias_ih_l"+ls+"_reverse", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hsd)); |
| 353 | model.lstm_bias_hh_rev[l] = CT("lstm.bias_hh_l"+ls+"_reverse", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hsd)); |
| 354 | } |
| 355 | |
| 356 | // Linear |
| 357 | int lo = hp.lstm_output_size(); |
| 358 | for (int l = 0; l < hp.linear_layers; l++) { |
| 359 | int inf = (l == 0) ? lo : hp.linear_hidden; |
| 360 | model.linear_w[l] = CT("linear."+std::to_string(l)+".weight", ggml_new_tensor_2d(ctx, GGML_TYPE_F32, inf, hp.linear_hidden)); |
| 361 | model.linear_b[l] = CT("linear."+std::to_string(l)+".bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.linear_hidden)); |
| 362 | } |
| 363 | |
| 364 | // Classifier |
| 365 | int ci = (hp.linear_layers > 0) ? hp.linear_hidden : lo; |
| 366 | model.classifier_w = CT("classifier.weight", ggml_new_tensor_2d(ctx, GGML_TYPE_F32, ci, hp.n_classes)); |
| 367 | model.classifier_b = CT("classifier.bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_classes)); |
| 368 | |
| 369 | ggml_free(ctx); |
| 370 | } |
| 371 | |
| 372 | // Allocate buffers |
| 373 | for (auto & p : ctx_map) { |
| 374 | auto buf = ggml_backend_alloc_ctx_tensors_from_buft(p.second, p.first); |
| 375 | if (buf) |
| 376 | model.buffers.push_back(buf); |
| 377 | } |
| 378 | |
| 379 | // Load weights |
| 380 | model.n_loaded = 0; |
| 381 | std::vector<char> read_buf; |
| 382 | while (!loader->eof(loader->context)) { |
| 383 | int32_t n_dims, length, ttype; |
| 384 | read_safe(loader, n_dims); |
| 385 | read_safe(loader, length); |
| 386 | read_safe(loader, ttype); |
| 387 | if (loader->eof(loader->context)) break; |
| 388 | |
| 389 | int32_t n_elements = 1, ne[4] = {1,1,1,1}; |
| 390 | for (int i = 0; i < n_dims; i++) { |
| 391 | read_safe(loader, ne[i]); |
| 392 | n_elements *= ne[i]; |
| 393 | } |
| 394 | |
| 395 | std::string name(length, 0); |
| 396 | loader->read(loader->context, name.data(), length); |
| 397 | |
| 398 | auto it = model.tensors.find(name); |
| 399 | if (it == model.tensors.end()) |
| 400 | Melder_throw(U": unknown tensor '", Melder_peek8to32_u(name.c_str()), U"'"); |
| 401 | |
| 402 | auto tensor = it->second; |
| 403 | const size_t bpe = ggml_type_size(ggml_type(ttype)); |
| 404 | |
| 405 | if (ggml_backend_buffer_is_host(tensor->buffer)) { |
| 406 | loader->read(loader->context, tensor->data, n_elements * bpe); |
| 407 | BYTESWAP_TENSOR(tensor); |
| 408 | } else { |
| 409 | read_buf.resize(ggml_nbytes(tensor)); |
| 410 | loader->read(loader->context, read_buf.data(), read_buf.size()); |
| 411 | // For non-host buffers, we'd need to byteswap in the temp buffer |
| 412 | // before copying to device, but as for now we are CPU-only, this path is not taken |
| 413 | ggml_backend_tensor_set(tensor, read_buf.data(), 0, ggml_nbytes(tensor)); |
| 414 | } |
| 415 | model.n_loaded++; |
| 416 | } |
| 417 | |
| 418 | trace (U"Loaded ", model.n_loaded, U"/", model.tensors.size(), U" tensors"); |
| 419 | if (model.n_loaded != model.tensors.size()) |
| 420 | Melder_throw (U"Segmentation model incomplete: loaded ", model.n_loaded, U" of ", model.tensors.size(), U" tensors."); |
| 421 | } |
| 422 | |
| 423 | // ============================================================================ |
| 424 | // Segmentation: Pre-compute SincNet bandpass filters |
| 425 | // ============================================================================ |
| 426 | static std::vector<float> compute_sinc_filters(const segmentation_model & model) { |
| 427 | auto & hp = model.hparams; |
| 428 | const int np = hp.n_sinc_params(); |
| 429 | const int hk = hp.half_kernel(); |
| 430 | const int ks = hp.sincnet_kernel_0; |
| 431 | const int nf = hp.n_filters(); |
| 432 | |
| 433 | const float mlh = 50.f; |
| 434 | const float mbh = 50.f; |
| 435 | const float sr = 16000.f; |
| 436 | |
| 437 | const float *lh = (const float*)model.sincnet_low_hz->data; |
| 438 | const float *bh = (const float*)model.sincnet_band_hz->data; |
| 439 | const float *w = (const float*)model.sincnet_window->data; |
| 440 | const float *n = (const float*)model.sincnet_n->data; |
| 441 | |
| 442 | std::vector<float> f(nf * ks, 0.f); |
| 443 | for (int i = 0; i < np; i++) { |
| 444 | float lo = mlh + fabsf(lh[i]); // low cutoff (minimum 50 Hz) |
| 445 | float hi = lo + mbh + fabsf(bh[i]); // high cutoff (at least 50 Hz above lo) |
| 446 | if (hi > sr/2) |
| 447 | hi = sr/2; // clamped to Nyquist (8000 Hz = 16000/2). |
| 448 | float b = hi - lo; |
| 449 | float nm = 2.f * b; |
| 450 | |
| 451 | // Cos filter |
| 452 | float *fc = &f[i * ks]; |
| 453 | for (int j = 0; j < hk; j++) fc[j] = (sinf(hi*n[j]) - sinf(lo*n[j])) / (n[j]/2.f) * w[j]; |
| 454 | fc[hk] = 2.f * b; |
| 455 | for (int j = 0; j < hk; j++) fc[hk+1+j] = fc[hk-1-j]; |
| 456 | for (int j = 0; j < ks; j++) fc[j] /= nm; |
| 457 | |
| 458 | // Sin filter |
| 459 | float *fs = &f[(np+i) * ks]; |
| 460 | for (int j = 0; j < hk; j++) fs[j] = (cosf(lo*n[j]) - cosf(hi*n[j])) / (n[j]/2.f) * w[j]; |
| 461 | fs[hk] = 0.f; |
| 462 | for (int j = 0; j < hk; j++) fs[hk+1+j] = -fs[hk-1-j]; |
| 463 | for (int j = 0; j < ks; j++) fs[j] /= nm; |
| 464 | } |
| 465 | return f; |
| 466 | } |
| 467 | |
| 468 | // ============================================================================ |
| 469 | // Segmentation: F32 conv1d (avoids F16 im2col precision loss) |
| 470 | // ============================================================================ |
| 471 | static ggml_tensor * ggml_conv_1d_f32(ggml_context * ctx, ggml_tensor * a, ggml_tensor * b, |
| 472 | int s0, int p0, int d0) { |
| 473 | auto im2col = ggml_im2col(ctx, a, b, s0, 0, p0, 0, d0, 0, false, GGML_TYPE_F32); |
| 474 | auto result = ggml_mul_mat(ctx, |
| 475 | ggml_reshape_2d(ctx, im2col, im2col->ne[0], im2col->ne[2] * im2col->ne[1]), |
| 476 | ggml_reshape_2d(ctx, a, a->ne[0] * a->ne[1], a->ne[2])); |
| 477 | return ggml_reshape_3d(ctx, result, im2col->ne[1], a->ne[2], im2col->ne[2]); |
| 478 | } |
| 479 | |
| 480 | // ============================================================================ |
| 481 | // Segmentation: SincNet forward pass (GGML graph) |
| 482 | // Block 0: SincConv(80, k=251, s=10) -> abs -> MaxPool(3,s=3) -> InstanceNorm(80) -> LeakyReLU |
| 483 | // Block 1: Conv1d(80->60, k=5) + bias -> MaxPool(3,s=3) -> InstanceNorm(60) -> LeakyReLU |
| 484 | // Block 2: Conv1d(60->60, k=5) + bias -> MaxPool(3,s=3) -> InstanceNorm(60) -> LeakyReLU |
| 485 | // Returns output tensor from the graph after compute. |
| 486 | // Output shape: [ne0=time, ne1=channels] = [589, 60] |
| 487 | // ============================================================================ |
| 488 | static bool sincnet_forward(segmentation_context & sctx, |
| 489 | const float * samples, int n_samples, |
| 490 | std::vector<float> & output, int & out_time, int & out_ch) { |
| 491 | auto & model = sctx.model; |
| 492 | auto & hp = model.hparams; |
| 493 | |
| 494 | ggml_init_params ctx_params = { |
| 495 | ggml_tensor_overhead() * SINCNET_MAX_NODES + ggml_graph_overhead(), |
| 496 | nullptr, |
| 497 | true |
| 498 | }; |
| 499 | ggml_context * ctx0 = ggml_init(ctx_params); |
| 500 | |
| 501 | // Input |
| 502 | ggml_tensor * inp = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_samples); |
| 503 | ggml_set_name(inp, "input"); |
| 504 | ggml_set_input(inp); |
| 505 | |
| 506 | // Sinc filter weights |
| 507 | ggml_tensor * sinc_w = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32,hp.sincnet_kernel_0, 1, hp.n_filters()); |
| 508 | ggml_set_name(sinc_w, "sinc_w"); |
| 509 | ggml_set_input(sinc_w); |
| 510 | |
| 511 | // wav_norm1d |
| 512 | ggml_tensor * cur = ggml_norm(ctx0, inp, 1e-5f); |
| 513 | cur = ggml_mul(ctx0, cur, model.sincnet_wav_norm_w); |
| 514 | cur = ggml_add(ctx0, cur, model.sincnet_wav_norm_b); |
| 515 | |
| 516 | // Helper lambda for one SincNet block |
| 517 | auto block = [&](ggml_tensor * conv_w, ggml_tensor * conv_b, int stride, ggml_tensor * nw, ggml_tensor * nb, |
| 518 | int nch, bool do_abs) { |
| 519 | cur = ggml_conv_1d_f32(ctx0, conv_w, cur, stride, 0, 1); |
| 520 | if (conv_b) cur = ggml_add(ctx0, cur, ggml_reshape_3d(ctx0, conv_b, 1, nch, 1)); |
| 521 | if (do_abs) cur = ggml_abs(ctx0, cur); |
| 522 | cur = ggml_pool_1d(ctx0, cur, GGML_OP_POOL_MAX, 3, 3, 0); |
| 523 | cur = ggml_norm(ctx0, cur, 1e-5f); |
| 524 | cur = ggml_mul(ctx0, cur, ggml_reshape_2d(ctx0, nw, 1, nch)); |
| 525 | cur = ggml_add(ctx0, cur, ggml_reshape_2d(ctx0, nb, 1, nch)); |
| 526 | cur = ggml_leaky_relu(ctx0, cur, 0.01f, false); |
| 527 | }; |
| 528 | |
| 529 | // Block 0: SincConv |
| 530 | block(sinc_w, nullptr, hp.sincnet_stride_0, |
| 531 | model.sincnet_norm0_w, model.sincnet_norm0_b, hp.sincnet_filters_0, true); |
| 532 | |
| 533 | // Block 1 |
| 534 | block(model.sincnet_conv1_w, model.sincnet_conv1_b, 1, |
| 535 | model.sincnet_norm1_w, model.sincnet_norm1_b, hp.sincnet_filters_1, false); |
| 536 | |
| 537 | // Block 2 |
| 538 | block(model.sincnet_conv2_w, model.sincnet_conv2_b, 1, |
| 539 | model.sincnet_norm2_w, model.sincnet_norm2_b, hp.sincnet_filters_2, false); |
| 540 | |
| 541 | ggml_set_name(cur, "sincnet_out"); |
| 542 | ggml_set_output(cur); |
| 543 | |
| 544 | // Build and compute |
| 545 | ggml_cgraph * gf = ggml_new_graph_custom(ctx0, SINCNET_MAX_NODES, false); |
| 546 | ggml_build_forward_expand(gf, cur); |
| 547 | //GGML_LOG_INFO("sincnet_forward: graph nodes = %d, leafs = %d\n", ggml_graph_n_nodes(gf), gf->n_leafs); |
| 548 | |
| 549 | ggml_gallocr_t galloc = ggml_gallocr_new(ggml_backend_get_default_buffer_type(sctx.backend)); |
| 550 | ggml_gallocr_alloc_graph(galloc, gf); |
| 551 | |
| 552 | ggml_backend_tensor_set(inp, samples, 0, n_samples * sizeof(float)); |
| 553 | ggml_backend_tensor_set(sinc_w, sctx.sinc_filters.data(), 0, |
| 554 | sctx.sinc_filters.size() * sizeof(float)); |
| 555 | |
| 556 | ggml_backend_graph_compute(sctx.backend, gf); |
| 557 | |
| 558 | out_time = (int)cur->ne[0]; |
| 559 | out_ch = (int)cur->ne[1]; |
| 560 | int total = out_time * out_ch; |
| 561 | output.resize(total); |
| 562 | ggml_backend_tensor_get(cur, output.data(), 0, total * sizeof(float)); |
| 563 | |
| 564 | ggml_gallocr_free(galloc); |
| 565 | ggml_free(ctx0); |
| 566 | return true; |
| 567 | } |
| 568 | |
| 569 | // ============================================================================ |
| 570 | // Segmentation: LSTM one direction (plain C++) |
| 571 | // ============================================================================ |
| 572 | static void lstm_one_direction( |
| 573 | const float * x, float * out, |
| 574 | const int T, const int input_size, const int H, |
| 575 | const float * w_ih, const float * w_hh, |
| 576 | const float * b_ih, const float * b_hh, |
| 577 | bool reverse) { |
| 578 | std::vector<float> h(H, 0.f), c(H, 0.f), gates(4*H); |
| 579 | |
| 580 | for (int step = 0; step < T; step++) { |
| 581 | int t = reverse ? (T-1-step) : step; |
| 582 | const float * xt = &x[t * input_size]; |
| 583 | |
| 584 | for (int g = 0; g < 4*H; g++) { |
| 585 | float val = b_ih[g] + b_hh[g]; |
| 586 | for (int j = 0; j < input_size; j++) val += w_ih[g*input_size + j] * xt[j]; |
| 587 | for (int j = 0; j < H; j++) val += w_hh[g*H + j] * h[j]; |
| 588 | gates[g] = val; |
| 589 | } |
| 590 | |
| 591 | for (int j = 0; j < H; j++) { |
| 592 | float ig = 1.f / (1.f + expf(-gates[0*H+j])); |
| 593 | float fg = 1.f / (1.f + expf(-gates[1*H+j])); |
| 594 | float gg = tanhf(gates[2*H+j]); |
| 595 | float og = 1.f / (1.f + expf(-gates[3*H+j])); |
| 596 | c[j] = fg * c[j] + ig * gg; |
| 597 | h[j] = og * tanhf(c[j]); |
| 598 | } |
| 599 | for (int j = 0; j < H; j++) out[t*H + j] = h[j]; |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | // ============================================================================ |
| 604 | // Segmentation: LSTM full forward pass (plain C++) |
| 605 | // 4-layer bidirectional LSTM |
| 606 | // Input: [T, input_size] (e.g. [589, 60]) |
| 607 | // Output: [T, 2*H] (e.g. [589, 256]) |
| 608 | // ============================================================================ |
| 609 | static std::vector<float> lstm_forward(const segmentation_model & model, const float * input, int T) { |
| 610 | auto & hp = model.hparams; |
| 611 | const int H = hp.lstm_hidden_size; |
| 612 | const int out_dim = hp.lstm_output_size(); |
| 613 | |
| 614 | std::vector<float> cur(input, input + T * hp.lstm_input_size); |
| 615 | int cur_input_size = hp.lstm_input_size; |
| 616 | |
| 617 | for (int l = 0; l < hp.lstm_layers; l++) { |
| 618 | const float * w_ih_f = (const float*)model.lstm_weight_ih[l]->data; |
| 619 | const float * w_hh_f = (const float*)model.lstm_weight_hh[l]->data; |
| 620 | const float * b_ih_f = (const float*)model.lstm_bias_ih[l]->data; |
| 621 | const float * b_hh_f = (const float*)model.lstm_bias_hh[l]->data; |
| 622 | const float * w_ih_r = (const float*)model.lstm_weight_ih_rev[l]->data; |
| 623 | const float * w_hh_r = (const float*)model.lstm_weight_hh_rev[l]->data; |
| 624 | const float * b_ih_r = (const float*)model.lstm_bias_ih_rev[l]->data; |
| 625 | const float * b_hh_r = (const float*)model.lstm_bias_hh_rev[l]->data; |
| 626 | |
| 627 | std::vector<float> out_fwd(T * H), out_rev(T * H); |
| 628 | lstm_one_direction(cur.data(), out_fwd.data(), T, cur_input_size, H, |
| 629 | w_ih_f, w_hh_f, b_ih_f, b_hh_f, false); |
| 630 | lstm_one_direction(cur.data(), out_rev.data(), T, cur_input_size, H, |
| 631 | w_ih_r, w_hh_r, b_ih_r, b_hh_r, true); |
| 632 | |
| 633 | std::vector<float> next(T * out_dim); |
| 634 | for (int t = 0; t < T; t++) { |
| 635 | for (int j = 0; j < H; j++) { |
| 636 | next[t * out_dim + j] = out_fwd[t * H + j]; |
| 637 | next[t * out_dim + H + j] = out_rev[t * H + j]; |
| 638 | } |
| 639 | } |
| 640 | cur = std::move(next); |
| 641 | cur_input_size = out_dim; |
| 642 | } |
| 643 | return cur; |
| 644 | } |
| 645 | |
| 646 | // ============================================================================ |
| 647 | // Segmentation: Linear + Classifier + Activation (plain C++) |
| 648 | // Linear: 2 layers, 256->128->128, LeakyReLU |
| 649 | // Classifier: 128->7 |
| 650 | // Activation: log-softmax |
| 651 | // ============================================================================ |
| 652 | static std::vector<float> linear_leaky_relu(const float * x, int T, int in_f, int out_f, |
| 653 | const float * weight, const float * bias) { |
| 654 | std::vector<float> out(T * out_f); |
| 655 | for (int t = 0; t < T; t++) { |
| 656 | for (int o = 0; o < out_f; o++) { |
| 657 | float val = bias[o]; |
| 658 | for (int i = 0; i < in_f; i++) val += weight[o * in_f + i] * x[t * in_f + i]; |
| 659 | out[t * out_f + o] = (val < 0) ? 0.01f * val : val; |
| 660 | } |
| 661 | } |
| 662 | return out; |
| 663 | } |
| 664 | |
| 665 | static std::vector<float> linear_forward_raw(const float * x, int T, int in_f, int out_f, |
| 666 | const float * weight, const float * bias) { |
| 667 | std::vector<float> out(T * out_f); |
| 668 | for (int t = 0; t < T; t++) { |
| 669 | for (int o = 0; o < out_f; o++) { |
| 670 | float val = bias[o]; |
| 671 | for (int i = 0; i < in_f; i++) val += weight[o * in_f + i] * x[t * in_f + i]; |
| 672 | out[t * out_f + o] = val; |
| 673 | } |
| 674 | } |
| 675 | return out; |
| 676 | } |
| 677 | |
| 678 | static std::vector<float> log_softmax(const float * x, const int T, const int C) { |
| 679 | std::vector<float> out(T * C); |
| 680 | for (int t = 0; t < T; t++) { |
| 681 | const float * row = &x[t * C]; |
| 682 | float mx = row[0]; |
| 683 | for (int j = 1; j < C; j++) if (row[j] > mx) mx = row[j]; |
| 684 | float sum = 0.f; |
| 685 | for (int j = 0; j < C; j++) sum += expf(row[j] - mx); |
| 686 | float ls = mx + logf(sum); |
| 687 | for (int j = 0; j < C; j++) out[t * C + j] = row[j] - ls; |
| 688 | } |
| 689 | return out; |
| 690 | } |
| 691 | |
| 692 | // ============================================================================ |
| 693 | // Segmentation: Full forward pass |
| 694 | // ============================================================================ |
| 695 | // Input: samples[n_samples] — 10s waveform at 16kHz (n_samples = 160000) |
| 696 | // Output: result[n_frames * n_classes] — log-softmax probabilities |
| 697 | // n_frames is set to the actual frame count (589 for 10s input) |
| 698 | static bool segmentation_forward(segmentation_context & sctx, const float * samples, int n_samples, |
| 699 | std::vector<float> & result, int & n_frames, int & n_classes) { |
| 700 | //TRACE |
| 701 | const auto & model = sctx.model; |
| 702 | auto & hp = model.hparams; |
| 703 | |
| 704 | // 1. SincNet (GGML graph) |
| 705 | std::vector<float> sincnet_out; |
| 706 | int sn_time, sn_ch; |
| 707 | |
| 708 | auto t0 = std::chrono::high_resolution_clock::now(); |
| 709 | |
| 710 | if (!sincnet_forward(sctx, samples, n_samples, sincnet_out, sn_time, sn_ch)) { |
| 711 | return false; |
| 712 | } |
| 713 | auto t1 = std::chrono::high_resolution_clock::now(); |
| 714 | trace (U"SincNet output: [", sn_time, U", ", sn_ch, U"]"); |
| 715 | |
| 716 | // SincNet output is [ne0=time, ne1=ch] in GGML memory order. |
| 717 | // This is the same as [ch, time] in PyTorch. |
| 718 | // PyanNet does: rearrange(sincnet_out, "batch feature frame -> batch frame feature") |
| 719 | // So we need to transpose: [ch, time] -> [time, ch] |
| 720 | // In memory: sincnet_out[c * time + t] -> lstm_in[t * ch + c] |
| 721 | const int T = sn_time; |
| 722 | std::vector<float> lstm_in(T * sn_ch); |
| 723 | for (int t = 0; t < T; t++) { |
| 724 | for (int c = 0; c < sn_ch; c++) { |
| 725 | lstm_in[t * sn_ch + c] = sincnet_out[c * T + t]; |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | // 2. LSTM (plain C++) |
| 730 | const auto lstm_out = lstm_forward(model, lstm_in.data(), T); |
| 731 | auto t2 = std::chrono::high_resolution_clock::now(); |
| 732 | trace (U"LSTM output: [", T, U", ", hp.lstm_output_size(), U"]"); |
| 733 | |
| 734 | // 3. Linear layers |
| 735 | const float * cur = lstm_out.data(); |
| 736 | int cur_dim = hp.lstm_output_size(); |
| 737 | |
| 738 | std::vector<float> lin_out; |
| 739 | for (int l = 0; l < hp.linear_layers; l++) { |
| 740 | lin_out = linear_leaky_relu(cur, T, cur_dim, hp.linear_hidden, |
| 741 | (const float*)model.linear_w[l]->data, |
| 742 | (const float*)model.linear_b[l]->data); |
| 743 | cur = lin_out.data(); |
| 744 | cur_dim = hp.linear_hidden; |
| 745 | } |
| 746 | |
| 747 | // 4. Classifier |
| 748 | auto cls_out = linear_forward_raw(cur, T, cur_dim, hp.n_classes, |
| 749 | (const float*)model.classifier_w->data, |
| 750 | (const float*)model.classifier_b->data); |
| 751 | |
| 752 | // 5. Log-softmax activation |
| 753 | result = log_softmax(cls_out.data(), T, hp.n_classes); |
| 754 | auto t3 = std::chrono::high_resolution_clock::now(); |
| 755 | |
| 756 | n_frames = T; |
| 757 | n_classes = hp.n_classes; |
| 758 | |
| 759 | if (Melder_debug == 2004) { |
| 760 | auto us = [](auto a, auto b) { |
| 761 | return std::chrono::duration_cast<std::chrono::microseconds>(b - a).count(); |
| 762 | }; |
| 763 | g_seg_sincnet_us += us(t0, t1); |
| 764 | g_seg_lstm_us += us(t1, t2); |
| 765 | g_seg_linear_us += us(t2, t3); |
| 766 | ++ g_seg_calls; |
| 767 | } |
| 768 | |
| 769 | return true; |
| 770 | } |
| 771 | |
| 772 | // ============================================================================ |
| 773 | // Segmentation: Init / Free |
| 774 | // ============================================================================ |
| 775 | static void segmentation_init(segmentation_context & sctx, diarize_model_loader * loader) { |
| 776 | //TRACE |
| 777 | try { |
| 778 | segmentation_load_model(loader, sctx.model); |
| 779 | } catch (MelderError) { |
| 780 | Melder_throw (U"Could not load segmentation model."); |
| 781 | } |
| 782 | |
| 783 | sctx.sinc_filters = compute_sinc_filters(sctx.model); |
| 784 | sctx.backend = ggml_backend_cpu_init(); |
| 785 | |
| 786 | trace (U"Initialized (", sctx.model.hparams.n_filters(), U" sinc filters, ", sctx.model.hparams.sincnet_kernel_0, U" kernel)"); |
| 787 | } |
| 788 | |
| 789 | static void segmentation_free(segmentation_context & sctx) { |
| 790 | if (sctx.backend) |
| 791 | ggml_backend_free(sctx.backend); |
| 792 | for (auto buf : sctx.model.buffers) |
| 793 | ggml_backend_buffer_free(buf); |
| 794 | for (auto ctx : sctx.model.ctxs) |
| 795 | ggml_free(ctx); |
| 796 | } |
| 797 | |
| 798 | |
| 799 | // ============================================================================ |
| 800 | // WeSpeaker ResNet34 speaker embedding inference in C++ |
| 801 | // Complete forward pass: Fbank extraction -> ResNet34 -> TSTP pooling -> Linear |
| 802 | // |
| 803 | // Architecture (wespeaker-voxceleb-resnet34-LM): |
| 804 | // Fbank: Kaldi-compatible, 80 mel bins, 25ms frame, 10ms shift, Hamming |
| 805 | // Stem: Conv2d(1->32, k=3, s=1, p=1) + BN + ReLU |
| 806 | // Layer1: 3x BasicBlock(32->32, s=1) |
| 807 | // Layer2: 4x BasicBlock(32->64, first s=2, shortcut) |
| 808 | // Layer3: 6x BasicBlock(64->128, first s=2, shortcut) |
| 809 | // Layer4: 3x BasicBlock(128->256, first s=2, shortcut) |
| 810 | // TSTP: temporal statistics pooling (mean+std) -> 5120 |
| 811 | // seg_1: Linear(5120->256) |
| 812 | // Input: float[n_samples] — raw PCM audio at 16kHz, normalized to [-1, 1] |
| 813 | // Output: float[256] — speaker embedding |
| 814 | // ============================================================================ |
| 815 | // Embedding: Model structs |
| 816 | // ============================================================================ |
| 817 | struct embedding_hparams { |
| 818 | int32_t m_channels; // 32 |
| 819 | int32_t feat_dim; // 80 (mel bins) |
| 820 | int32_t embed_dim; // 256 |
| 821 | int32_t num_blocks[4]; // [3, 4, 6, 3] |
| 822 | int32_t two_emb_layer; // 0 |
| 823 | |
| 824 | int ch(int layer) const { return m_channels * (1 << (layer - 1)); } |
| 825 | }; |
| 826 | |
| 827 | struct embedding_model { |
| 828 | embedding_hparams hparams; |
| 829 | std::map<std::string, struct ggml_tensor *> tensors; |
| 830 | int n_loaded = 0; |
| 831 | std::vector<ggml_context *> ctxs; |
| 832 | std::vector<ggml_backend_buffer_t> buffers; |
| 833 | }; |
| 834 | |
| 835 | struct embedding_context { |
| 836 | embedding_model model; |
| 837 | ggml_backend_t backend = nullptr; |
| 838 | }; |
| 839 | |
| 840 | // ============================================================================ |
| 841 | // Embedding: Model loading |
| 842 | // ============================================================================ |
| 843 | static void embedding_load_model(diarize_model_loader * loader, embedding_model & model) { |
| 844 | //TRACE |
| 845 | uint32_t magic; |
| 846 | read_safe(loader, magic); |
| 847 | if (magic != GGML_FILE_MAGIC) |
| 848 | Melder_throw (U"Invalid model data (bad magic)."); |
| 849 | |
| 850 | auto & hp = model.hparams; |
| 851 | read_safe(loader, hp.m_channels); |
| 852 | read_safe(loader, hp.feat_dim); |
| 853 | read_safe(loader, hp.embed_dim); |
| 854 | for (int i = 0; i < 4; i++) |
| 855 | read_safe(loader, hp.num_blocks[i]); |
| 856 | read_safe(loader, hp.two_emb_layer); |
| 857 | |
| 858 | trace (U"m_ch=", hp.m_channels, U" feat=", hp.feat_dim, U" embed=", hp.embed_dim, |
| 859 | U" blocks=[", hp.num_blocks[0], U",", hp.num_blocks[1], U",", hp.num_blocks[2], U",", hp.num_blocks[3], |
| 860 | U"] two_emb=", hp.two_emb_layer); |
| 861 | |
| 862 | // Count tensors |
| 863 | int total_blocks = hp.num_blocks[0] + hp.num_blocks[1] + hp.num_blocks[2] + hp.num_blocks[3]; |
| 864 | size_t n_tensors = 5 + total_blocks * 10 + 3 * 5 + 2; |
| 865 | if (hp.two_emb_layer) |
| 866 | n_tensors += 2; |
| 867 | |
| 868 | // Create tensors |
| 869 | std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map; |
| 870 | ggml_backend_buffer_type_t cpu_buft = ggml_backend_cpu_buffer_type(); |
| 871 | |
| 872 | auto get_ctx = [&](ggml_backend_buffer_type_t buft) -> ggml_context * { |
| 873 | auto it = ctx_map.find(buft); |
| 874 | if (it == ctx_map.end()) { |
| 875 | ggml_init_params params = { |
| 876 | (n_tensors + 16) * ggml_tensor_overhead(), |
| 877 | nullptr, |
| 878 | true |
| 879 | }; |
| 880 | ggml_context * ctx = ggml_init(params); |
| 881 | ctx_map[buft] = ctx; |
| 882 | model.ctxs.push_back(ctx); |
| 883 | return ctx; |
| 884 | } |
| 885 | return it->second; |
| 886 | }; |
| 887 | |
| 888 | auto CT = [&](const std::string & name, ggml_tensor * meta) -> ggml_tensor * { |
| 889 | ggml_context * ctx = get_ctx(cpu_buft); |
| 890 | ggml_tensor * t = ggml_dup_tensor(ctx, meta); |
| 891 | ggml_set_name(t, name.c_str()); |
| 892 | model.tensors[name] = t; |
| 893 | return t; |
| 894 | }; |
| 895 | |
| 896 | auto create_bn = [&](ggml_context * ctx, const std::string & prefix, int channels) { |
| 897 | CT(prefix + ".weight", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, channels)); |
| 898 | CT(prefix + ".bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, channels)); |
| 899 | CT(prefix + ".running_mean", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, channels)); |
| 900 | CT(prefix + ".running_var", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, channels)); |
| 901 | }; |
| 902 | |
| 903 | { |
| 904 | ggml_init_params meta_params = { |
| 905 | (n_tensors + 16) * ggml_tensor_overhead(), |
| 906 | nullptr, |
| 907 | true |
| 908 | }; |
| 909 | ggml_context * ctx = ggml_init(meta_params); |
| 910 | |
| 911 | // Stem |
| 912 | CT("resnet.conv1.weight", ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 3, 3, 1, hp.m_channels)); |
| 913 | create_bn(ctx, "resnet.bn1", hp.m_channels); |
| 914 | |
| 915 | // ResNet layers |
| 916 | int in_ch = hp.m_channels; |
| 917 | for (int layer = 1; layer <= 4; layer++) { |
| 918 | int out_ch = hp.ch(layer); |
| 919 | int stride_first = (layer == 1) ? 1 : 2; |
| 920 | std::string lp = "resnet.layer" + std::to_string(layer); |
| 921 | for (int blk = 0; blk < hp.num_blocks[layer-1]; blk++) { |
| 922 | std::string bp = lp + "." + std::to_string(blk); |
| 923 | int blk_in = (blk == 0) ? in_ch : out_ch; |
| 924 | CT(bp + ".conv1.weight", ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 3, 3, blk_in, out_ch)); |
| 925 | create_bn(ctx, bp + ".bn1", out_ch); |
| 926 | CT(bp + ".conv2.weight", ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 3, 3, out_ch, out_ch)); |
| 927 | create_bn(ctx, bp + ".bn2", out_ch); |
| 928 | if (blk == 0 && (stride_first != 1 || in_ch != out_ch)) { |
| 929 | CT(bp + ".shortcut.0.weight", ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, 1, in_ch, out_ch)); |
| 930 | create_bn(ctx, bp + ".shortcut.1", out_ch); |
| 931 | } |
| 932 | } |
| 933 | in_ch = out_ch; |
| 934 | } |
| 935 | |
| 936 | // seg_1 |
| 937 | int stats_dim = (hp.feat_dim / 8) * hp.m_channels * 8; |
| 938 | int pool_out = stats_dim * 2; |
| 939 | CT("resnet.seg_1.weight", ggml_new_tensor_2d(ctx, GGML_TYPE_F32, pool_out, hp.embed_dim)); |
| 940 | CT("resnet.seg_1.bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.embed_dim)); |
| 941 | if (hp.two_emb_layer) { |
| 942 | CT("resnet.seg_2.weight", ggml_new_tensor_2d(ctx, GGML_TYPE_F32, hp.embed_dim, hp.embed_dim)); |
| 943 | CT("resnet.seg_2.bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.embed_dim)); |
| 944 | } |
| 945 | ggml_free(ctx); |
| 946 | } |
| 947 | |
| 948 | // Allocate |
| 949 | for (auto & p : ctx_map) { |
| 950 | ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(p.second, p.first); |
| 951 | if (buf) |
| 952 | model.buffers.push_back(buf); |
| 953 | } |
| 954 | |
| 955 | // Load weights |
| 956 | model.n_loaded = 0; |
| 957 | std::vector<char> read_buf; |
| 958 | while (true) { |
| 959 | int32_t n_dims, length, ttype; |
| 960 | read_safe(loader, n_dims); |
| 961 | read_safe(loader, length); |
| 962 | read_safe(loader, ttype); |
| 963 | if (loader->eof(loader->context)) break; |
| 964 | |
| 965 | int32_t n_elements = 1; |
| 966 | int32_t ne[4] = {1,1,1,1}; |
| 967 | |
| 968 | for (int i = 0; i < n_dims; ++i) { |
| 969 | read_safe(loader, ne[i]); |
| 970 | n_elements *= ne[i]; |
| 971 | } |
| 972 | std::string name(length, 0); |
| 973 | loader->read(loader->context, name.data(), length); |
| 974 | |
| 975 | auto it = model.tensors.find(name); |
| 976 | if (it == model.tensors.end()) |
| 977 | Melder_throw (U"Unknown tensor '", Melder_peek8to32_u (name.c_str()), U"'"); |
| 978 | |
| 979 | auto tensor = it->second; |
| 980 | const size_t bpe = ggml_type_size(ggml_type(ttype)); |
| 981 | |
| 982 | if (ggml_backend_buffer_is_host(tensor->buffer)) { |
| 983 | loader->read(loader->context, tensor->data, n_elements * bpe); |
| 984 | BYTESWAP_TENSOR(tensor); |
| 985 | } else { |
| 986 | read_buf.resize(ggml_nbytes(tensor)); |
| 987 | loader->read(loader->context, read_buf.data(), read_buf.size()); |
| 988 | // For non-host buffers, we'd need to byteswap in the temp buffer |
| 989 | // before copying to device, but as for now we are CPU-only, this path is not taken |
| 990 | ggml_backend_tensor_set(tensor, read_buf.data(), 0, ggml_nbytes(tensor)); |
| 991 | } |
| 992 | model.n_loaded++; |
| 993 | } |
| 994 | |
| 995 | trace (U"Loaded ", model.n_loaded, U"/", model.tensors.size(), U" tensors"); |
| 996 | if (model.n_loaded != model.tensors.size()) |
| 997 | Melder_throw (U"Embedding model incomplete: loaded ", model.n_loaded, U" of ", model.tensors.size(), U" tensors."); |
| 998 | } |
| 999 | |
| 1000 | // ============================================================================ |
| 1001 | // Embedding: Fbank extraction (Kaldi-compatible) |
| 1002 | // ============================================================================ |
| 1003 | static float mel_scale(float freq) { |
| 1004 | return 1127.0f * logf(1.0f + freq / 700.0f); |
| 1005 | } |
| 1006 | |
| 1007 | static void build_mel_filterbank(int num_mel_bins, int padded_window_size, |
| 1008 | float sample_rate, float low_freq, float high_freq, |
| 1009 | std::vector<std::vector<float>> & filterbank) { |
| 1010 | if (high_freq <= 0.0f) high_freq = sample_rate / 2.0f; |
| 1011 | int num_fft_bins = padded_window_size / 2; |
| 1012 | float fft_bin_width = sample_rate / padded_window_size; |
| 1013 | float mel_low = mel_scale(low_freq), mel_high = mel_scale(high_freq); |
| 1014 | int num_bins = num_mel_bins + 2; |
| 1015 | std::vector<float> mel_points(num_bins); |
| 1016 | for (int i = 0; i < num_bins; i++) |
| 1017 | mel_points[i] = mel_low + (mel_high - mel_low) * i / (num_bins - 1); |
| 1018 | filterbank.resize(num_mel_bins); |
| 1019 | for (int m = 0; m < num_mel_bins; m++) { |
| 1020 | float left = mel_points[m], center = mel_points[m+1], right = mel_points[m+2]; |
| 1021 | filterbank[m].assign(num_fft_bins, 0.0f); |
| 1022 | for (int k = 0; k < num_fft_bins; k++) { |
| 1023 | float fmel = mel_scale(fft_bin_width * k); |
| 1024 | if (fmel > left && fmel <= center) |
| 1025 | filterbank[m][k] = (fmel - left) / (center - left); |
| 1026 | else if (fmel > center && fmel < right) |
| 1027 | filterbank[m][k] = (right - fmel) / (right - center); |
| 1028 | } |
| 1029 | } |
| 1030 | } |
| 1031 | |
| 1032 | static void fft_radix2(const float * in, int N, float * out) { |
| 1033 | std::vector<float> buf(2 * N); |
| 1034 | for (int i = 0; i < N; i++) { buf[2*i] = in[i]; buf[2*i+1] = 0.0f; } |
| 1035 | int bits = 0; |
| 1036 | for (int tmp = N; tmp > 1; tmp >>= 1) bits++; |
| 1037 | for (int i = 0; i < N; i++) { |
| 1038 | int j = 0; |
| 1039 | for (int b = 0; b < bits; b++) if (i & (1 << b)) j |= (1 << (bits-1-b)); |
| 1040 | if (j > i) { std::swap(buf[2*i], buf[2*j]); std::swap(buf[2*i+1], buf[2*j+1]); } |
| 1041 | } |
| 1042 | for (int s = 1; s <= bits; s++) { |
| 1043 | int m = 1 << s, hm = m / 2; |
| 1044 | float wm_re = cosf(-2.0f * (float)M_PI / m), wm_im = sinf(-2.0f * (float)M_PI / m); |
| 1045 | for (int k = 0; k < N; k += m) { |
| 1046 | float w_re = 1.0f, w_im = 0.0f; |
| 1047 | for (int j = 0; j < hm; j++) { |
| 1048 | int e = k+j, o = k+j+hm; |
| 1049 | float t_re = w_re*buf[2*o] - w_im*buf[2*o+1], t_im = w_re*buf[2*o+1] + w_im*buf[2*o]; |
| 1050 | buf[2*o] = buf[2*e] - t_re; buf[2*o+1] = buf[2*e+1] - t_im; |
| 1051 | buf[2*e] += t_re; buf[2*e+1] += t_im; |
| 1052 | float nw = w_re*wm_re - w_im*wm_im; w_im = w_re*wm_im + w_im*wm_re; w_re = nw; |
| 1053 | } |
| 1054 | } |
| 1055 | } |
| 1056 | for (int i = 0; i <= N/2; i++) { out[2*i] = buf[2*i]; out[2*i+1] = buf[2*i+1]; } |
| 1057 | } |
| 1058 | |
| 1059 | // Compute fbank features from raw PCM audio |
| 1060 | // Input: samples (float, [-1, 1] normalized), n_samples |
| 1061 | // Output: fbank_out (num_frames × 80), row-major |
| 1062 | static void compute_fbank(const float * samples, int n_samples, |
| 1063 | std::vector<float> & fbank_out, int & num_frames_out) { |
| 1064 | const int sample_rate = 16000; |
| 1065 | const int num_mel_bins = 80; |
| 1066 | const int frame_length = 400; // 25ms |
| 1067 | const int frame_shift = 160; // 10ms |
| 1068 | const int padded_window_size = 512; |
| 1069 | const int n_fft_bins = padded_window_size / 2; |
| 1070 | const float preemphasis = 0.97f; |
| 1071 | const float epsilon = 1.1920928955078125e-07f; |
| 1072 | |
| 1073 | // Scale by 32768 (WeSpeaker convention) |
| 1074 | std::vector<float> scaled(n_samples); |
| 1075 | for (int i = 0; i < n_samples; i++) scaled[i] = samples[i] * 32768.0f; |
| 1076 | |
| 1077 | // Number of frames (snip_edges=true) |
| 1078 | int num_frames = (n_samples >= frame_length) ? 1 + (n_samples - frame_length) / frame_shift : 0; |
| 1079 | num_frames_out = num_frames; |
| 1080 | if (num_frames == 0) { fbank_out.clear(); return; } |
| 1081 | |
| 1082 | // Hamming window |
| 1083 | std::vector<float> hamming(frame_length); |
| 1084 | for (int i = 0; i < frame_length; i++) |
| 1085 | hamming[i] = 0.54f - 0.46f * cosf(2.0f * (float)M_PI * i / (frame_length - 1)); |
| 1086 | |
| 1087 | // Mel filterbank |
| 1088 | std::vector<std::vector<float>> mel_filters; |
| 1089 | build_mel_filterbank(num_mel_bins, padded_window_size, sample_rate, 20.0f, 0.0f, mel_filters); |
| 1090 | |
| 1091 | // Process frames |
| 1092 | fbank_out.resize(num_frames * num_mel_bins); |
| 1093 | std::vector<float> frame(padded_window_size, 0.0f); |
| 1094 | std::vector<float> fft_out(2 * (padded_window_size / 2 + 1)); |
| 1095 | |
| 1096 | for (int f = 0; f < num_frames; f++) { |
| 1097 | int offset = f * frame_shift; |
| 1098 | for (int i = 0; i < frame_length; i++) frame[i] = scaled[offset + i]; |
| 1099 | for (int i = frame_length; i < padded_window_size; i++) frame[i] = 0.0f; |
| 1100 | |
| 1101 | // Remove DC offset |
| 1102 | float dc = 0.0f; |
| 1103 | for (int i = 0; i < frame_length; i++) dc += frame[i]; |
| 1104 | dc /= frame_length; |
| 1105 | for (int i = 0; i < frame_length; i++) frame[i] -= dc; |
| 1106 | |
| 1107 | // Pre-emphasis |
| 1108 | for (int i = frame_length - 1; i > 0; i--) frame[i] -= preemphasis * frame[i-1]; |
| 1109 | frame[0] -= preemphasis * frame[0]; |
| 1110 | |
| 1111 | // Hamming window |
| 1112 | for (int i = 0; i < frame_length; i++) frame[i] *= hamming[i]; |
| 1113 | |
| 1114 | // FFT -> power spectrum |
| 1115 | fft_radix2(frame.data(), padded_window_size, fft_out.data()); |
| 1116 | std::vector<float> power(n_fft_bins + 1); |
| 1117 | for (int k = 0; k <= n_fft_bins; k++) |
| 1118 | power[k] = fft_out[2*k]*fft_out[2*k] + fft_out[2*k+1]*fft_out[2*k+1]; |
| 1119 | |
| 1120 | // Mel filterbank + log |
| 1121 | for (int m = 0; m < num_mel_bins; m++) { |
| 1122 | double sum = 0.0; |
| 1123 | for (int k = 0; k < n_fft_bins; k++) sum += power[k] * mel_filters[m][k]; |
| 1124 | float val = (float)sum; |
| 1125 | if (val < epsilon) val = epsilon; |
| 1126 | fbank_out[f * num_mel_bins + m] = logf(val); |
| 1127 | } |
| 1128 | } |
| 1129 | |
| 1130 | // Cepstral mean normalization |
| 1131 | for (int m = 0; m < num_mel_bins; m++) { |
| 1132 | double sum = 0.0; |
| 1133 | for (int f = 0; f < num_frames; f++) sum += fbank_out[f * num_mel_bins + m]; |
| 1134 | float mean = (float)(sum / num_frames); |
| 1135 | for (int f = 0; f < num_frames; f++) fbank_out[f * num_mel_bins + m] -= mean; |
| 1136 | } |
| 1137 | } |
| 1138 | |
| 1139 | // ============================================================================ |
| 1140 | // Embedding: Conv2d via GGML graph |
| 1141 | // ============================================================================ |
| 1142 | static bool conv2d_forward(ggml_backend_t backend, ggml_tensor * weight, |
| 1143 | const float * input, int N, int IC, int IH, int IW, |
| 1144 | int stride, int padding, |
| 1145 | std::vector<float> & output, int & OH, int & OW, int & OC) { |
| 1146 | OC = (int)weight->ne[3]; |
| 1147 | OH = (IH + 2*padding - (int)weight->ne[1]) / stride + 1; |
| 1148 | OW = (IW + 2*padding - (int)weight->ne[0]) / stride + 1; |
| 1149 | |
| 1150 | ggml_init_params ctx_params = { ggml_tensor_overhead() * CONV2D_MAX_NODES + ggml_graph_overhead(), |
| 1151 | nullptr, true }; |
| 1152 | ggml_context * ctx0 = ggml_init(ctx_params); |
| 1153 | |
| 1154 | ggml_tensor * inp = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, IW, IH, IC, N); |
| 1155 | ggml_set_name(inp, "inp"); ggml_set_input(inp); |
| 1156 | ggml_tensor * conv_out = ggml_conv_2d(ctx0, weight, inp, stride, stride, padding, padding, 1, 1); |
| 1157 | ggml_set_name(conv_out, "conv_out"); ggml_set_output(conv_out); |
| 1158 | |
| 1159 | ggml_cgraph * gf = ggml_new_graph_custom(ctx0, CONV2D_MAX_NODES, false); |
| 1160 | ggml_build_forward_expand(gf, conv_out); |
| 1161 | //GGML_LOG_INFO("conv2d_forward: graph nodes = %d, leafs = %d\n", ggml_graph_n_nodes(gf), gf->n_leafs); |
| 1162 | ggml_gallocr_t galloc = ggml_gallocr_new(ggml_backend_get_default_buffer_type(backend)); |
| 1163 | ggml_gallocr_alloc_graph(galloc, gf); |
| 1164 | ggml_backend_tensor_set(inp, input, 0, N * IC * IH * IW * sizeof(float)); |
| 1165 | ggml_backend_graph_compute(backend, gf); |
| 1166 | |
| 1167 | output.resize(N * OC * OH * OW); |
| 1168 | ggml_backend_tensor_get(conv_out, output.data(), 0, output.size() * sizeof(float)); |
| 1169 | ggml_gallocr_free(galloc); |
| 1170 | ggml_free(ctx0); |
| 1171 | return true; |
| 1172 | } |
| 1173 | |
| 1174 | // ============================================================================ |
| 1175 | // Embedding: Plain C++ ops: BN, ReLU, residual add |
| 1176 | // ============================================================================ |
| 1177 | static void batchnorm2d(float * data, int N, int C, int H, int W, |
| 1178 | const float * w, const float * b, |
| 1179 | const float * mean, const float * var, float eps = 1e-5f) { |
| 1180 | for (int n = 0; n < N; n++) |
| 1181 | for (int c = 0; c < C; c++) { |
| 1182 | float scale = w[c] / sqrtf(var[c] + eps); |
| 1183 | float shift = b[c] - mean[c] * scale; |
| 1184 | float * p = data + ((n*C + c) * H * W); |
| 1185 | for (int i = 0; i < H*W; i++) p[i] = p[i] * scale + shift; |
| 1186 | } |
| 1187 | } |
| 1188 | |
| 1189 | static void apply_bn(embedding_model & m, const std::string & pfx, |
| 1190 | float * data, int N, int C, int H, int W) { |
| 1191 | batchnorm2d(data, N, C, H, W, |
| 1192 | (float*)m.tensors[pfx+".weight"]->data, (float*)m.tensors[pfx+".bias"]->data, |
| 1193 | (float*)m.tensors[pfx+".running_mean"]->data, (float*)m.tensors[pfx+".running_var"]->data); |
| 1194 | } |
| 1195 | |
| 1196 | static void relu_inplace(float * d, int n) { for (int i = 0; i < n; i++) if (d[i] < 0.f) d[i] = 0.f; } |
| 1197 | static void add_inplace(float * a, const float * b, int n) { for (int i = 0; i < n; i++) a[i] += b[i]; } |
| 1198 | |
| 1199 | // ============================================================================ |
| 1200 | // Embedding: BasicBlock forward |
| 1201 | // ============================================================================ |
| 1202 | static bool basic_block_forward(ggml_backend_t backend, embedding_model & model, |
| 1203 | const std::string & prefix, const float * input, |
| 1204 | int N, int in_C, int H, int W, int stride, bool has_shortcut, |
| 1205 | std::vector<float> & output, int & oH, int & oW, int & oC) { |
| 1206 | // Main path: conv1 + bn1 + relu |
| 1207 | std::vector<float> t1; |
| 1208 | int h1, w1, c1; |
| 1209 | conv2d_forward(backend, model.tensors[prefix+".conv1.weight"], input, N, in_C, H, W, stride, 1, t1, h1, w1, c1); |
| 1210 | apply_bn(model, prefix+".bn1", t1.data(), N, c1, h1, w1); |
| 1211 | relu_inplace(t1.data(), t1.size()); |
| 1212 | |
| 1213 | // Main path: conv2 + bn2 |
| 1214 | std::vector<float> t2; |
| 1215 | conv2d_forward(backend, model.tensors[prefix+".conv2.weight"], t1.data(), N, c1, h1, w1, 1, 1, t2, oH, oW, oC); |
| 1216 | apply_bn(model, prefix+".bn2", t2.data(), N, oC, oH, oW); |
| 1217 | |
| 1218 | // Residual |
| 1219 | if (has_shortcut) { |
| 1220 | std::vector<float> sc; |
| 1221 | int sH, sW, sC; |
| 1222 | conv2d_forward(backend, model.tensors[prefix+".shortcut.0.weight"], input, N, in_C, H, W, stride, 0, sc, sH, sW, sC); |
| 1223 | apply_bn(model, prefix+".shortcut.1", sc.data(), N, sC, sH, sW); |
| 1224 | add_inplace(t2.data(), sc.data(), t2.size()); |
| 1225 | } else { |
| 1226 | add_inplace(t2.data(), input, t2.size()); |
| 1227 | } |
| 1228 | relu_inplace(t2.data(), t2.size()); |
| 1229 | output = std::move(t2); |
| 1230 | return true; |
| 1231 | } |
| 1232 | |
| 1233 | // ============================================================================ |
| 1234 | // Embedding: Run a full ResNet layer |
| 1235 | // ============================================================================ |
| 1236 | static bool run_layer(ggml_backend_t backend, embedding_model & model, int layer_idx, |
| 1237 | std::vector<float> & cur, int & N, int & C, int & H, int & W) { |
| 1238 | int out_ch = model.hparams.ch(layer_idx); |
| 1239 | int stride_first = (layer_idx == 1) ? 1 : 2; |
| 1240 | std::string lp = "resnet.layer" + std::to_string(layer_idx); |
| 1241 | |
| 1242 | for (int blk = 0; blk < model.hparams.num_blocks[layer_idx-1]; blk++) { |
| 1243 | std::string prefix = lp + "." + std::to_string(blk); |
| 1244 | int blk_stride = (blk == 0) ? stride_first : 1; |
| 1245 | int blk_in_ch = (blk == 0) ? C : out_ch; |
| 1246 | bool has_sc = (blk == 0) && (blk_stride != 1 || blk_in_ch != out_ch); |
| 1247 | |
| 1248 | std::vector<float> out; |
| 1249 | int bH, bW, bC; |
| 1250 | if (!basic_block_forward(backend, model, prefix, cur.data(), N, blk_in_ch, H, W, |
| 1251 | blk_stride, has_sc, out, bH, bW, bC)) return false; |
| 1252 | cur = std::move(out); |
| 1253 | C = bC; H = bH; W = bW; |
| 1254 | } |
| 1255 | return true; |
| 1256 | } |
| 1257 | |
| 1258 | // ============================================================================ |
| 1259 | // Embedding: TSTP pooling |
| 1260 | // ============================================================================ |
| 1261 | static void tstp_pooling(const float * data, int N, int C, int H, int W, |
| 1262 | std::vector<float> & stats) { |
| 1263 | int feat_dim = C * H; |
| 1264 | stats.resize(N * feat_dim * 2); |
| 1265 | for (int n = 0; n < N; n++) { |
| 1266 | float * mean_out = &stats[n * feat_dim * 2]; |
| 1267 | float * std_out = mean_out + feat_dim; |
| 1268 | for (int c = 0; c < C; c++) { |
| 1269 | for (int h = 0; h < H; h++) { |
| 1270 | const float * p = data + ((n*C + c)*H + h)*W; |
| 1271 | double sum = 0.0; |
| 1272 | for (int w = 0; w < W; w++) sum += (double)p[w]; |
| 1273 | double m = sum / W; |
| 1274 | mean_out[c*H + h] = (float)m; |
| 1275 | double var_sum = 0.0; |
| 1276 | for (int w = 0; w < W; w++) { double d = (double)p[w] - m; var_sum += d*d; } |
| 1277 | std_out[c*H + h] = (float)sqrt(var_sum / (W - 1) + 1e-7); |
| 1278 | } |
| 1279 | } |
| 1280 | } |
| 1281 | } |
| 1282 | |
| 1283 | // ============================================================================ |
| 1284 | // Embedding: Linear layer |
| 1285 | // ============================================================================ |
| 1286 | static void linear_forward(const float * input, int N, int in_dim, |
| 1287 | const float * weight, const float * bias, int out_dim, |
| 1288 | std::vector<float> & output) { |
| 1289 | output.resize(N * out_dim); |
| 1290 | for (int n = 0; n < N; n++) |
| 1291 | for (int o = 0; o < out_dim; o++) { |
| 1292 | float sum = bias ? bias[o] : 0.f; |
| 1293 | for (int i = 0; i < in_dim; i++) |
| 1294 | sum += input[n*in_dim + i] * weight[o*in_dim + i]; |
| 1295 | output[n*out_dim + o] = sum; |
| 1296 | } |
| 1297 | } |
| 1298 | |
| 1299 | // ============================================================================ |
| 1300 | // Embedding: Full forward pass: raw PCM -> 256-d embedding |
| 1301 | // ============================================================================ |
| 1302 | static bool embedding_forward(embedding_context & ectx, |
| 1303 | const float * samples, int n_samples, |
| 1304 | std::vector<float> & embedding_out) { |
| 1305 | //TRACE |
| 1306 | auto & model = ectx.model; |
| 1307 | auto & hp = model.hparams; |
| 1308 | |
| 1309 | auto t0 = std::chrono::high_resolution_clock::now(); |
| 1310 | |
| 1311 | // 1. Fbank extraction |
| 1312 | std::vector<float> fbank; |
| 1313 | int num_frames; |
| 1314 | compute_fbank(samples, n_samples, fbank, num_frames); |
| 1315 | if (num_frames == 0) { |
| 1316 | trace (U"Audio too short for fbank"); |
| 1317 | return false; |
| 1318 | } |
| 1319 | trace (U"fbank: (", num_frames, U", ", hp.feat_dim, U")"); |
| 1320 | |
| 1321 | // 2. Prepare input: transpose (T, F) -> (1, 1, F, T) |
| 1322 | int N = 1, C = 1, H = hp.feat_dim, W = num_frames; |
| 1323 | std::vector<float> cur(N * C * H * W); |
| 1324 | for (int t = 0; t < W; t++) |
| 1325 | for (int f = 0; f < H; f++) |
| 1326 | cur[f * W + t] = fbank[t * H + f]; |
| 1327 | auto t1 = std::chrono::high_resolution_clock::now(); |
| 1328 | |
| 1329 | // 3. Stem: conv1 + bn1 + relu |
| 1330 | { |
| 1331 | std::vector<float> conv_out; |
| 1332 | int OH, OW, OC; |
| 1333 | conv2d_forward(ectx.backend, model.tensors["resnet.conv1.weight"], |
| 1334 | cur.data(), N, C, H, W, 1, 1, conv_out, OH, OW, OC); |
| 1335 | apply_bn(model, "resnet.bn1", conv_out.data(), N, OC, OH, OW); |
| 1336 | relu_inplace(conv_out.data(), conv_out.size()); |
| 1337 | cur = conv_out; C = OC; H = OH; W = OW; |
| 1338 | } |
| 1339 | trace (U"stem: (", N, U", ", C, U", ", H, U", ", W, U")"); |
| 1340 | auto t2 = std::chrono::high_resolution_clock::now(); |
| 1341 | |
| 1342 | // 4. ResNet layers 1-4 |
| 1343 | for (int layer = 1; layer <= 4; layer++) { |
| 1344 | if (!run_layer(ectx.backend, model, layer, cur, N, C, H, W)) return false; |
| 1345 | trace (U"layer ", layer, U": (", N, U", ", C, U", ", H, U", ", W, U")"); |
| 1346 | } |
| 1347 | auto t3 = std::chrono::high_resolution_clock::now(); |
| 1348 | |
| 1349 | // 5. TSTP pooling |
| 1350 | std::vector<float> pool; |
| 1351 | tstp_pooling(cur.data(), N, C, H, W, pool); |
| 1352 | trace (U"pool: (", N, U", ", (int)pool.size() / N, U")"); |
| 1353 | |
| 1354 | // 6. seg_1 linear |
| 1355 | linear_forward(pool.data(), N, (int)pool.size() / N, |
| 1356 | (float*)model.tensors["resnet.seg_1.weight"]->data, |
| 1357 | (float*)model.tensors["resnet.seg_1.bias"]->data, |
| 1358 | hp.embed_dim, embedding_out); |
| 1359 | |
| 1360 | auto t4 = std::chrono::high_resolution_clock::now(); |
| 1361 | |
| 1362 | trace (U"embedding: (", N, U", ", hp.embed_dim, U")"); |
| 1363 | |
| 1364 | if (Melder_debug == 2004) { |
| 1365 | auto us = [](auto a, auto b) { |
| 1366 | return std::chrono::duration_cast<std::chrono::microseconds>(b - a).count(); |
| 1367 | }; |
| 1368 | g_emb_fbank_us += us(t0, t1); |
| 1369 | g_emb_conv1bn1relu_us += us(t1, t2); |
| 1370 | g_emb_resnet_us += us(t2, t3); |
| 1371 | g_emb_tail_us += us(t3, t4); |
| 1372 | ++g_emb_calls; |
| 1373 | } |
| 1374 | |
| 1375 | return true; |
| 1376 | } |
| 1377 | struct ggml_backend_cpu_context; |
| 1378 | // ============================================================================ |
| 1379 | // Embedding: Init / Free |
| 1380 | // ============================================================================ |
| 1381 | static void embedding_init(embedding_context & ectx, diarize_model_loader * loader) { |
| 1382 | //TRACE |
| 1383 | try { |
| 1384 | embedding_load_model(loader, ectx.model); |
| 1385 | } catch (MelderError) { |
| 1386 | Melder_throw (U"Could not load embedding model."); |
| 1387 | } |
| 1388 | |
| 1389 | ectx.backend = ggml_backend_cpu_init(); |
| 1390 | |
| 1391 | trace (U"Embedding model initialized (", ectx.model.n_loaded, U" tensors)"); |
| 1392 | } |
| 1393 | |
| 1394 | static void embedding_free(embedding_context & ectx) { |
| 1395 | if (ectx.backend) |
| 1396 | ggml_backend_free(ectx.backend); |
| 1397 | for (auto buf : ectx.model.buffers) |
| 1398 | ggml_backend_buffer_free(buf); |
| 1399 | for (auto ctx : ectx.model.ctxs) |
| 1400 | ggml_free(ctx); |
| 1401 | } |
| 1402 | |
| 1403 | |
| 1404 | /* |
| 1405 | * Agglomerative clustering + reconstruction. |
| 1406 | */ |
| 1407 | // ============================================================================ |
| 1408 | // Pipeline parameters (from config.yaml) |
| 1409 | // ============================================================================ |
| 1410 | struct diarization_params { |
| 1411 | // Segmentation |
| 1412 | float seg_duration = 10.0f; // chunk duration (seconds) |
| 1413 | float seg_step_ratio = 0.1f; // step = 10% of duration (90% overlap) |
| 1414 | int seg_num_frames = 589; // frames per chunk (segmentation-3.0) |
| 1415 | int seg_num_classes = 7; // powerset classes |
| 1416 | int seg_num_speakers = 3; // max local speakers per chunk |
| 1417 | int seg_max_set_size = 2; // powerset max set size |
| 1418 | |
| 1419 | // Embedding |
| 1420 | int emb_dimension = 256; // WeSpeaker ResNet34 output dim |
| 1421 | int emb_sample_rate = 16000; |
| 1422 | bool emb_exclude_overlap = true; |
| 1423 | |
| 1424 | // Clustering |
| 1425 | double cluster_threshold = 0.7f; // https://huggingface.co/pyannote/speaker-diarization-3.1/blob/main/config.yaml |
| 1426 | int cluster_min_size = 12; |
| 1427 | float min_active_ratio = 0.2f; // for filter_embeddings |
| 1428 | int num_speakers = 0; // unspecified |
| 1429 | int min_speakers = 0; // unspecified |
| 1430 | int max_speakers = 0; // unspecified |
| 1431 | |
| 1432 | // Post-processing |
| 1433 | float min_duration_off = 0.0f; |
| 1434 | |
| 1435 | // Derived |
| 1436 | int seg_step_samples() const { return (int)(seg_duration * seg_step_ratio * emb_sample_rate); } |
| 1437 | int seg_chunk_samples() const { return (int)(seg_duration * emb_sample_rate); } |
| 1438 | int seg_step_frames() const { return (int)(seg_num_frames * seg_step_ratio); } |
| 1439 | }; |
| 1440 | |
| 1441 | // ============================================================================ |
| 1442 | // Output structures |
| 1443 | // ============================================================================ |
| 1444 | struct diarization_segment { |
| 1445 | float start; // seconds |
| 1446 | float end; // seconds |
| 1447 | int speaker; // 0-indexed speaker ID |
| 1448 | }; |
| 1449 | |
| 1450 | struct diarization_result { |
| 1451 | std::vector<diarization_segment> segments; |
| 1452 | int num_speakers; |
| 1453 | }; |
| 1454 | |
| 1455 | // ============================================================================ |
| 1456 | // Powerset -> multilabel conversion |
| 1457 | // |
| 1458 | // segmentation-3.0 uses num_classes=3, max_set_size=2 -> 7 powerset classes: |
| 1459 | // 0: {} -> [0,0,0] |
| 1460 | // 1: {0} -> [1,0,0] |
| 1461 | // 2: {1} -> [0,1,0] |
| 1462 | // 3: {2} -> [0,0,1] |
| 1463 | // 4: {0,1} -> [1,1,0] |
| 1464 | // 5: {0,2} -> [1,0,1] |
| 1465 | // 6: {1,2} -> [0,1,1] |
| 1466 | // |
| 1467 | // Hard conversion: argmax over 7 classes -> lookup in mapping table. |
| 1468 | // ============================================================================ |
| 1469 | |
| 1470 | // Mapping table: powerset_mapping[powerset_class][speaker] = 0 or 1 |
| 1471 | static const int powerset_mapping[7][3] = { |
| 1472 | {0, 0, 0}, // class 0: silence |
| 1473 | {1, 0, 0}, // class 1: speaker 0 |
| 1474 | {0, 1, 0}, // class 2: speaker 1 |
| 1475 | {0, 0, 1}, // class 3: speaker 2 |
| 1476 | {1, 1, 0}, // class 4: speakers 0+1 |
| 1477 | {1, 0, 1}, // class 5: speakers 0+2 |
| 1478 | {0, 1, 1}, // class 6: speakers 1+2 |
| 1479 | }; |
| 1480 | |
| 1481 | // Convert powerset logits -> binary multilabel |
| 1482 | // Input: logits[num_frames * 7] (log-softmax output from segmentation) |
| 1483 | // Output: binary[num_frames * 3] (0.0 or 1.0 per speaker) |
| 1484 | static void powerset_to_multilabel( |
| 1485 | const float * logits, int num_frames, int num_powerset_classes, int num_speakers, |
| 1486 | std::vector<float> & binary |
| 1487 | ) { |
| 1488 | binary.resize(num_frames * num_speakers); |
| 1489 | for (int f = 0; f < num_frames; f++) { |
| 1490 | // Find argmax over powerset classes |
| 1491 | int best_class = 0; |
| 1492 | float best_val = logits[f * num_powerset_classes]; |
| 1493 | for (int c = 1; c < num_powerset_classes; c++) { |
| 1494 | float v = logits[f * num_powerset_classes + c]; |
| 1495 | if (v > best_val) { |
| 1496 | best_val = v; |
| 1497 | best_class = c; |
| 1498 | } |
| 1499 | } |
| 1500 | // Map to multilabel |
| 1501 | for (int s = 0; s < num_speakers; s++) { |
| 1502 | binary[f * num_speakers + s] = (float)powerset_mapping[best_class][s]; |
| 1503 | } |
| 1504 | } |
| 1505 | } |
| 1506 | |
| 1507 | // Convert powerset logits -> soft multilabel probabilities |
| 1508 | // Input: logits[num_chunks * num_frames * 7] (log-softmax from segmentation) |
| 1509 | // Output: soft[num_chunks * num_frames * 3] (soft speaker probabilities) |
| 1510 | // |
| 1511 | // This is the soft=True path from Powerset.to_multilabel(): |
| 1512 | // probs = exp(logits) — convert log-probs to probs |
| 1513 | // multilabel = probs @ mapping — sum probabilities of sets containing each speaker |
| 1514 | // |
| 1515 | // Used for the reconstruct step, which needs continuous scores (not binary). |
| 1516 | static void powerset_to_soft_multilabel( |
| 1517 | const float * logits, int num_chunks, int num_frames, |
| 1518 | int num_powerset_classes, int num_speakers, |
| 1519 | std::vector<float> & soft |
| 1520 | ) { |
| 1521 | soft.resize((size_t)num_chunks * num_frames * num_speakers); |
| 1522 | for (int c = 0; c < num_chunks; c++) { |
| 1523 | for (int f = 0; f < num_frames; f++) { |
| 1524 | const float * row = logits + (c * num_frames + f) * num_powerset_classes; |
| 1525 | float * out = soft.data() + (c * num_frames + f) * num_speakers; |
| 1526 | |
| 1527 | // Initialize output to 0 |
| 1528 | for (int s = 0; s < num_speakers; s++) out[s] = 0.0f; |
| 1529 | |
| 1530 | // probs = exp(logits), then accumulate into speakers via mapping |
| 1531 | for (int p = 0; p < num_powerset_classes; p++) { |
| 1532 | float prob = expf(row[p]); |
| 1533 | for (int s = 0; s < num_speakers; s++) { |
| 1534 | out[s] += prob * (float)powerset_mapping[p][s]; |
| 1535 | } |
| 1536 | } |
| 1537 | } |
| 1538 | } |
| 1539 | } |
| 1540 | |
| 1541 | // ============================================================================ |
| 1542 | // Speaker count from binarized segmentations |
| 1543 | // |
| 1544 | // For overlapping chunks, count how many speakers are active per global frame. |
| 1545 | // Uses simple overlap-add of per-chunk speaker counts. |
| 1546 | // ============================================================================ |
| 1547 | static void compute_speaker_count( |
| 1548 | const float * binarized_segs, // [num_chunks, num_frames, num_speakers] |
| 1549 | int num_chunks, int num_frames, int num_speakers, |
| 1550 | int chunk_step_frames, int total_frames, |
| 1551 | std::vector<int32_t> & count // [total_frames] |
| 1552 | ) { |
| 1553 | // Sum speakers per frame, then aggregate over overlapping chunks |
| 1554 | std::vector<double> sum(total_frames, 0.0); |
| 1555 | std::vector<double> cnt(total_frames, 0.0); |
| 1556 | |
| 1557 | for (int c = 0; c < num_chunks; c++) { |
| 1558 | int start = c * chunk_step_frames; |
| 1559 | int end = std::min(start + num_frames, total_frames); |
| 1560 | for (int f = 0; f < end - start; f++) { |
| 1561 | float spk_count = 0.0f; |
| 1562 | for (int s = 0; s < num_speakers; s++) { |
| 1563 | spk_count += binarized_segs[(c * num_frames + f) * num_speakers + s]; |
| 1564 | } |
| 1565 | sum[start + f] += spk_count; |
| 1566 | cnt[start + f] += 1.0; |
| 1567 | } |
| 1568 | } |
| 1569 | |
| 1570 | count.resize(total_frames); |
| 1571 | for (int f = 0; f < total_frames; f++) { |
| 1572 | count[f] = (cnt[f] > 0) ? (int32_t)std::round(sum[f] / cnt[f]) : 0; |
| 1573 | } |
| 1574 | } |
| 1575 | |
| 1576 | // ============================================================================ |
| 1577 | // Filter embeddings |
| 1578 | // |
| 1579 | // Keep only embeddings where: |
| 1580 | // - The speaker has ≥ min_active_ratio non-overlapping (clean) frames |
| 1581 | // - The embedding is not NaN |
| 1582 | // ============================================================================ |
| 1583 | struct filter_result { |
| 1584 | std::vector<float> filtered_embeddings; // [num_filtered * dim] |
| 1585 | std::vector<int32_t> chunk_idx; |
| 1586 | std::vector<int32_t> speaker_idx; |
| 1587 | int num_filtered; |
| 1588 | }; |
| 1589 | |
| 1590 | static filter_result filter_embeddings( |
| 1591 | const float * embeddings, // [num_chunks * num_speakers * dim] |
| 1592 | const float * segmentations, // [num_chunks * num_frames * num_speakers] |
| 1593 | int num_chunks, int num_frames, int num_speakers, int dim, |
| 1594 | float min_active_ratio |
| 1595 | ) { |
| 1596 | filter_result result; |
| 1597 | result.num_filtered = 0; |
| 1598 | |
| 1599 | for (int c = 0; c < num_chunks; c++) { |
| 1600 | for (int s = 0; s < num_speakers; s++) { |
| 1601 | // Check NaN |
| 1602 | const float * emb = embeddings + (c * num_speakers + s) * dim; |
| 1603 | bool has_nan = false; |
| 1604 | for (int d = 0; d < dim; d++) { |
| 1605 | if (std::isnan(emb[d])) { has_nan = true; break; } |
| 1606 | } |
| 1607 | if (has_nan) continue; |
| 1608 | |
| 1609 | // Count clean frames (non-overlapping) |
| 1610 | int num_clean = 0; |
| 1611 | for (int f = 0; f < num_frames; f++) { |
| 1612 | const float * frame = segmentations + (c * num_frames + f) * num_speakers; |
| 1613 | if (frame[s] <= 0.0f) continue; |
| 1614 | float total = 0.0f; |
| 1615 | for (int ss = 0; ss < num_speakers; ss++) total += frame[ss]; |
| 1616 | if (total == 1.0f) num_clean++; |
| 1617 | } |
| 1618 | |
| 1619 | if ((float)num_clean < min_active_ratio * num_frames) continue; |
| 1620 | |
| 1621 | result.chunk_idx.push_back(c); |
| 1622 | result.speaker_idx.push_back(s); |
| 1623 | for (int d = 0; d < dim; d++) { |
| 1624 | result.filtered_embeddings.push_back(emb[d]); |
| 1625 | } |
| 1626 | result.num_filtered++; |
| 1627 | } |
| 1628 | } |
| 1629 | return result; |
| 1630 | } |
| 1631 | |
| 1632 | // ============================================================================ |
| 1633 | // Agglomerative clustering (centroid linkage) |
| 1634 | // ============================================================================ |
| 1635 | static void l2_normalize_f32_to_f64(const float * src, double * dst, int dim) { |
| 1636 | double norm = 0.0; |
| 1637 | for (int j = 0; j < dim; j++) { double v = (double)src[j]; norm += v * v; } |
| 1638 | norm = std::sqrt(norm); |
| 1639 | if (norm > 0.0) { |
| 1640 | for (int j = 0; j < dim; j++) dst[j] = (double)src[j] / norm; |
| 1641 | } else { |
| 1642 | for (int j = 0; j < dim; j++) dst[j] = (double)src[j]; |
| 1643 | } |
| 1644 | } |
| 1645 | |
| 1646 | static double euclidean_dist(const double * a, const double * b, int dim) { |
| 1647 | double s = 0.0; |
| 1648 | for (int j = 0; j < dim; j++) { double d = a[j] - b[j]; s += d * d; } |
| 1649 | return std::sqrt(s); |
| 1650 | } |
| 1651 | |
| 1652 | static double cosine_distance(const double * a, const double * b, int dim) { |
| 1653 | double dot = 0.0, na = 0.0, nb = 0.0; |
| 1654 | for (int j = 0; j < dim; j++) { dot += a[j]*b[j]; na += a[j]*a[j]; nb += b[j]*b[j]; } |
| 1655 | double denom = std::sqrt(na) * std::sqrt(nb); |
| 1656 | return (denom < 1e-30) ? 1.0 : 1.0 - dot / denom; |
| 1657 | } |
| 1658 | |
| 1659 | struct linkage_merge { double idx1, idx2, distance, count; }; |
| 1660 | |
| 1661 | static void centroid_linkage(const double * emb, int n, int dim, |
| 1662 | std::vector<linkage_merge> & dendrogram) { |
| 1663 | dendrogram.resize(n - 1); |
| 1664 | int max_cl = 2 * n - 1; |
| 1665 | std::vector<double> centroids(max_cl * dim); |
| 1666 | std::vector<int> counts(max_cl, 0); |
| 1667 | std::vector<bool> active(max_cl, false); |
| 1668 | |
| 1669 | for (int i = 0; i < n; i++) { |
| 1670 | for (int j = 0; j < dim; j++) centroids[i * dim + j] = emb[i * dim + j]; |
| 1671 | counts[i] = 1; active[i] = true; |
| 1672 | } |
| 1673 | |
| 1674 | for (int step = 0; step < n - 1; step++) { |
| 1675 | double best_d = 1e30; int bi = -1, bj = -1; |
| 1676 | for (int i = 0; i < n + step; i++) { |
| 1677 | if (!active[i]) continue; |
| 1678 | for (int j = i + 1; j < n + step; j++) { |
| 1679 | if (!active[j]) continue; |
| 1680 | double d = euclidean_dist(centroids.data()+i*dim, centroids.data()+j*dim, dim); |
| 1681 | if (d < best_d) { best_d = d; bi = i; bj = j; } |
| 1682 | } |
| 1683 | } |
| 1684 | int ni = n + step; |
| 1685 | dendrogram[step] = {(double)bi, (double)bj, best_d, (double)(counts[bi]+counts[bj])}; |
| 1686 | int nc = counts[bi] + counts[bj]; |
| 1687 | for (int j = 0; j < dim; j++) |
| 1688 | centroids[ni*dim+j] = (counts[bi]*centroids[bi*dim+j]+counts[bj]*centroids[bj*dim+j])/nc; |
| 1689 | counts[ni] = nc; active[bi] = false; active[bj] = false; active[ni] = true; |
| 1690 | } |
| 1691 | } |
| 1692 | |
| 1693 | static void fcluster_distance(const std::vector<linkage_merge> & dend, int n, double threshold, |
| 1694 | std::vector<int32_t> & labels) { |
| 1695 | int mx = 2 * n - 1; |
| 1696 | std::vector<int> parent(mx); |
| 1697 | for (int i = 0; i < mx; i++) parent[i] = i; |
| 1698 | auto find = [&](int x) -> int { |
| 1699 | while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; |
| 1700 | }; |
| 1701 | for (int i = 0; i < n - 1; i++) { |
| 1702 | int a = (int)dend[i].idx1, b = (int)dend[i].idx2, ni = n + i; |
| 1703 | parent[ni] = ni; |
| 1704 | if (dend[i].distance <= threshold) { parent[find(a)] = ni; parent[find(b)] = ni; } |
| 1705 | } |
| 1706 | labels.resize(n); |
| 1707 | for (int i = 0; i < n; i++) labels[i] = find(i); |
| 1708 | // Renumber 0..K-1 |
| 1709 | std::vector<int> uq; |
| 1710 | for (int i = 0; i < n; i++) { |
| 1711 | bool found = false; |
| 1712 | for (int u : uq) { if (u == labels[i]) { found = true; break; } } |
| 1713 | if (!found) uq.push_back(labels[i]); |
| 1714 | } |
| 1715 | std::vector<int> mp(mx, -1); |
| 1716 | for (int k = 0; k < (int)uq.size(); k++) mp[uq[k]] = k; |
| 1717 | for (int i = 0; i < n; i++) labels[i] = mp[labels[i]]; |
| 1718 | } |
| 1719 | |
| 1720 | // Variant of fcluster_distance that cuts the dendrogram at an iteration |
| 1721 | // index instead of a distance. Performs merges 0..cut_index inclusive, |
| 1722 | // then assigns connected components. |
| 1723 | // Mirrors pyannote's clustering.py:407-408 + fcluster trick: |
| 1724 | // _dendrogram[:, 2] = np.arange(num_embeddings - 1) |
| 1725 | // fcluster(_dendrogram, iteration, criterion="distance") |
| 1726 | static void fcluster_byiteration(const std::vector<linkage_merge> & dend, int n, |
| 1727 | int cut_index, |
| 1728 | std::vector<int32_t> & labels) { |
| 1729 | int mx = 2 * n - 1; |
| 1730 | std::vector<int> parent(mx); |
| 1731 | for (int i = 0; i < mx; i++) parent[i] = i; |
| 1732 | auto find = [&](int x) -> int { |
| 1733 | while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; |
| 1734 | }; |
| 1735 | for (int i = 0; i < n - 1; i++) { |
| 1736 | int a = (int)dend[i].idx1, b = (int)dend[i].idx2, ni = n + i; |
| 1737 | parent[ni] = ni; |
| 1738 | if (i <= cut_index) { parent[find(a)] = ni; parent[find(b)] = ni; } |
| 1739 | } |
| 1740 | labels.resize(n); |
| 1741 | for (int i = 0; i < n; i++) labels[i] = find(i); |
| 1742 | // Renumber 0..K-1 (same as fcluster_distance) |
| 1743 | std::vector<int> uq; |
| 1744 | for (int i = 0; i < n; i++) { |
| 1745 | bool found = false; |
| 1746 | for (int u : uq) { if (u == labels[i]) { found = true; break; } } |
| 1747 | if (!found) uq.push_back(labels[i]); |
| 1748 | } |
| 1749 | std::vector<int> mp(mx, -1); |
| 1750 | for (int k = 0; k < (int)uq.size(); k++) mp[uq[k]] = k; |
| 1751 | for (int i = 0; i < n; i++) labels[i] = mp[labels[i]]; |
| 1752 | } |
| 1753 | |
| 1754 | // Helper: count "large" clusters (size >= min_cluster_size) given labels. |
| 1755 | static int count_large_clusters(const std::vector<int32_t> & labels, int min_cluster_size) { |
| 1756 | std::map<int32_t, int> counts; |
| 1757 | for (auto l : labels) counts[l]++; |
| 1758 | int n_large = 0; |
| 1759 | for (auto & [_, c] : counts) if (c >= min_cluster_size) n_large++; |
| 1760 | return n_large; |
| 1761 | } |
| 1762 | |
| 1763 | // Normalize cluster-count constraints. Mirrors pyannote's |
| 1764 | // AgglomerativeClustering.set_num_clusters (clustering.py:54). |
| 1765 | // num, min, max are 0 when "not specified" by the caller. |
| 1766 | // On return, min and max are valid (1 <= min <= max <= n_embeddings) |
| 1767 | // and num is either 0 (range) or >0 (force exact count). |
| 1768 | static void set_num_clusters(int num_embeddings, |
| 1769 | int & num_clusters, |
| 1770 | int & min_clusters, |
| 1771 | int & max_clusters) { |
| 1772 | // pyannote: min_clusters = num_clusters or min_clusters or 1 |
| 1773 | if (num_clusters > 0) min_clusters = num_clusters; |
| 1774 | else if (min_clusters <= 0) min_clusters = 1; |
| 1775 | min_clusters = std::max(1, std::min(num_embeddings, min_clusters)); |
| 1776 | |
| 1777 | // pyannote: max_clusters = num_clusters or max_clusters or num_embeddings |
| 1778 | if (num_clusters > 0) max_clusters = num_clusters; |
| 1779 | else if (max_clusters <= 0) max_clusters = num_embeddings; |
| 1780 | max_clusters = std::max(1, std::min(num_embeddings, max_clusters)); |
| 1781 | |
| 1782 | if (min_clusters > max_clusters) |
| 1783 | Melder_throw (U"min_speakers must be <= max_speakers (got min=", min_clusters, |
| 1784 | U", max=", max_clusters, U")."); |
| 1785 | |
| 1786 | if (min_clusters == max_clusters) |
| 1787 | num_clusters = min_clusters; |
| 1788 | } |
| 1789 | |
| 1790 | static std::vector<int32_t> agglomerative_cluster( |
| 1791 | const float * embeddings_raw, int n, int dim, |
| 1792 | double threshold, int min_cluster_size_param, |
| 1793 | int num_clusters_in, // 0 = unspecified |
| 1794 | int min_clusters_in, // 0 = unspecified |
| 1795 | int max_clusters_in // 0 = unspecified |
| 1796 | ) { |
| 1797 | int mcs = std::min(min_cluster_size_param, std::max(1, (int)std::round(0.1 * n))); |
| 1798 | |
| 1799 | if (n == 1) return {0}; |
| 1800 | |
| 1801 | // Normalize cluster-count constraints (mirrors clustering.py:259-263). |
| 1802 | int num_clusters = num_clusters_in; |
| 1803 | int min_clusters = min_clusters_in; |
| 1804 | int max_clusters = max_clusters_in; |
| 1805 | set_num_clusters(n, num_clusters, min_clusters, max_clusters); |
| 1806 | |
| 1807 | // L2-normalize |
| 1808 | std::vector<double> emb(n * dim); |
| 1809 | for (int i = 0; i < n; i++) |
| 1810 | l2_normalize_f32_to_f64(embeddings_raw + i * dim, emb.data() + i * dim, dim); |
| 1811 | |
| 1812 | // Centroid linkage |
| 1813 | std::vector<linkage_merge> dend; |
| 1814 | centroid_linkage(emb.data(), n, dim, dend); |
| 1815 | |
| 1816 | // Initial cut at threshold (clustering.py:385) |
| 1817 | std::vector<int32_t> clusters; |
| 1818 | fcluster_distance(dend, n, threshold, clusters); |
| 1819 | |
| 1820 | // Count large clusters (clustering.py:387-394) |
| 1821 | int n_large = count_large_clusters(clusters, mcs); |
| 1822 | |
| 1823 | // Force num_clusters from min/max bounds when threshold cut is out of range |
| 1824 | // (clustering.py:396-402). |
| 1825 | if (n_large < min_clusters) num_clusters = min_clusters; |
| 1826 | else if (n_large > max_clusters) num_clusters = max_clusters; |
| 1827 | |
| 1828 | // If num_clusters is now constrained and the threshold cut doesn't already |
| 1829 | // produce that count, search the dendrogram for the best alternative cut |
| 1830 | // (clustering.py:405-451). |
| 1831 | if (num_clusters > 0 && n_large != num_clusters) { |
| 1832 | // Sort iteration indices by |dend[i].distance - threshold| (closest first) |
| 1833 | std::vector<int> order (n - 1); |
| 1834 | for (int i = 0; i < n - 1; i++) order[i] = i; |
| 1835 | std::sort (order.begin(), order.end(), [&](int a, int b) { |
| 1836 | return std::abs(dend[a].distance - threshold) |
| 1837 | < std::abs(dend[b].distance - threshold); |
| 1838 | }); |
| 1839 | |
| 1840 | int best_iteration = n - 2; // default: cut after all merges (1 cluster) |
| 1841 | int best_n_large = 1; |
| 1842 | std::vector<int32_t> best_clusters = std::vector<int32_t>(n, 0); |
| 1843 | |
| 1844 | for (int it : order) { |
| 1845 | // Skip merges where the new cluster would be too small |
| 1846 | // (clustering.py:419-421). |
| 1847 | int new_size = (int) dend[it].count; |
| 1848 | if (new_size < mcs) continue; |
| 1849 | |
| 1850 | std::vector<int32_t> trial; |
| 1851 | fcluster_byiteration(dend, n, it, trial); |
| 1852 | int n_l = count_large_clusters(trial, mcs); |
| 1853 | |
| 1854 | if (std::abs(n_l - num_clusters) < std::abs(best_n_large - num_clusters)) { |
| 1855 | best_iteration = it; |
| 1856 | best_n_large = n_l; |
| 1857 | best_clusters = std::move(trial); |
| 1858 | } |
| 1859 | if (n_l == num_clusters) break; // perfect candidate |
| 1860 | } |
| 1861 | |
| 1862 | clusters = std::move(best_clusters); |
| 1863 | n_large = best_n_large; |
| 1864 | |
| 1865 | const bool max_only_constraint = (num_clusters_in == 0 && min_clusters_in == 0 && max_clusters_in > 0); |
| 1866 | if (!max_only_constraint && num_clusters > 0 && n_large != num_clusters) |
| 1867 | Melder_warning (U"Diarization: detected only ", n_large, U" speakers (requested ", num_clusters, U")."); |
| 1868 | } |
| 1869 | |
| 1870 | // Large/small split |
| 1871 | std::map<int32_t, int> cc; |
| 1872 | for (int i = 0; i < n; i++) cc[clusters[i]]++; |
| 1873 | std::vector<int32_t> large, small; |
| 1874 | for (auto & [l, c] : cc) { if (c >= mcs) large.push_back(l); else small.push_back(l); } |
| 1875 | |
| 1876 | if (large.empty()) { |
| 1877 | return std::vector<int32_t>(n, 0); |
| 1878 | } |
| 1879 | |
| 1880 | if (!small.empty()) { |
| 1881 | // Reassign small -> nearest large (cosine distance between centroids) |
| 1882 | int nl = (int)large.size(), ns = (int)small.size(); |
| 1883 | std::vector<double> lc(nl * dim, 0.0), sc(ns * dim, 0.0); |
| 1884 | std::vector<int> lcnt(nl, 0), scnt(ns, 0); |
| 1885 | for (int i = 0; i < n; i++) { |
| 1886 | for (int k = 0; k < nl; k++) if (clusters[i] == large[k]) { |
| 1887 | for (int j = 0; j < dim; j++) lc[k*dim+j] += emb[i*dim+j]; |
| 1888 | lcnt[k]++; break; |
| 1889 | } |
| 1890 | for (int k = 0; k < ns; k++) if (clusters[i] == small[k]) { |
| 1891 | for (int j = 0; j < dim; j++) sc[k*dim+j] += emb[i*dim+j]; |
| 1892 | scnt[k]++; break; |
| 1893 | } |
| 1894 | } |
| 1895 | for (int k = 0; k < nl; k++) for (int j = 0; j < dim; j++) lc[k*dim+j] /= lcnt[k]; |
| 1896 | for (int k = 0; k < ns; k++) for (int j = 0; j < dim; j++) sc[k*dim+j] /= scnt[k]; |
| 1897 | |
| 1898 | for (int sk = 0; sk < ns; sk++) { |
| 1899 | double bd = 1e30; int blk = 0; |
| 1900 | for (int lk = 0; lk < nl; lk++) { |
| 1901 | double d = cosine_distance(lc.data()+lk*dim, sc.data()+sk*dim, dim); |
| 1902 | if (d < bd) { bd = d; blk = lk; } |
| 1903 | } |
| 1904 | int ol = small[sk], nl_ = large[blk]; |
| 1905 | for (int i = 0; i < n; i++) if (clusters[i] == ol) clusters[i] = nl_; |
| 1906 | } |
| 1907 | } |
| 1908 | |
| 1909 | // Renumber |
| 1910 | std::vector<int32_t> us; |
| 1911 | { auto t = clusters; std::sort(t.begin(),t.end()); t.erase(std::unique(t.begin(),t.end()),t.end()); us = t; } |
| 1912 | std::map<int32_t,int32_t> rm; |
| 1913 | for (int k = 0; k < (int)us.size(); k++) rm[us[k]] = k; |
| 1914 | for (int i = 0; i < n; i++) clusters[i] = rm[clusters[i]]; |
| 1915 | return clusters; |
| 1916 | } |
| 1917 | |
| 1918 | // ============================================================================ |
| 1919 | // Assign embeddings — compute centroids, then assign ALL embeddings |
| 1920 | // ============================================================================ |
| 1921 | struct assign_result { |
| 1922 | std::vector<int32_t> hard_clusters; // [num_chunks * num_speakers] |
| 1923 | std::vector<double> centroids; // [num_clusters * dim] |
| 1924 | int num_clusters; |
| 1925 | }; |
| 1926 | |
| 1927 | static assign_result assign_embeddings( |
| 1928 | const float * embeddings, // [num_chunks * num_speakers * dim] |
| 1929 | int num_chunks, int num_speakers, int dim, |
| 1930 | const int32_t * chunk_idx, const int32_t * speaker_idx, |
| 1931 | const int32_t * train_clusters, int num_train |
| 1932 | ) { |
| 1933 | int num_clusters = 0; |
| 1934 | for (int i = 0; i < num_train; i++) |
| 1935 | num_clusters = std::max(num_clusters, train_clusters[i] + 1); |
| 1936 | |
| 1937 | assign_result r; |
| 1938 | r.num_clusters = num_clusters; |
| 1939 | r.centroids.resize(num_clusters * dim, 0.0); |
| 1940 | std::vector<int> cc(num_clusters, 0); |
| 1941 | |
| 1942 | for (int i = 0; i < num_train; i++) { |
| 1943 | int c = chunk_idx[i], s = speaker_idx[i], k = train_clusters[i]; |
| 1944 | const float * e = embeddings + (c * num_speakers + s) * dim; |
| 1945 | for (int d = 0; d < dim; d++) r.centroids[k*dim+d] += (double)e[d]; |
| 1946 | cc[k]++; |
| 1947 | } |
| 1948 | for (int k = 0; k < num_clusters; k++) |
| 1949 | if (cc[k] > 0) for (int d = 0; d < dim; d++) r.centroids[k*dim+d] /= cc[k]; |
| 1950 | |
| 1951 | int total = num_chunks * num_speakers; |
| 1952 | r.hard_clusters.resize(total); |
| 1953 | for (int cs = 0; cs < total; cs++) { |
| 1954 | const float * e = embeddings + cs * dim; |
| 1955 | std::vector<double> ef(dim); |
| 1956 | for (int d = 0; d < dim; d++) ef[d] = (double)e[d]; |
| 1957 | int bk = 0; double bs = -1e30; |
| 1958 | for (int k = 0; k < num_clusters; k++) { |
| 1959 | double dist = cosine_distance(ef.data(), r.centroids.data()+k*dim, dim); |
| 1960 | double score = 2.0 - dist; |
| 1961 | if (score > bs) { bs = score; bk = k; } |
| 1962 | } |
| 1963 | r.hard_clusters[cs] = bk; |
| 1964 | } |
| 1965 | return r; |
| 1966 | } |
| 1967 | |
| 1968 | // ============================================================================ |
| 1969 | // Reconstruct — remap local speakers -> global clusters |
| 1970 | // ============================================================================ |
| 1971 | struct reconstruct_result { |
| 1972 | std::vector<float> clustered; // [num_chunks * num_frames * num_global] |
| 1973 | std::vector<int8_t> nan_mask; // 1=NaN, 0=valid |
| 1974 | int num_global_speakers; |
| 1975 | }; |
| 1976 | |
| 1977 | static reconstruct_result reconstruct( |
| 1978 | const float * segmentations, // [num_chunks * num_frames * local_num_speakers] |
| 1979 | const int32_t * hard_clusters, // [num_chunks * local_num_speakers] |
| 1980 | int num_chunks, int num_frames, int local_num_speakers |
| 1981 | ) { |
| 1982 | int ng = 0; |
| 1983 | for (int i = 0; i < num_chunks * local_num_speakers; i++) |
| 1984 | if (hard_clusters[i] >= 0) ng = std::max(ng, hard_clusters[i] + 1); |
| 1985 | |
| 1986 | reconstruct_result r; |
| 1987 | r.num_global_speakers = ng; |
| 1988 | size_t total = (size_t)num_chunks * num_frames * ng; |
| 1989 | r.clustered.resize(total, -1.0f); |
| 1990 | r.nan_mask.resize(total, 1); |
| 1991 | |
| 1992 | for (int c = 0; c < num_chunks; c++) { |
| 1993 | for (int k = 0; k < ng; k++) { |
| 1994 | for (int f = 0; f < num_frames; f++) { |
| 1995 | float mx = -1e30f; bool found = false; |
| 1996 | for (int s = 0; s < local_num_speakers; s++) { |
| 1997 | if (hard_clusters[c * local_num_speakers + s] == k) { |
| 1998 | float v = segmentations[(c * num_frames + f) * local_num_speakers + s]; |
| 1999 | if (!found || v > mx) { mx = v; found = true; } |
| 2000 | } |
| 2001 | } |
| 2002 | size_t idx = (c * num_frames + f) * ng + k; |
| 2003 | if (found) { r.clustered[idx] = mx; r.nan_mask[idx] = 0; } |
| 2004 | } |
| 2005 | } |
| 2006 | } |
| 2007 | return r; |
| 2008 | } |
| 2009 | |
| 2010 | // ============================================================================ |
| 2011 | // Aggregate overlapping windows |
| 2012 | // |
| 2013 | // Because chunks overlap, a single global-timeline frame is covered by several |
| 2014 | // chunks. For each global (frame, speaker) we average the activation over only |
| 2015 | // the chunks that actually have data for that speaker (missing entries are |
| 2016 | // skipped). Result: one activation score per (frame, speaker) over the whole |
| 2017 | // timeline. |
| 2018 | // ============================================================================ |
| 2019 | static std::vector<float> aggregate_overlapping( |
| 2020 | const float * frame_activations, // [chunk][frame][speaker], flattened |
| 2021 | const int8_t * is_missing_in_frame, // [chunk][frame][speaker]; 1 = no data |
| 2022 | int n_chunks, |
| 2023 | int n_frames_per_chunk, // frames produced per chunk (e.g. 589) |
| 2024 | int n_global_speakers, // number of global speakers (clusters) |
| 2025 | int segmentation_step_in_frames, // frame offset between consecutive chunks |
| 2026 | int n_total_frames // length of the global timeline, in frames |
| 2027 | ) { |
| 2028 | std::vector<double> activation_sum(n_total_frames * n_global_speakers, 0.0); |
| 2029 | std::vector<int> contributor_count(n_total_frames * n_global_speakers, 0); |
| 2030 | |
| 2031 | for (int chunk = 0; chunk < n_chunks; chunk++) { |
| 2032 | // Where this chunk sits on the global timeline (in frames), and where it ends |
| 2033 | // (clipped, because the last chunk may run past the timeline). |
| 2034 | const int chunk_start = chunk * segmentation_step_in_frames; |
| 2035 | const int chunk_end = std::min(chunk_start + n_frames_per_chunk, n_total_frames); |
| 2036 | |
| 2037 | for (int local_frame = 0; local_frame < chunk_end - chunk_start; local_frame++) { |
| 2038 | const int global_frame = chunk_start + local_frame; |
| 2039 | |
| 2040 | for (int speaker = 0; speaker < n_global_speakers; speaker++) { |
| 2041 | const size_t src = ((size_t) chunk * n_frames_per_chunk + local_frame) * n_global_speakers + speaker; |
| 2042 | const size_t dst = ((size_t) global_frame) * n_global_speakers + speaker; |
| 2043 | |
| 2044 | if (is_missing_in_frame[src] == 0) { // this chunk has an opinion here |
| 2045 | activation_sum [dst] += (double) frame_activations[src]; |
| 2046 | contributor_count[dst] += 1; |
| 2047 | } |
| 2048 | } |
| 2049 | } |
| 2050 | } |
| 2051 | |
| 2052 | // Average each summed activation by how many chunks contributed to it. |
| 2053 | // A (frame, speaker) that no chunk had data for stays at 0. |
| 2054 | std::vector<float> averaged_activations(n_total_frames * n_global_speakers); |
| 2055 | for (int i = 0; i < n_total_frames * n_global_speakers; i++) { |
| 2056 | averaged_activations[i] = (contributor_count[i] > 0) |
| 2057 | ? (float) (activation_sum[i] / contributor_count[i]) |
| 2058 | : 0.0f; |
| 2059 | } |
| 2060 | return averaged_activations; |
| 2061 | } |
| 2062 | |
| 2063 | // ============================================================================ |
| 2064 | // to_diarization — top-N speaker selection per frame |
| 2065 | // ============================================================================ |
| 2066 | static std::vector<float> to_diarization( |
| 2067 | const float * act, const int32_t * count, int total_frames, int ns |
| 2068 | ) { |
| 2069 | std::vector<float> bin(total_frames * ns, 0.0f); |
| 2070 | std::vector<int> idx(ns); |
| 2071 | for (int t = 0; t < total_frames; t++) { |
| 2072 | int c = count[t]; if (c <= 0) continue; |
| 2073 | for (int s = 0; s < ns; s++) idx[s] = s; |
| 2074 | std::sort(idx.begin(), idx.end(), [&](int a, int b) { |
| 2075 | return act[t*ns+a] > act[t*ns+b]; |
| 2076 | }); |
| 2077 | for (int i = 0; i < std::min(c, ns); i++) bin[t*ns+idx[i]] = 1.0f; |
| 2078 | } |
| 2079 | return bin; |
| 2080 | } |
| 2081 | |
| 2082 | // ============================================================================ |
| 2083 | // to_annotation — binary frames -> time-stamped segments |
| 2084 | // ============================================================================ |
| 2085 | static std::vector<diarization_segment> to_annotation( |
| 2086 | const float * binary, int total_frames, int ns, float frame_step |
| 2087 | ) { |
| 2088 | std::vector<diarization_segment> segs; |
| 2089 | for (int s = 0; s < ns; s++) { |
| 2090 | bool in_seg = false; int sf = 0; |
| 2091 | for (int t = 0; t < total_frames; t++) { |
| 2092 | bool a = binary[t*ns+s] >= 0.5f; |
| 2093 | if (a && !in_seg) { sf = t; in_seg = true; } |
| 2094 | else if (!a && in_seg) { |
| 2095 | segs.push_back({sf * frame_step, t * frame_step, s}); |
| 2096 | in_seg = false; |
| 2097 | } |
| 2098 | } |
| 2099 | if (in_seg) segs.push_back({sf * frame_step, total_frames * frame_step, s}); |
| 2100 | } |
| 2101 | std::sort(segs.begin(), segs.end(), [](auto & a, auto & b) { |
| 2102 | if (std::abs(a.start-b.start) > 1e-6f) return a.start < b.start; |
| 2103 | return a.speaker < b.speaker; |
| 2104 | }); |
| 2105 | return segs; |
| 2106 | } |
| 2107 | |
| 2108 | // ============================================================================ |
| 2109 | // Full diarization pipeline (clustering + reconstruction) |
| 2110 | // |
| 2111 | // This is the function you call after running segmentation and embedding |
| 2112 | // models on all chunks. It takes: |
| 2113 | // - binarized segmentations from powerset conversion |
| 2114 | // - raw segmentation scores (for reconstruct) |
| 2115 | // - embeddings from the WeSpeaker model |
| 2116 | // And returns time-stamped speaker segments. |
| 2117 | // ============================================================================ |
| 2118 | static diarization_result run_diarization_pipeline( |
| 2119 | const float * powerset_logits, // [num_chunks * num_frames * num_powerset_classes] log-softmax |
| 2120 | const float * binarized_segmentations, // [num_chunks * num_frames * num_speakers] binary |
| 2121 | const float * embeddings, // [num_chunks * num_speakers * emb_dim] |
| 2122 | int num_chunks, |
| 2123 | int num_frames, |
| 2124 | int num_powerset_classes, // powerset classes (7) |
| 2125 | int num_speakers, // local speakers per chunk (3) |
| 2126 | int emb_dim, |
| 2127 | const diarization_params & params, |
| 2128 | int max_simultaneous_speakers // per-frame cap |
| 2129 | ) { |
| 2130 | //TRACE |
| 2131 | int step_frames = params.seg_step_frames(); |
| 2132 | int total_frames = (num_chunks - 1) * step_frames + num_frames; |
| 2133 | float frame_step = params.seg_duration / num_frames; |
| 2134 | |
| 2135 | trace (U"diarize: ", num_chunks, U" chunks, ", num_frames, U" frames/chunk, step=", |
| 2136 | step_frames, U", total=", total_frames, U" frames"); |
| 2137 | |
| 2138 | // --- Convert powerset logits -> soft multilabel for reconstruct --- |
| 2139 | // pyannote's Inference (with skip_conversion=False) returns soft multilabel |
| 2140 | // probabilities (3-class), which are then used in the reconstruct step. |
| 2141 | // Our C++ segmentation model outputs raw 7-class log-softmax, so we need |
| 2142 | // to convert: probs = exp(logits), then multilabel = probs @ mapping. |
| 2143 | std::vector<float> soft_segmentations; |
| 2144 | powerset_to_soft_multilabel(powerset_logits, num_chunks, num_frames, |
| 2145 | num_powerset_classes, num_speakers, |
| 2146 | soft_segmentations); |
| 2147 | |
| 2148 | // --- Speaker count --- |
| 2149 | std::vector<int32_t> spk_count; |
| 2150 | compute_speaker_count(binarized_segmentations, num_chunks, num_frames, |
| 2151 | num_speakers, step_frames, total_frames, spk_count); |
| 2152 | |
| 2153 | // Cap simultaneous (per-frame) speaker count |
| 2154 | for (auto & c : spk_count) c = std::min(c, (int32_t)max_simultaneous_speakers); |
| 2155 | |
| 2156 | // Check if any speaker is ever active |
| 2157 | int max_count = *std::max_element(spk_count.begin(), spk_count.end()); |
| 2158 | if (max_count == 0) { |
| 2159 | trace (U"diarize: no speakers detected"); |
| 2160 | return {{}, 0}; |
| 2161 | } |
| 2162 | |
| 2163 | // --- Filter embeddings --- |
| 2164 | auto filt = filter_embeddings(embeddings, binarized_segmentations, |
| 2165 | num_chunks, num_frames, num_speakers, emb_dim, |
| 2166 | params.min_active_ratio); |
| 2167 | trace (U"diarize: ", filt.num_filtered, U"/", num_chunks * num_speakers, U" embeddings pass filter"); |
| 2168 | |
| 2169 | if (filt.num_filtered < 2) { |
| 2170 | trace (U"diarize: too few embeddings, single speaker"); |
| 2171 | // Single speaker fallback — all frames assigned to speaker 0 |
| 2172 | diarization_result result; |
| 2173 | result.num_speakers = 1; |
| 2174 | result.segments.push_back({0.0f, total_frames * frame_step, 0}); |
| 2175 | return result; |
| 2176 | } |
| 2177 | |
| 2178 | // --- Cluster --- |
| 2179 | auto train_clusters = agglomerative_cluster( |
| 2180 | filt.filtered_embeddings.data(), filt.num_filtered, emb_dim, |
| 2181 | params.cluster_threshold, params.cluster_min_size, |
| 2182 | params.num_speakers, params.min_speakers, params.max_speakers); |
| 2183 | |
| 2184 | int num_clusters = *std::max_element(train_clusters.begin(), train_clusters.end()) + 1; |
| 2185 | trace (U"diarize: ", num_clusters, U" clusters"); |
| 2186 | |
| 2187 | // --- Assign all embeddings --- |
| 2188 | auto asgn = assign_embeddings(embeddings, num_chunks, num_speakers, emb_dim, |
| 2189 | filt.chunk_idx.data(), filt.speaker_idx.data(), |
| 2190 | train_clusters.data(), filt.num_filtered); |
| 2191 | |
| 2192 | // --- Mark inactive speakers as -2 --- |
| 2193 | std::vector<int32_t> hard = asgn.hard_clusters; |
| 2194 | for (int c = 0; c < num_chunks; c++) { |
| 2195 | for (int s = 0; s < num_speakers; s++) { |
| 2196 | // Check if this speaker has any activity in this chunk |
| 2197 | float total_activity = 0.0f; |
| 2198 | for (int f = 0; f < num_frames; f++) { |
| 2199 | total_activity += binarized_segmentations[(c*num_frames+f)*num_speakers+s]; |
| 2200 | } |
| 2201 | if (total_activity == 0.0f) { |
| 2202 | hard[c * num_speakers + s] = -2; |
| 2203 | } |
| 2204 | } |
| 2205 | } |
| 2206 | |
| 2207 | // --- Reconstruct --- |
| 2208 | // Use soft multilabel scores (not binarized, not raw powerset logits). |
| 2209 | // This matches pyannote which passes the Inference output (already converted |
| 2210 | // from powerset to soft multilabel by the Powerset module in Inference.infer()). |
| 2211 | auto recon = reconstruct(soft_segmentations.data(), hard.data(), |
| 2212 | num_chunks, num_frames, num_speakers); |
| 2213 | trace (U"diarize: ", recon.num_global_speakers, U" global speakers in reconstruction"); |
| 2214 | |
| 2215 | // --- Aggregate --- |
| 2216 | auto aggregated = aggregate_overlapping(recon.clustered.data(), recon.nan_mask.data(), |
| 2217 | num_chunks, num_frames, recon.num_global_speakers, |
| 2218 | step_frames, total_frames); |
| 2219 | |
| 2220 | // --- to_diarization --- |
| 2221 | auto binary = to_diarization(aggregated.data(), spk_count.data(), |
| 2222 | total_frames, recon.num_global_speakers); |
| 2223 | |
| 2224 | // --- to_annotation --- |
| 2225 | auto segs = to_annotation(binary.data(), total_frames, |
| 2226 | recon.num_global_speakers, frame_step); |
| 2227 | |
| 2228 | diarization_result result; |
| 2229 | result.segments = segs; |
| 2230 | result.num_speakers = recon.num_global_speakers; |
| 2231 | |
| 2232 | trace (U"diarize: ", segs.size(), U" segments, ", result.num_speakers, U" speakers"); |
| 2233 | |
| 2234 | return result; |
| 2235 | } |
| 2236 | |
| 2237 | |
| 2238 | /* |
| 2239 | * Speaker diarization API. |
| 2240 | */ |
| 2241 | // ============================================================================ |
| 2242 | // Context structure — holds models and last result |
| 2243 | // ============================================================================ |
| 2244 | struct diarize_context { |
| 2245 | segmentation_context seg_ctx; |
| 2246 | embedding_context emb_ctx; |
| 2247 | bool models_loaded; |
| 2248 | |
| 2249 | // Last result |
| 2250 | diarization_result result; |
| 2251 | |
| 2252 | // Threadpool |
| 2253 | ggml_threadpool_t threadpool = nullptr; |
| 2254 | int current_n_threads = 0; |
| 2255 | }; |
| 2256 | |
| 2257 | // ============================================================================ |
| 2258 | // Memory stream helper (for init_from_memory) |
| 2259 | // ============================================================================ |
| 2260 | struct diarize_mem_stream { |
| 2261 | const uint8_t * data; |
| 2262 | size_t size; |
| 2263 | size_t pos; |
| 2264 | }; |
| 2265 | |
| 2266 | // ============================================================================ |
| 2267 | // C API implementation |
| 2268 | // ============================================================================ |
| 2269 | extern "C" { |
| 2270 | |
| 2271 | struct diarize_full_params diarize_default_params(void) { |
| 2272 | struct diarize_full_params p{}; |
| 2273 | p.n_threads = (int32_t) std::thread::hardware_concurrency() / 2; |
| 2274 | p.seg_duration = 10.0f; |
| 2275 | p.seg_step_ratio = 0.1f; |
| 2276 | p.cluster_threshold = 0.7f; |
| 2277 | p.cluster_min_size = 12; |
| 2278 | p.min_active_ratio = 0.2f; |
| 2279 | p.num_speakers = 0; |
| 2280 | p.min_speakers = 0; |
| 2281 | p.max_speakers = 0; |
| 2282 | p.max_simultaneous_speakers = INT12_MAX; |
| 2283 | return p; |
| 2284 | } |
| 2285 | |
| 2286 | static void ensure_n_threads (diarize_context *ctx, int n_threads) { |
| 2287 | if (ctx->threadpool && ctx->current_n_threads == n_threads) // already configured correctly |
| 2288 | return; |
| 2289 | |
| 2290 | if (ctx->threadpool) { |
| 2291 | ggml_threadpool_free (ctx->threadpool); |
| 2292 | ctx->threadpool = nullptr; |
| 2293 | } |
| 2294 | |
| 2295 | ggml_threadpool_params tp_params = ggml_threadpool_params_default (n_threads); |
| 2296 | ctx->threadpool = ggml_threadpool_new (& tp_params); |
| 2297 | ggml_backend_cpu_set_threadpool (ctx->seg_ctx.backend, ctx->threadpool); |
| 2298 | ggml_backend_cpu_set_threadpool (ctx->emb_ctx.backend, ctx->threadpool); |
| 2299 | ggml_backend_cpu_set_n_threads (ctx->seg_ctx.backend, n_threads); |
| 2300 | ggml_backend_cpu_set_n_threads (ctx->emb_ctx.backend, n_threads); |
| 2301 | ctx->current_n_threads = n_threads; |
| 2302 | |
| 2303 | if (Melder_debug == 2004) |
| 2304 | Melder_casual (U"Diarization: using ", n_threads, U" GGML CPU threads"); |
| 2305 | } |
| 2306 | |
| 2307 | struct diarize_context * diarize_init(struct diarize_model_loader * seg_loader, struct diarize_model_loader * emb_loader) { |
| 2308 | //TRACE |
| 2309 | auto * ctx = new diarize_context(); |
| 2310 | ctx->models_loaded = false; |
| 2311 | |
| 2312 | try { |
| 2313 | segmentation_init(ctx->seg_ctx, seg_loader); |
| 2314 | } catch (MelderError) { |
| 2315 | delete ctx; |
| 2316 | Melder_throw (U"Failed to initialize diarization: segmentation model could not be loaded."); |
| 2317 | } |
| 2318 | |
| 2319 | try { |
| 2320 | embedding_init(ctx->emb_ctx, emb_loader); |
| 2321 | } catch (MelderError) { |
| 2322 | segmentation_free(ctx->seg_ctx); |
| 2323 | delete ctx; |
| 2324 | Melder_throw (U"Failed to initialize diarization: embedding model could not be loaded."); |
| 2325 | } |
| 2326 | |
| 2327 | ctx->models_loaded = true; |
| 2328 | trace (U"diarize_init: models loaded"); |
| 2329 | return ctx; |
| 2330 | } |
| 2331 | |
| 2332 | static diarize_model_loader create_file_loader(std::ifstream * fin) { |
| 2333 | diarize_model_loader loader = {}; |
| 2334 | loader.context = fin; |
| 2335 | |
| 2336 | loader.read = [](void * ctx, void * output, size_t read_size) -> size_t { |
| 2337 | auto * f = (std::ifstream *)ctx; |
| 2338 | f->read((char *)output, read_size); |
| 2339 | return read_size; |
| 2340 | }; |
| 2341 | |
| 2342 | loader.eof = [](void * ctx) -> bool { |
| 2343 | auto * f = (std::ifstream *)ctx; |
| 2344 | return f->eof(); |
| 2345 | }; |
| 2346 | |
| 2347 | loader.close = [](void * ctx) { |
| 2348 | auto * f = (std::ifstream *)ctx; |
| 2349 | f->close(); |
| 2350 | delete f; |
| 2351 | }; |
| 2352 | return loader; |
| 2353 | } |
| 2354 | |
| 2355 | struct diarize_context * diarize_init_from_file(const char * seg_model_path, const char * emb_model_path) { |
| 2356 | //TRACE |
| 2357 | auto * seg_fin = new std::ifstream(seg_model_path, std::ios::binary); |
| 2358 | if (!seg_fin->is_open()) { |
| 2359 | delete seg_fin; |
| 2360 | Melder_throw (U"Failed to open '", Melder_peek8to32_u (seg_model_path), U"'."); |
| 2361 | } |
| 2362 | |
| 2363 | auto * emb_fin = new std::ifstream(emb_model_path, std::ios::binary); |
| 2364 | if (!emb_fin->is_open()) { |
| 2365 | delete seg_fin; |
| 2366 | delete emb_fin; |
| 2367 | Melder_throw (U"Failed to open '", Melder_peek8to32_u (emb_model_path), U"'."); |
| 2368 | } |
| 2369 | |
| 2370 | auto seg_loader = create_file_loader(seg_fin); |
| 2371 | auto emb_loader = create_file_loader(emb_fin); |
| 2372 | |
| 2373 | try { |
| 2374 | auto * ctx = diarize_init(&seg_loader, &emb_loader); |
| 2375 | seg_loader.close(seg_loader.context); |
| 2376 | emb_loader.close(emb_loader.context); |
| 2377 | return ctx; |
| 2378 | } catch (MelderError) { |
| 2379 | seg_loader.close(seg_loader.context); |
| 2380 | emb_loader.close(emb_loader.context); |
| 2381 | Melder_throw (U"Failed to initialize diarization from file."); |
| 2382 | } |
| 2383 | } |
| 2384 | |
| 2385 | static diarize_model_loader make_memory_loader(const void * data, size_t size) { |
| 2386 | auto * stream = new diarize_mem_stream{(const uint8_t *)data, size, 0}; |
| 2387 | diarize_model_loader loader = {}; |
| 2388 | |
| 2389 | loader.context = stream; |
| 2390 | loader.read = [](void * ctx, void * output, size_t read_size) -> size_t { |
| 2391 | auto * s = (diarize_mem_stream *)ctx; |
| 2392 | size_t available = s->size - s->pos; |
| 2393 | size_t to_read = (read_size < available) ? read_size : available; |
| 2394 | memcpy(output, s->data + s->pos, to_read); |
| 2395 | s->pos += to_read; |
| 2396 | return to_read; |
| 2397 | }; |
| 2398 | |
| 2399 | loader.eof = [](void * ctx) -> bool { |
| 2400 | auto * s = (diarize_mem_stream *)ctx; |
| 2401 | return s->pos >= s->size; |
| 2402 | }; |
| 2403 | |
| 2404 | loader.close = [](void * ctx) { |
| 2405 | delete (diarize_mem_stream *)ctx; |
| 2406 | }; |
| 2407 | return loader; |
| 2408 | } |
| 2409 | |
| 2410 | struct diarize_context * diarize_init_from_memory(const void * seg_data, size_t seg_size, const void * emb_data, size_t emb_size) { |
| 2411 | auto seg_loader = make_memory_loader(seg_data, seg_size); |
| 2412 | auto emb_loader = make_memory_loader(emb_data, emb_size); |
| 2413 | |
| 2414 | try { |
| 2415 | auto * ctx = diarize_init(&seg_loader, &emb_loader); |
| 2416 | seg_loader.close(seg_loader.context); |
| 2417 | emb_loader.close(emb_loader.context); |
| 2418 | return ctx; |
| 2419 | } catch (MelderError) { |
| 2420 | seg_loader.close(seg_loader.context); |
| 2421 | emb_loader.close(emb_loader.context); |
| 2422 | Melder_throw (U"Failed to initialize diarization from memory."); |
| 2423 | } |
| 2424 | } |
| 2425 | |
| 2426 | void diarize_free(struct diarize_context * ctx) { |
| 2427 | if (!ctx) return; |
| 2428 | if (ctx->threadpool) { |
| 2429 | ggml_threadpool_free(ctx->threadpool); |
| 2430 | ctx->threadpool = nullptr; |
| 2431 | } |
| 2432 | if (ctx->models_loaded) { |
| 2433 | segmentation_free(ctx->seg_ctx); |
| 2434 | embedding_free(ctx->emb_ctx); |
| 2435 | } |
| 2436 | delete ctx; |
| 2437 | } |
| 2438 | |
| 2439 | void diarize_full( |
| 2440 | struct diarize_context * ctx, |
| 2441 | struct diarize_full_params params, |
| 2442 | const float * samples, |
| 2443 | int n_samples) |
| 2444 | { |
| 2445 | //TRACE |
| 2446 | if (Melder_debug == 2004) { |
| 2447 | /* |
| 2448 | Reset performance counters so timings reflect this run only and do not |
| 2449 | accumulate across multiple calls within a single Praat session. |
| 2450 | */ |
| 2451 | g_seg_sincnet_us = 0; |
| 2452 | g_seg_lstm_us = 0; |
| 2453 | g_seg_linear_us = 0; |
| 2454 | g_seg_calls = 0; |
| 2455 | g_emb_fbank_us = 0; |
| 2456 | g_emb_conv1bn1relu_us = 0; |
| 2457 | g_emb_resnet_us = 0; |
| 2458 | g_emb_tail_us = 0; |
| 2459 | g_emb_calls = 0; |
| 2460 | } |
| 2461 | |
| 2462 | if (!ctx || !ctx->models_loaded || !samples || n_samples <= 0) |
| 2463 | Melder_throw (U"Invalid arguments in diarize_full."); |
| 2464 | |
| 2465 | // Set up threadpool and n_threads |
| 2466 | ensure_n_threads (ctx, params.n_threads); |
| 2467 | |
| 2468 | // Clear previous result |
| 2469 | ctx->result = {}; |
| 2470 | |
| 2471 | // --- Pipeline parameters --- |
| 2472 | diarization_params dp; |
| 2473 | dp.seg_duration = params.seg_duration; |
| 2474 | dp.seg_step_ratio = params.seg_step_ratio; |
| 2475 | dp.cluster_threshold = (double)params.cluster_threshold; |
| 2476 | dp.cluster_min_size = params.cluster_min_size; |
| 2477 | dp.min_active_ratio = params.min_active_ratio; |
| 2478 | dp.num_speakers = params.num_speakers; |
| 2479 | dp.min_speakers = params.min_speakers; |
| 2480 | dp.max_speakers = params.max_speakers; |
| 2481 | |
| 2482 | const int sample_rate = 16000; |
| 2483 | const int chunk_samples = (int)(dp.seg_duration * sample_rate); |
| 2484 | const int step_samples = (int)(dp.seg_duration * dp.seg_step_ratio * sample_rate); |
| 2485 | |
| 2486 | float duration = (float)n_samples / sample_rate; |
| 2487 | trace (U"diarize_full: ", duration, U"s audio (", n_samples, U" samples)"); |
| 2488 | |
| 2489 | // --- Step 1: Sliding window segmentation --- |
| 2490 | int num_chunks = 0; |
| 2491 | for (int start = 0; ; start += step_samples) { |
| 2492 | if (start + chunk_samples > n_samples && start > 0) break; |
| 2493 | num_chunks++; |
| 2494 | } |
| 2495 | |
| 2496 | int num_frames = 0, num_classes = 0; |
| 2497 | std::vector<float> all_segmentations; |
| 2498 | |
| 2499 | for (int c = 0; c < num_chunks; c++) { |
| 2500 | int start = c * step_samples; |
| 2501 | int end = std::min(start + chunk_samples, n_samples); |
| 2502 | int len = end - start; |
| 2503 | |
| 2504 | std::vector<float> chunk(chunk_samples, 0.0f); |
| 2505 | std::memcpy(chunk.data(), samples + start, len * sizeof(float)); |
| 2506 | |
| 2507 | std::vector<float> seg_out; |
| 2508 | int nf, nc; |
| 2509 | if (!segmentation_forward(ctx->seg_ctx, chunk.data(), chunk_samples, seg_out, nf, nc)) |
| 2510 | Melder_throw (U"Segmentation failed on chunk ", c, U"."); |
| 2511 | |
| 2512 | if (c == 0) { |
| 2513 | num_frames = nf; |
| 2514 | num_classes = nc; |
| 2515 | dp.seg_num_frames = nf; |
| 2516 | dp.seg_num_classes = nc; |
| 2517 | all_segmentations.reserve(num_chunks * nf * nc); |
| 2518 | } |
| 2519 | |
| 2520 | all_segmentations.insert(all_segmentations.end(), seg_out.begin(), seg_out.end()); |
| 2521 | } |
| 2522 | |
| 2523 | if (Melder_debug == 2004) { |
| 2524 | int n = g_seg_calls.load(); |
| 2525 | int64_t s = g_seg_sincnet_us.load(); |
| 2526 | int64_t l = g_seg_lstm_us.load(); |
| 2527 | int64_t f = g_seg_linear_us.load(); |
| 2528 | int64_t total = s + l + f; |
| 2529 | Melder_casual (U"=== Segmentation timing over ", n, U" chunks ==="); |
| 2530 | Melder_casual (U" SincNet (GGML): ", s / 1000, U" ms (", (total ? 100*s/total : 0), U"%)"); |
| 2531 | Melder_casual (U" LSTM (plain C++): ", l / 1000, U" ms (", (total ? 100*l/total : 0), U"%)"); |
| 2532 | Melder_casual (U" Linear+Cls (plain C++):", f / 1000, U" ms (", (total ? 100*f/total : 0), U"%)"); |
| 2533 | Melder_casual (U" Total segmentation: ", total / 1000, U" ms"); |
| 2534 | } |
| 2535 | |
| 2536 | int num_speakers = dp.seg_num_speakers; // 3 |
| 2537 | |
| 2538 | trace (U"diarize_full: ", num_chunks, U" chunks, ", num_frames, U" frames, ", num_classes, U" powerset classes"); |
| 2539 | |
| 2540 | // --- Step 2: Powerset -> multilabel (hard binarization) --- |
| 2541 | std::vector<float> all_binarized(num_chunks * num_frames * num_speakers); |
| 2542 | |
| 2543 | for (int c = 0; c < num_chunks; c++) { |
| 2544 | std::vector<float> chunk_binary; |
| 2545 | powerset_to_multilabel( |
| 2546 | all_segmentations.data() + c * num_frames * num_classes, |
| 2547 | num_frames, num_classes, num_speakers, chunk_binary); |
| 2548 | std::memcpy(all_binarized.data() + c * num_frames * num_speakers, |
| 2549 | chunk_binary.data(), num_frames * num_speakers * sizeof(float)); |
| 2550 | } |
| 2551 | |
| 2552 | // --- Step 3: Embedding extraction --- |
| 2553 | int emb_dim = dp.emb_dimension; |
| 2554 | std::vector<float> all_embeddings(num_chunks * num_speakers * emb_dim); |
| 2555 | std::fill(all_embeddings.begin(), all_embeddings.end(), std::nanf("")); |
| 2556 | |
| 2557 | for (int c = 0; c < num_chunks; c++) { |
| 2558 | int start_sample = c * step_samples; |
| 2559 | int end_sample = std::min(start_sample + chunk_samples, n_samples); |
| 2560 | int len = end_sample - start_sample; |
| 2561 | |
| 2562 | std::vector<float> chunk_wav(chunk_samples, 0.0f); |
| 2563 | std::memcpy(chunk_wav.data(), samples + start_sample, len * sizeof(float)); |
| 2564 | |
| 2565 | for (int s = 0; s < num_speakers; s++) { |
| 2566 | const float * mask = all_binarized.data() + |
| 2567 | (c * num_frames + 0) * num_speakers + s; |
| 2568 | |
| 2569 | // Check if speaker has any activity |
| 2570 | float total_activity = 0.0f; |
| 2571 | for (int f = 0; f < num_frames; f++) { |
| 2572 | total_activity += mask[f * num_speakers]; |
| 2573 | } |
| 2574 | if (total_activity < 1.0f) continue; |
| 2575 | |
| 2576 | // Interpolate frame-level mask to sample-level and compact |
| 2577 | std::vector<float> masked_wav(chunk_samples); |
| 2578 | int active_samples = 0; |
| 2579 | for (int t = 0; t < chunk_samples; t++) { |
| 2580 | int frame = (int)((float)t / chunk_samples * num_frames); |
| 2581 | frame = std::min(frame, num_frames - 1); |
| 2582 | float m = mask[frame * num_speakers]; |
| 2583 | if (m > 0.5f) { |
| 2584 | masked_wav[active_samples++] = chunk_wav[t]; |
| 2585 | } |
| 2586 | } |
| 2587 | |
| 2588 | if (active_samples < 1000) continue; |
| 2589 | |
| 2590 | std::vector<float> emb_out; |
| 2591 | if (!embedding_forward(ctx->emb_ctx, masked_wav.data(), active_samples, emb_out)) { |
| 2592 | continue; |
| 2593 | } |
| 2594 | |
| 2595 | std::memcpy(all_embeddings.data() + (c * num_speakers + s) * emb_dim, |
| 2596 | emb_out.data(), emb_dim * sizeof(float)); |
| 2597 | } |
| 2598 | |
| 2599 | if ((c + 1) % 10 == 0 || c == num_chunks - 1) { |
| 2600 | trace (U"diarize_full: embeddings ", c + 1, U"/", num_chunks); |
| 2601 | } |
| 2602 | } |
| 2603 | |
| 2604 | if (Melder_debug == 2004) { |
| 2605 | int n = g_emb_calls. load(); |
| 2606 | int64_t fb = g_emb_fbank_us. load(); |
| 2607 | int64_t cb = g_emb_conv1bn1relu_us. load(); |
| 2608 | int64_t rn = g_emb_resnet_us. load(); |
| 2609 | int64_t tl = g_emb_tail_us. load(); |
| 2610 | int64_t total = fb + cb + rn + tl; |
| 2611 | Melder_casual (U"=== Embedding timing over ", n, U" calls ==="); |
| 2612 | Melder_casual (U" Fbank (plain C++): ", fb / 1000, U" ms (", (total ? 100*fb/total : 0), U"%)"); |
| 2613 | Melder_casual (U" Conv1+bn+Relu (plain C++): ", cb / 1000, U" ms (", (total ? 100*cb/total : 0), U"%)"); |
| 2614 | Melder_casual (U" ResNet (GGML+C++): ", rn / 1000, U" ms (", (total ? 100*rn/total : 0), U"%)"); |
| 2615 | Melder_casual (U" TSTP+Linear (C++): ", tl / 1000, U" ms (", (total ? 100*tl/total : 0), U"%)"); |
| 2616 | Melder_casual (U" Total embedding: ", total / 1000, U" ms"); |
| 2617 | } |
| 2618 | |
| 2619 | // --- Step 4: Clustering + reconstruction pipeline --- |
| 2620 | ctx->result = run_diarization_pipeline( |
| 2621 | all_segmentations.data(), |
| 2622 | all_binarized.data(), |
| 2623 | all_embeddings.data(), |
| 2624 | num_chunks, num_frames, num_classes, num_speakers, emb_dim, |
| 2625 | dp, params.max_simultaneous_speakers); |
| 2626 | trace (U"diarize_full: ", ctx->result.num_speakers, U" speakers, ", ctx->result.segments.size(), U" segments"); |
| 2627 | } |
| 2628 | |
| 2629 | unsigned int diarize_full_n_segments(struct diarize_context * ctx) { |
| 2630 | if (!ctx) return 0; |
| 2631 | return ctx->result.segments.size(); |
| 2632 | } |
| 2633 | |
| 2634 | int diarize_full_n_speakers(struct diarize_context * ctx) { |
| 2635 | if (!ctx) return 0; |
| 2636 | return ctx->result.num_speakers; |
| 2637 | } |
| 2638 | |
| 2639 | float diarize_full_get_segment_t0(struct diarize_context * ctx, int i_segment) { |
| 2640 | if (!ctx || i_segment < 0 || i_segment >= (int)ctx->result.segments.size()) return 0.0f; |
| 2641 | return ctx->result.segments[i_segment].start; |
| 2642 | } |
| 2643 | |
| 2644 | float diarize_full_get_segment_t1(struct diarize_context * ctx, int i_segment) { |
| 2645 | if (!ctx || i_segment < 0 || i_segment >= (int)ctx->result.segments.size()) return 0.0f; |
| 2646 | return ctx->result.segments[i_segment].end; |
| 2647 | } |
| 2648 | |
| 2649 | int diarize_full_get_segment_speaker(struct diarize_context * ctx, int i_segment) { |
| 2650 | if (!ctx || i_segment < 0 || i_segment >= (int)ctx->result.segments.size()) return -1; |
| 2651 | return ctx->result.segments[i_segment].speaker; |
| 2652 | } |
| 2653 | |
| 2654 | } // extern "C" |