Debian Codegraph @

external/whispercpp/diarize.cpp

raw symbols SCIP
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"cxx . . $ `<file>/external/whispercpp/ggml.h`/
61 #include "ggml-alloc.h"cxx . . $ `<file>/external/whispercpp/ggml-alloc.h`/
62 #include "ggml-backend.h"cxx . . $ `<file>/external/whispercpp/ggml-backend.h`/
63 #include "ggml-cpu.h"cxx . . $ `<file>/external/whispercpp/ggml-cpu.h`/
64 #include "diarize.h"cxx . . $ `<file>/external/whispercpp/diarize.h`/
65 #include "melder.h"cxx . . $ `<file>/melder/melder.h`/
66
67 #define GGML_FILE_MAGICcxx . . $ `external/whispercpp/diarize.cpp:67:9`! 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_NODEScxx . . $ `external/whispercpp/diarize.cpp:77:9`! 64
78 #define CONV2D_MAX_NODEScxx . . $ `external/whispercpp/diarize.cpp:78:9`! 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 stdcxx . . $ std/::atomiccxx . . $ std/atomic# <int64_t> g_seg_sincnet_uscxx . . $ g_seg_sincnet_us. {0}; // ggml SincNet forward
88 static stdcxx . . $ std/::atomiccxx . . $ std/atomic# <int64_t> g_seg_lstm_uscxx . . $ g_seg_lstm_us. {0}; // plain-C++ bidirectional LSTM
89 static stdcxx . . $ std/::atomiccxx . . $ std/atomic# <int64_t> g_seg_linear_uscxx . . $ g_seg_linear_us. {0}; // plain-C++ linear layers + classifier
90 static stdcxx . . $ std/::atomiccxx . . $ std/atomic# <int> g_seg_callscxx . . $ g_seg_calls. {0}; // number of segmentation_forward() calls
91
92 static stdcxx . . $ std/::atomiccxx . . $ std/atomic# <int64_t> g_emb_fbank_uscxx . . $ g_emb_fbank_us. {0}; // plain-C++ fbank feature extraction
93 static stdcxx . . $ std/::atomiccxx . . $ std/atomic# <int64_t> g_emb_conv1bn1relu_uscxx . . $ g_emb_conv1bn1relu_us. {0}; // ResNet stem (ggml conv + plain-C++ BN/ReLU)
94 static stdcxx . . $ std/::atomiccxx . . $ std/atomic# <int64_t> g_emb_resnet_uscxx . . $ g_emb_resnet_us. {0}; // ResNet layers 1–4 (mix of ggml and plain C++)
95 static stdcxx . . $ std/::atomiccxx . . $ std/atomic# <int64_t> g_emb_tail_uscxx . . $ g_emb_tail_us. {0}; // TSTP pooling + final linear layer
96 static stdcxx . . $ std/::atomiccxx . . $ std/atomic# <int> g_emb_callscxx . . $ g_emb_calls. {0}; // number of embedding_forward() calls
97
98 // ============================================================================
99 // Big-endian support
100 // ============================================================================
101 #if __BYTE_ORDER__cxx . . $ `<built-in>:113:9`! == __ORDER_BIG_ENDIAN__cxx . . $ `<built-in>:111:9`!
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_VALUEcxx . . $ `external/whispercpp/diarize.cpp:131:9`!(d) do {} while (0)
132 #define BYTESWAP_TENSORcxx . . $ `external/whispercpp/diarize.cpp:132:9`!(t) do {} while (0)
133 #endif
134
135 // ============================================================================
136 // Model loading
137 // ============================================================================
138 template<typename T>
139 static void read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(diarize_model_loader * loader, T & dest) {
140 loader->read(loader->context, &dest, sizeof(T));
141 BYTESWAP_VALUEcxx . . $ `external/whispercpp/diarize.cpp:131:9`!(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_hparamscxx . . $ 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_0cxx . . $ segmentation_hparams#sincnet_filters_0. = 80;
154 int32_t sincnet_kernel_0cxx . . $ segmentation_hparams#sincnet_kernel_0. = 251;
155 int32_t sincnet_stride_0cxx . . $ segmentation_hparams#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_1cxx . . $ segmentation_hparams#sincnet_filters_1. = 60;
160 int32_t sincnet_kernel_1cxx . . $ segmentation_hparams#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_2cxx . . $ segmentation_hparams#sincnet_filters_2. = 60;
165 int32_t sincnet_kernel_2cxx . . $ segmentation_hparams#sincnet_kernel_2. = 5;
166
167 // LSTM: processes the 589×60 SincNet output as a sequence.
168 int32_t lstm_input_sizecxx . . $ segmentation_hparams#lstm_input_size. = 60;
169 int32_t lstm_hidden_sizecxx . . $ segmentation_hparams#lstm_hidden_size. = 128; // hidden state size per direction
170 int32_t lstm_layerscxx . . $ segmentation_hparams#lstm_layers. = 4; // number of stacked LSTM layers
171 int32_t lstm_bidirectionalcxx . . $ segmentation_hparams#lstm_bidirectional. = 1; // 1 = bidirectional (forward + reverse)\
172
173 // Feed-forward layers after LSTM:
174 int32_t linear_hiddencxx . . $ segmentation_hparams#linear_hidden. = 128; // hidden size of each linear layer
175 int32_t linear_layerscxx . . $ segmentation_hparams#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_classescxx . . $ segmentation_hparams#n_classes. = 7; // powerset classes for up to 3 speakers
179
180 // Derived
181 int n_filterscxx . . $ segmentation_hparams#n_filters(455f465bc33b4cdf).() const { return sincnet_filters_0cxx . . $ segmentation_hparams#sincnet_filters_0.; } // 80
182 int n_sinc_paramscxx . . $ segmentation_hparams#n_sinc_params(455f465bc33b4cdf).() const { return sincnet_filters_0cxx . . $ segmentation_hparams#sincnet_filters_0. / 2; } // 40 (learned frequency pairs)
183 int half_kernelcxx . . $ segmentation_hparams#half_kernel(455f465bc33b4cdf).() const { return sincnet_kernel_0cxx . . $ segmentation_hparams#sincnet_kernel_0. / 2; } // 125 (symmetric kernel half)
184 int lstm_output_sizecxx . . $ segmentation_hparams#lstm_output_size(455f465bc33b4cdf).() const { return lstm_hidden_sizecxx . . $ segmentation_hparams#lstm_hidden_size. * (lstm_bidirectionalcxx . . $ segmentation_hparams#lstm_bidirectional. ? 2 : 1); } // 256 features per frame
185 };
186
187 struct segmentation_modelcxx . . $ segmentation_model# {
188 segmentation_hparamscxx . . $ segmentation_hparams# hparamscxx . . $ segmentation_model#hparams.;
189
190 // Waveform normalization (InstanceNorm1d on raw input, 1 channel)
191 struct ggml_tensor * sincnet_wav_norm_wcxx . . $ segmentation_model#sincnet_wav_norm_w.; // [1]
192 struct ggml_tensor * sincnet_wav_norm_bcxx . . $ segmentation_model#sincnet_wav_norm_b.; // [1]
193
194 // SincConv learned filterbank parameters (block 0)
195 struct ggml_tensor * sincnet_low_hzcxx . . $ segmentation_model#sincnet_low_hz.; // [40] low cutoff frequency per filter pair
196 struct ggml_tensor * sincnet_band_hzcxx . . $ segmentation_model#sincnet_band_hz.; // [40] bandwidth per filter pair
197 struct ggml_tensor * sincnet_windowcxx . . $ segmentation_model#sincnet_window.; // [125] Hamming window (half-kernel)
198 struct ggml_tensor * sincnet_ncxx . . $ segmentation_model#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_wcxx . . $ segmentation_model#sincnet_conv1_w.; // [5, 80, 60]
202 struct ggml_tensor * sincnet_conv1_bcxx . . $ segmentation_model#sincnet_conv1_b.; // [60]
203 struct ggml_tensor * sincnet_conv2_wcxx . . $ segmentation_model#sincnet_conv2_w.; // [5, 60, 60]
204 struct ggml_tensor * sincnet_conv2_bcxx . . $ segmentation_model#sincnet_conv2_b.; // [60]
205
206 // InstanceNorm affine parameters (one per block)
207 struct ggml_tensor * sincnet_norm0_wcxx . . $ segmentation_model#sincnet_norm0_w.; // [80]
208 struct ggml_tensor * sincnet_norm0_bcxx . . $ segmentation_model#sincnet_norm0_b.; // [80]
209 struct ggml_tensor * sincnet_norm1_wcxx . . $ segmentation_model#sincnet_norm1_w.; // [60]
210 struct ggml_tensor * sincnet_norm1_bcxx . . $ segmentation_model#sincnet_norm1_b.; // [60]
211 struct ggml_tensor * sincnet_norm2_wcxx . . $ segmentation_model#sincnet_norm2_w.; // [60]
212 struct ggml_tensor * sincnet_norm2_bcxx . . $ segmentation_model#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_ihcxx . . $ segmentation_model#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_hhcxx . . $ segmentation_model#lstm_weight_hh.[4]; // [128, 512] hidden-to-hidden
218 struct ggml_tensor * lstm_bias_ihcxx . . $ segmentation_model#lstm_bias_ih.[4]; // [512]
219 struct ggml_tensor * lstm_bias_hhcxx . . $ segmentation_model#lstm_bias_hh.[4]; // [512]
220 // Reverse direction
221 struct ggml_tensor * lstm_weight_ih_revcxx . . $ segmentation_model#lstm_weight_ih_rev.[4]; // [in, 512]
222 struct ggml_tensor * lstm_weight_hh_revcxx . . $ segmentation_model#lstm_weight_hh_rev.[4]; // [128, 512]
223 struct ggml_tensor * lstm_bias_ih_revcxx . . $ segmentation_model#lstm_bias_ih_rev.[4]; // [512]
224 struct ggml_tensor * lstm_bias_hh_revcxx . . $ segmentation_model#lstm_bias_hh_rev.[4]; // [512]
225
226 // Feed-forward layers (2 layers with LeakyReLU)
227 struct ggml_tensor * linear_wcxx . . $ segmentation_model#linear_w.[2]; // [256, 128] for layer 0, [128, 128] for layer 1
228 struct ggml_tensor * linear_bcxx . . $ segmentation_model#linear_b.[2]; // [128]
229
230 // Powerset classifier
231 struct ggml_tensor * classifier_wcxx . . $ segmentation_model#classifier_w.; // [128, 7]
232 struct ggml_tensor * classifier_bcxx . . $ segmentation_model#classifier_b.; // [7]
233
234 // Bookkeeping
235 stdcxx . . $ std/::mapcxx . . $ std/map#<stdcxx . . $ std/::stringcxx . . $ std/string#, struct ggml_tensor *> tensorscxx . . $ segmentation_model#tensors.;
236 int n_loadedcxx . . $ segmentation_model#n_loaded. = 0;
237 stdcxx . . $ std/::vectorcxx . . $ std/vector#<ggml_context *> ctxscxx . . $ segmentation_model#ctxs.;
238 stdcxx . . $ std/::vectorcxx . . $ std/vector#<ggml_backend_buffer_t> bufferscxx . . $ segmentation_model#buffers.;
239 };
240
241 struct segmentation_contextcxx . . $ segmentation_context# {
242 segmentation_modelcxx . . $ segmentation_model# modelcxx . . $ segmentation_context#model.;
243
244 // Pre-computed SincNet filters [n_filters * kernel_size]
245 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> sinc_filterscxx . . $ segmentation_context#sinc_filters.;
246
247 // GGML backend for SincNet
248 ggml_backend_t backendcxx . . $ segmentation_context#backend. = nullptr;
249 };
250
251 // ============================================================================
252 // Segmentation: Model loading
253 // ============================================================================
254 static void segmentation_load_modelcxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).(diarize_model_loader * loader, segmentation_modelcxx . . $ segmentation_model# & model) {
255 //TRACE
256 uint32_tcxx . . $ uint32_t# magic;
257 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, magic);
258 if (magic != GGML_FILE_MAGICcxx . . $ `external/whispercpp/diarize.cpp:67:9`!)
259 Melder_throwcxx . . $ `melder/melder_error.h:77:9`!(U"Invalid model data (bad magic).");
260
261 auto & hp = model.hparamscxx . . $ segmentation_model#hparams.;
262 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.sincnet_filters_0cxx . . $ segmentation_hparams#sincnet_filters_0.);
263 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.sincnet_kernel_0cxx . . $ segmentation_hparams#sincnet_kernel_0.);
264 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.sincnet_stride_0cxx . . $ segmentation_hparams#sincnet_stride_0.);
265 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.sincnet_filters_1cxx . . $ segmentation_hparams#sincnet_filters_1.);
266 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.sincnet_kernel_1cxx . . $ segmentation_hparams#sincnet_kernel_1.);
267 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.sincnet_filters_2cxx . . $ segmentation_hparams#sincnet_filters_2.);
268 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.sincnet_kernel_2cxx . . $ segmentation_hparams#sincnet_kernel_2.);
269 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.lstm_input_sizecxx . . $ segmentation_hparams#lstm_input_size.);
270 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.lstm_hidden_sizecxx . . $ segmentation_hparams#lstm_hidden_size.);
271 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.lstm_layerscxx . . $ segmentation_hparams#lstm_layers.);
272 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.lstm_bidirectionalcxx . . $ segmentation_hparams#lstm_bidirectional.);
273 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.linear_hiddencxx . . $ segmentation_hparams#linear_hidden.);
274 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.linear_layerscxx . . $ segmentation_hparams#linear_layers.);
275 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.n_classescxx . . $ segmentation_hparams#n_classes.);
276
277 tracecxx . . $ `melder/melder_debug.h:60:10`! (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_paramscxx . . $ segmentation_hparams#n_sinc_params(455f465bc33b4cdf).();
283 const int hk = hp.half_kernelcxx . . $ segmentation_hparams#half_kernel(455f465bc33b4cdf).();
284 const int hsd = hp.lstm_hidden_sizecxx . . $ segmentation_hparams#lstm_hidden_size. * 4;
285 const size_t nt = 16 + 8 * hp.lstm_layerscxx . . $ segmentation_hparams#lstm_layers. + 2 * hp.linear_layerscxx . . $ segmentation_hparams#linear_layers. + 2;
286
287 stdcxx . . $ std/::mapcxx . . $ std/map#<ggml_backend_buffer_type_t, ggml_context*> ctx_mapcxx . . $ std/map#map(49f6e7a06ebc5aa8).;
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.findcxx . . $ std/map#find(36f8d56706583706).(buft);
292 if (it ==cxx . . $ std/`operator==`(be6a71a859368080). ctx_map.endcxx . . $ std/map#end(7e4de33083b6e738).()) {
293 ggml_init_params p = {
294 nt * ggml_tensor_overhead(),
295 nullptr,
296 true
297 };
298 auto c = ggml_init(p);
299 ctx_map[cxx . . $ std/map#`operator[]`(bbd415b616967878).buft] = c;
300 model.ctxscxx . . $ segmentation_model#ctxs..push_backcxx . . $ std/vector#push_back(77d9f17553126ecb).(c);
301 return c;
302 }
303 return it->cxx . . $ std/_Rb_tree_iterator#`operator->`(34d6acfd341ba7ab).second;
304 };
305
306 auto CT = [&](const stdcxx . . $ std/::stringcxx . . $ std/string# & name, ggml_tensor * meta) -> ggml_tensor* {
307 auto c = get_ctx(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_0#`operator()`(986c283657a23dc8).cpu_buft);
308 auto t = ggml_dup_tensor(c, meta);
309 ggml_set_name(t, name.c_strcxx . . $ std/__cxx11/basic_string#c_str(8e614c7de0b1573e).());
310 model.tensorscxx . . $ segmentation_model#tensors.[cxx . . $ std/map#`operator[]`(bbd415b616967878).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_wcxx . . $ segmentation_model#sincnet_wav_norm_w. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.wav_norm1d.weight"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1));
324 model.sincnet_wav_norm_bcxx . . $ segmentation_model#sincnet_wav_norm_b. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.wav_norm1d.bias"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1));
325 model.sincnet_low_hzcxx . . $ segmentation_model#sincnet_low_hz. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.conv1d.0.filterbank.low_hz_"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nsp));
326 model.sincnet_band_hzcxx . . $ segmentation_model#sincnet_band_hz. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.conv1d.0.filterbank.band_hz_"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nsp));
327 model.sincnet_windowcxx . . $ segmentation_model#sincnet_window. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.conv1d.0.filterbank.window_"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hk));
328 model.sincnet_ncxx . . $ segmentation_model#sincnet_n. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.conv1d.0.filterbank.n_"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hk));
329
330 model.sincnet_conv1_wcxx . . $ segmentation_model#sincnet_conv1_w. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.conv1d.1.weight"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hp.sincnet_kernel_1cxx . . $ segmentation_hparams#sincnet_kernel_1., hp.sincnet_filters_0cxx . . $ segmentation_hparams#sincnet_filters_0., hp.sincnet_filters_1cxx . . $ segmentation_hparams#sincnet_filters_1.));
331 model.sincnet_conv1_bcxx . . $ segmentation_model#sincnet_conv1_b. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.conv1d.1.bias"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_1cxx . . $ segmentation_hparams#sincnet_filters_1.));
332 model.sincnet_conv2_wcxx . . $ segmentation_model#sincnet_conv2_w. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.conv1d.2.weight"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hp.sincnet_kernel_2cxx . . $ segmentation_hparams#sincnet_kernel_2., hp.sincnet_filters_1cxx . . $ segmentation_hparams#sincnet_filters_1., hp.sincnet_filters_2cxx . . $ segmentation_hparams#sincnet_filters_2.));
333 model.sincnet_conv2_bcxx . . $ segmentation_model#sincnet_conv2_b. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.conv1d.2.bias"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_2cxx . . $ segmentation_hparams#sincnet_filters_2.));
334
335 model.sincnet_norm0_wcxx . . $ segmentation_model#sincnet_norm0_w. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.norm1d.0.weight"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_0cxx . . $ segmentation_hparams#sincnet_filters_0.));
336 model.sincnet_norm0_bcxx . . $ segmentation_model#sincnet_norm0_b. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.norm1d.0.bias"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_0cxx . . $ segmentation_hparams#sincnet_filters_0.));
337 model.sincnet_norm1_wcxx . . $ segmentation_model#sincnet_norm1_w. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.norm1d.1.weight"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_1cxx . . $ segmentation_hparams#sincnet_filters_1.));
338 model.sincnet_norm1_bcxx . . $ segmentation_model#sincnet_norm1_b. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.norm1d.1.bias"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_1cxx . . $ segmentation_hparams#sincnet_filters_1.));
339 model.sincnet_norm2_wcxx . . $ segmentation_model#sincnet_norm2_w. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.norm1d.2.weight"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_2cxx . . $ segmentation_hparams#sincnet_filters_2.));
340 model.sincnet_norm2_bcxx . . $ segmentation_model#sincnet_norm2_b. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."sincnet.norm1d.2.bias"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.sincnet_filters_2cxx . . $ segmentation_hparams#sincnet_filters_2.));
341
342 // LSTM
343 for (int l = 0; l < hp.lstm_layerscxx . . $ segmentation_hparams#lstm_layers.; l++) {
344 int in_sz = (l == 0) ? hp.lstm_input_sizecxx . . $ segmentation_hparams#lstm_input_size. : hp.lstm_output_sizecxx . . $ segmentation_hparams#lstm_output_size(455f465bc33b4cdf).();
345 stdcxx . . $ std/::stringcxx . . $ std/string# ls = stdcxx . . $ std/::to_stringcxx . . $ std/__cxx11/to_string(3d81e17e7a87eecc).(l);
346 model.lstm_weight_ihcxx . . $ segmentation_model#lstm_weight_ih.[l] = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."lstm.weight_ih_l"+cxx . . $ std/operator+(42c652dfebe55ad7).ls, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, in_sz, hsd));
347 model.lstm_weight_hhcxx . . $ segmentation_model#lstm_weight_hh.[l] = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."lstm.weight_hh_l"+cxx . . $ std/operator+(42c652dfebe55ad7).ls, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, hp.lstm_hidden_sizecxx . . $ segmentation_hparams#lstm_hidden_size., hsd));
348 model.lstm_bias_ihcxx . . $ segmentation_model#lstm_bias_ih.[l] = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."lstm.bias_ih_l"+cxx . . $ std/operator+(42c652dfebe55ad7).ls, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hsd));
349 model.lstm_bias_hhcxx . . $ segmentation_model#lstm_bias_hh.[l] = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."lstm.bias_hh_l"+cxx . . $ std/operator+(42c652dfebe55ad7).ls, ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hsd));
350 model.lstm_weight_ih_revcxx . . $ segmentation_model#lstm_weight_ih_rev.[l] = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."lstm.weight_ih_l"+cxx . . $ std/operator+(42c652dfebe55ad7).ls+cxx . . $ std/operator+(900ec9581c410ad9)."_reverse", ggml_new_tensor_2d(ctx, GGML_TYPE_F32, in_sz, hsd));
351 model.lstm_weight_hh_revcxx . . $ segmentation_model#lstm_weight_hh_rev.[l] = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."lstm.weight_hh_l"+cxx . . $ std/operator+(42c652dfebe55ad7).ls+cxx . . $ std/operator+(900ec9581c410ad9)."_reverse", ggml_new_tensor_2d(ctx, GGML_TYPE_F32, hp.lstm_hidden_sizecxx . . $ segmentation_hparams#lstm_hidden_size., hsd));
352 model.lstm_bias_ih_revcxx . . $ segmentation_model#lstm_bias_ih_rev.[l] = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."lstm.bias_ih_l"+cxx . . $ std/operator+(42c652dfebe55ad7).ls+cxx . . $ std/operator+(900ec9581c410ad9)."_reverse", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hsd));
353 model.lstm_bias_hh_revcxx . . $ segmentation_model#lstm_bias_hh_rev.[l] = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."lstm.bias_hh_l"+cxx . . $ std/operator+(42c652dfebe55ad7).ls+cxx . . $ std/operator+(900ec9581c410ad9)."_reverse", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hsd));
354 }
355
356 // Linear
357 int lo = hp.lstm_output_sizecxx . . $ segmentation_hparams#lstm_output_size(455f465bc33b4cdf).();
358 for (int l = 0; l < hp.linear_layerscxx . . $ segmentation_hparams#linear_layers.; l++) {
359 int inf = (l == 0) ? lo : hp.linear_hiddencxx . . $ segmentation_hparams#linear_hidden.;
360 model.linear_wcxx . . $ segmentation_model#linear_w.[l] = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."linear."+cxx . . $ std/operator+(39ed2c165380f78e).stdcxx . . $ std/::to_stringcxx . . $ std/__cxx11/to_string(3d81e17e7a87eecc).(l)+cxx . . $ std/operator+(900ec9581c410ad9).".weight", ggml_new_tensor_2d(ctx, GGML_TYPE_F32, inf, hp.linear_hiddencxx . . $ segmentation_hparams#linear_hidden.));
361 model.linear_bcxx . . $ segmentation_model#linear_b.[l] = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."linear."+cxx . . $ std/operator+(39ed2c165380f78e).stdcxx . . $ std/::to_stringcxx . . $ std/__cxx11/to_string(3d81e17e7a87eecc).(l)+cxx . . $ std/operator+(900ec9581c410ad9).".bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.linear_hiddencxx . . $ segmentation_hparams#linear_hidden.));
362 }
363
364 // Classifier
365 int ci = (hp.linear_layerscxx . . $ segmentation_hparams#linear_layers. > 0) ? hp.linear_hiddencxx . . $ segmentation_hparams#linear_hidden. : lo;
366 model.classifier_wcxx . . $ segmentation_model#classifier_w. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."classifier.weight"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_2d(ctx, GGML_TYPE_F32, ci, hp.n_classescxx . . $ segmentation_hparams#n_classes.));
367 model.classifier_bcxx . . $ segmentation_model#classifier_b. = CT(cxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).$anonymous_type_1#`operator()`(f703bb206d6e343f)."classifier.bias"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_classescxx . . $ segmentation_hparams#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.bufferscxx . . $ segmentation_model#buffers..push_backcxx . . $ std/vector#push_back(77d9f17553126ecb).(buf);
377 }
378
379 // Load weights
380 model.n_loadedcxx . . $ segmentation_model#n_loaded. = 0;
381 stdcxx . . $ std/::vectorcxx . . $ std/vector#<char> read_bufcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
382 while (!loader->eof(loader->context)) {
383 int32_t n_dims, length, ttype;
384 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, n_dims);
385 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, length);
386 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(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_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, ne[i]);
392 n_elements *= ne[i];
393 }
394
395 stdcxx . . $ std/::stringcxx . . $ std/string# namecxx . . $ std/__cxx11/basic_string#basic_string(57f9c416bbf2a7d6).(length, 0);
396 loader->read(loader->context, name.datacxx . . $ std/__cxx11/basic_string#data(258ee1c9e0a18a5c).(), length);
397
398 auto it = model.tensorscxx . . $ segmentation_model#tensors..findcxx . . $ std/map#find(36f8d56706583706).(name);
399 if (it ==cxx . . $ std/`operator==`(be6a71a859368080). model.tensorscxx . . $ segmentation_model#tensors..endcxx . . $ std/map#end(7e4de33083b6e738).())
400 Melder_throwcxx . . $ `melder/melder_error.h:77:9`!(U": unknown tensor '", Melder_peek8to32_u(name.c_str()), U"'");
401
402 auto tensor = it->cxx . . $ std/_Rb_tree_iterator#`operator->`(34d6acfd341ba7ab).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_TENSORcxx . . $ `external/whispercpp/diarize.cpp:132:9`!(tensor);
408 } else {
409 read_buf.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(ggml_nbytes(tensor));
410 loader->read(loader->context, read_buf.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), read_buf.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).());
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.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), 0, ggml_nbytes(tensor));
414 }
415 model.n_loadedcxx . . $ segmentation_model#n_loaded.++;
416 }
417
418 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"Loaded ", model.n_loaded, U"/", model.tensors.size(), U" tensors");
419 if (model.n_loadedcxx . . $ segmentation_model#n_loaded. != model.tensorscxx . . $ segmentation_model#tensors..sizecxx . . $ std/map#size(a08d7b23eb6940f6).())
420 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> compute_sinc_filterscxx . . $ compute_sinc_filters(1de572a9a165651f).(const segmentation_modelcxx . . $ segmentation_model# & model) {
427 auto & hp = model.hparamscxx . . $ segmentation_model#hparams.;
428 const int np = hp.n_sinc_paramscxx . . $ segmentation_hparams#n_sinc_params(455f465bc33b4cdf).();
429 const int hk = hp.half_kernelcxx . . $ segmentation_hparams#half_kernel(455f465bc33b4cdf).();
430 const int ks = hp.sincnet_kernel_0cxx . . $ segmentation_hparams#sincnet_kernel_0.;
431 const int nf = hp.n_filterscxx . . $ segmentation_hparams#n_filters(455f465bc33b4cdf).();
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_hzcxx . . $ segmentation_model#sincnet_low_hz.->data;
438 const float *bh = (const float*)model.sincnet_band_hzcxx . . $ segmentation_model#sincnet_band_hz.->data;
439 const float *w = (const float*)model.sincnet_windowcxx . . $ segmentation_model#sincnet_window.->data;
440 const float *n = (const float*)model.sincnet_ncxx . . $ segmentation_model#sincnet_n.->data;
441
442 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> fcxx . . $ std/vector#vector(229e4d6bd205de31).(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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).(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 fcxx . . $ std/vector#vector(6f559d22b039ccdb).;
466 }
467
468 // ============================================================================
469 // Segmentation: F32 conv1d (avoids F16 im2col precision loss)
470 // ============================================================================
471 static ggml_tensor * ggml_conv_1d_f32cxx . . $ ggml_conv_1d_f32(8784f8cdaed3b4fd).(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_forwardcxx . . $ sincnet_forward(135b33e7526ba24b).(segmentation_contextcxx . . $ segmentation_context# & sctx,
489 const float * samples, int n_samples,
490 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> & output, int & out_time, int & out_ch) {
491 auto & model = sctx.modelcxx . . $ segmentation_context#model.;
492 auto & hp = model.hparamscxx . . $ segmentation_model#hparams.;
493
494 ggml_init_params ctx_params = {
495 ggml_tensor_overhead() * SINCNET_MAX_NODEScxx . . $ `external/whispercpp/diarize.cpp:77:9`! + 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_0cxx . . $ segmentation_hparams#sincnet_kernel_0., 1, hp.n_filterscxx . . $ segmentation_hparams#n_filters(455f465bc33b4cdf).());
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_wcxx . . $ segmentation_model#sincnet_wav_norm_w.);
514 cur = ggml_add(ctx0, cur, model.sincnet_wav_norm_bcxx . . $ segmentation_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_f32cxx . . $ ggml_conv_1d_f32(8784f8cdaed3b4fd).(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(cxx . . $ sincnet_forward(135b33e7526ba24b).$anonymous_type_2#`operator()`(170d5311f14365d).sinc_w, nullptr, hp.sincnet_stride_0cxx . . $ segmentation_hparams#sincnet_stride_0.,
531 model.sincnet_norm0_wcxx . . $ segmentation_model#sincnet_norm0_w., model.sincnet_norm0_bcxx . . $ segmentation_model#sincnet_norm0_b., hp.sincnet_filters_0cxx . . $ segmentation_hparams#sincnet_filters_0., true);
532
533 // Block 1
534 block(cxx . . $ sincnet_forward(135b33e7526ba24b).$anonymous_type_2#`operator()`(170d5311f14365d).model.sincnet_conv1_wcxx . . $ segmentation_model#sincnet_conv1_w., model.sincnet_conv1_bcxx . . $ segmentation_model#sincnet_conv1_b., 1,
535 model.sincnet_norm1_wcxx . . $ segmentation_model#sincnet_norm1_w., model.sincnet_norm1_bcxx . . $ segmentation_model#sincnet_norm1_b., hp.sincnet_filters_1cxx . . $ segmentation_hparams#sincnet_filters_1., false);
536
537 // Block 2
538 block(cxx . . $ sincnet_forward(135b33e7526ba24b).$anonymous_type_2#`operator()`(170d5311f14365d).model.sincnet_conv2_wcxx . . $ segmentation_model#sincnet_conv2_w., model.sincnet_conv2_bcxx . . $ segmentation_model#sincnet_conv2_b., 1,
539 model.sincnet_norm2_wcxx . . $ segmentation_model#sincnet_norm2_w., model.sincnet_norm2_bcxx . . $ segmentation_model#sincnet_norm2_b., hp.sincnet_filters_2cxx . . $ segmentation_hparams#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_NODEScxx . . $ `external/whispercpp/diarize.cpp:77:9`!, 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.backendcxx . . $ segmentation_context#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_filterscxx . . $ segmentation_context#sinc_filters..datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), 0,
554 sctx.sinc_filterscxx . . $ segmentation_context#sinc_filters..sizecxx . . $ std/vector#size(c9b1e749b64d5edc).() * sizeof(float));
555
556 ggml_backend_graph_compute(sctx.backendcxx . . $ segmentation_context#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.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(total);
562 ggml_backend_tensor_get(cur, output.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), 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_directioncxx . . $ lstm_one_direction(d87fbd5584ce5d32).(
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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> hcxx . . $ std/vector#vector(229e4d6bd205de31).(H, 0.f), ccxx . . $ std/vector#vector(229e4d6bd205de31).(H, 0.f), gatescxx . . $ std/vector#vector(83fdeebbe0501a83).(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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).j];
588 gates[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).g] = val;
589 }
590
591 for (int j = 0; j < H; j++) {
592 float ig = 1.f / (1.f + expf(-gates[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).0*H+j]));
593 float fg = 1.f / (1.f + expf(-gates[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).1*H+j]));
594 float gg = tanhf(gates[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*H+j]);
595 float og = 1.f / (1.f + expf(-gates[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).3*H+j]));
596 c[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).j] = fg * c[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).j] + ig * gg;
597 h[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).j] = og * tanhf(c[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).j]);
598 }
599 for (int j = 0; j < H; j++) out[t*H + j] = h[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> lstm_forwardcxx . . $ lstm_forward(7c23b40fd5985447).(const segmentation_modelcxx . . $ segmentation_model# & model, const float * input, int T) {
610 auto & hp = model.hparamscxx . . $ segmentation_model#hparams.;
611 const int H = hp.lstm_hidden_sizecxx . . $ segmentation_hparams#lstm_hidden_size.;
612 const int out_dim = hp.lstm_output_sizecxx . . $ segmentation_hparams#lstm_output_size(455f465bc33b4cdf).();
613
614 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> curcxx . . $ std/vector#vector(13e0640cd3842f28).(input, input + T * hp.lstm_input_sizecxx . . $ segmentation_hparams#lstm_input_size.);
615 int cur_input_size = hp.lstm_input_sizecxx . . $ segmentation_hparams#lstm_input_size.;
616
617 for (int l = 0; l < hp.lstm_layerscxx . . $ segmentation_hparams#lstm_layers.; l++) {
618 const float * w_ih_f = (const float*)model.lstm_weight_ihcxx . . $ segmentation_model#lstm_weight_ih.[l]->data;
619 const float * w_hh_f = (const float*)model.lstm_weight_hhcxx . . $ segmentation_model#lstm_weight_hh.[l]->data;
620 const float * b_ih_f = (const float*)model.lstm_bias_ihcxx . . $ segmentation_model#lstm_bias_ih.[l]->data;
621 const float * b_hh_f = (const float*)model.lstm_bias_hhcxx . . $ segmentation_model#lstm_bias_hh.[l]->data;
622 const float * w_ih_r = (const float*)model.lstm_weight_ih_revcxx . . $ segmentation_model#lstm_weight_ih_rev.[l]->data;
623 const float * w_hh_r = (const float*)model.lstm_weight_hh_revcxx . . $ segmentation_model#lstm_weight_hh_rev.[l]->data;
624 const float * b_ih_r = (const float*)model.lstm_bias_ih_revcxx . . $ segmentation_model#lstm_bias_ih_rev.[l]->data;
625 const float * b_hh_r = (const float*)model.lstm_bias_hh_revcxx . . $ segmentation_model#lstm_bias_hh_rev.[l]->data;
626
627 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> out_fwdcxx . . $ std/vector#vector(83fdeebbe0501a83).(T * H), out_revcxx . . $ std/vector#vector(83fdeebbe0501a83).(T * H);
628 lstm_one_directioncxx . . $ lstm_one_direction(d87fbd5584ce5d32).(cur.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), out_fwd.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), T, cur_input_size, H,
629 w_ih_f, w_hh_f, b_ih_f, b_hh_f, false);
630 lstm_one_directioncxx . . $ lstm_one_direction(d87fbd5584ce5d32).(cur.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), out_rev.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), T, cur_input_size, H,
631 w_ih_r, w_hh_r, b_ih_r, b_hh_r, true);
632
633 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> nextcxx . . $ std/vector#vector(83fdeebbe0501a83).(T * out_dim);
634 for (int t = 0; t < T; t++) {
635 for (int j = 0; j < H; j++) {
636 next[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).t * out_dim + j] = out_fwd[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).t * H + j];
637 next[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).t * out_dim + H + j] = out_rev[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).t * H + j];
638 }
639 }
640 cur =cxx . . $ std/vector#`operator=`(1104576815caab1a). stdcxx . . $ std/::move(next);
641 cur_input_size = out_dim;
642 }
643 return curcxx . . $ std/vector#vector(6f559d22b039ccdb).;
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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> linear_leaky_relucxx . . $ linear_leaky_relu(6e14f184c9c68b86).(const float * x, int T, int in_f, int out_f,
653 const float * weight, const float * bias) {
654 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> outcxx . . $ std/vector#vector(83fdeebbe0501a83).(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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).t * out_f + o] = (val < 0) ? 0.01f * val : val;
660 }
661 }
662 return outcxx . . $ std/vector#vector(6f559d22b039ccdb).;
663 }
664
665 static stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> linear_forward_rawcxx . . $ linear_forward_raw(6e14f184c9c68b86).(const float * x, int T, int in_f, int out_f,
666 const float * weight, const float * bias) {
667 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> outcxx . . $ std/vector#vector(83fdeebbe0501a83).(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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).t * out_f + o] = val;
673 }
674 }
675 return outcxx . . $ std/vector#vector(6f559d22b039ccdb).;
676 }
677
678 static stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> log_softmaxcxx . . $ log_softmax(3e14fb3c78f6aa70).(const float * x, const int T, const int C) {
679 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> outcxx . . $ std/vector#vector(83fdeebbe0501a83).(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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).t * C + j] = row[j] - ls;
688 }
689 return outcxx . . $ std/vector#vector(6f559d22b039ccdb).;
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_forwardcxx . . $ segmentation_forward(135b33e7526ba24b).(segmentation_contextcxx . . $ segmentation_context# & sctx, const float * samples, int n_samples,
699 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> & result, int & n_frames, int & n_classes) {
700 //TRACE
701 const auto & model = sctx.modelcxx . . $ segmentation_context#model.;
702 auto & hp = model.hparamscxx . . $ segmentation_model#hparams.;
703
704 // 1. SincNet (GGML graph)
705 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> sincnet_outcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
706 int sn_time, sn_ch;
707
708 auto t0 = stdcxx . . $ std/::chronocxx . . $ std/chrono/::high_resolution_clockcxx . . $ std/chrono/_V2/high_resolution_clock#::nowcxx . . $ std/chrono/_V2/system_clock#now(3657dacbd9b4f607).();
709
710 if (!sincnet_forwardcxx . . $ sincnet_forward(135b33e7526ba24b).(sctx, samples, n_samples, sincnet_out, sn_time, sn_ch)) {
711 return false;
712 }
713 auto t1 = stdcxx . . $ std/::chronocxx . . $ std/chrono/::high_resolution_clockcxx . . $ std/chrono/_V2/high_resolution_clock#::nowcxx . . $ std/chrono/_V2/system_clock#now(3657dacbd9b4f607).();
714 tracecxx . . $ `melder/melder_debug.h:60:10`! (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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> lstm_incxx . . $ std/vector#vector(83fdeebbe0501a83).(T * sn_ch);
723 for (int t = 0; t < T; t++) {
724 for (int c = 0; c < sn_ch; c++) {
725 lstm_in[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).t * sn_ch + c] = sincnet_out[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).c * T + t];
726 }
727 }
728
729 // 2. LSTM (plain C++)
730 const auto lstm_out = lstm_forwardcxx . . $ lstm_forward(7c23b40fd5985447).(model, lstm_in.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), T);
731 auto t2 = stdcxx . . $ std/::chronocxx . . $ std/chrono/::high_resolution_clockcxx . . $ std/chrono/_V2/high_resolution_clock#::nowcxx . . $ std/chrono/_V2/system_clock#now(3657dacbd9b4f607).();
732 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"LSTM output: [", T, U", ", hp.lstm_output_size(), U"]");
733
734 // 3. Linear layers
735 const float * cur = lstm_out.datacxx . . $ std/vector#data(8e614c7de0b1573e).();
736 int cur_dim = hp.lstm_output_sizecxx . . $ segmentation_hparams#lstm_output_size(455f465bc33b4cdf).();
737
738 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> lin_outcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
739 for (int l = 0; l < hp.linear_layerscxx . . $ segmentation_hparams#linear_layers.; l++) {
740 lin_out =cxx . . $ std/vector#`operator=`(1104576815caab1a). linear_leaky_relucxx . . $ linear_leaky_relu(6e14f184c9c68b86).(cur, T, cur_dim, hp.linear_hiddencxx . . $ segmentation_hparams#linear_hidden.,
741 (const float*)model.linear_wcxx . . $ segmentation_model#linear_w.[l]->data,
742 (const float*)model.linear_bcxx . . $ segmentation_model#linear_b.[l]->data);
743 cur = lin_out.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).();
744 cur_dim = hp.linear_hiddencxx . . $ segmentation_hparams#linear_hidden.;
745 }
746
747 // 4. Classifier
748 auto cls_out = linear_forward_rawcxx . . $ linear_forward_raw(6e14f184c9c68b86).(cur, T, cur_dim, hp.n_classescxx . . $ segmentation_hparams#n_classes.,
749 (const float*)model.classifier_wcxx . . $ segmentation_model#classifier_w.->data,
750 (const float*)model.classifier_bcxx . . $ segmentation_model#classifier_b.->data);
751
752 // 5. Log-softmax activation
753 result =cxx . . $ std/vector#`operator=`(1104576815caab1a). log_softmaxcxx . . $ log_softmax(3e14fb3c78f6aa70).(cls_out.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), T, hp.n_classescxx . . $ segmentation_hparams#n_classes.);
754 auto t3 = stdcxx . . $ std/::chronocxx . . $ std/chrono/::high_resolution_clockcxx . . $ std/chrono/_V2/high_resolution_clock#::nowcxx . . $ std/chrono/_V2/system_clock#now(3657dacbd9b4f607).();
755
756 n_frames = T;
757 n_classes = hp.n_classescxx . . $ segmentation_hparams#n_classes.;
758
759 if (Melder_debugcxx . . $ Melder_debug. == 2004) {
760 auto us = [](auto a, auto b) {
761 return stdcxx . . $ std/::chronocxx . . $ std/chrono/::duration_castcxx . . $ std/chrono/duration_cast(b7f67bf9c2f19806).<stdcxx . . $ std/::chronocxx . . $ std/chrono/::microsecondscxx . . $ std/chrono/microseconds#>(b -cxx . . $ operator-(8538f57502d6bea9). a).count();
762 };
763 g_seg_sincnet_uscxx . . $ g_seg_sincnet_us. +=cxx . . $ std/__atomic_base#`operator+=`(73de6b30e1938209). us(cxx . . $ segmentation_forward(135b33e7526ba24b).$anonymous_type_3#`operator()`(e5e5cabccbaf6ef5).t0, t1);
764 g_seg_lstm_uscxx . . $ g_seg_lstm_us. +=cxx . . $ std/__atomic_base#`operator+=`(73de6b30e1938209). us(cxx . . $ segmentation_forward(135b33e7526ba24b).$anonymous_type_3#`operator()`(e5e5cabccbaf6ef5).t1, t2);
765 g_seg_linear_uscxx . . $ g_seg_linear_us. +=cxx . . $ std/__atomic_base#`operator+=`(73de6b30e1938209). us(cxx . . $ segmentation_forward(135b33e7526ba24b).$anonymous_type_3#`operator()`(e5e5cabccbaf6ef5).t2, t3);
766 ++cxx . . $ std/__atomic_base#operator++(6390f2d371ad8d1d). g_seg_callscxx . . $ g_seg_calls.;
767 }
768
769 return true;
770 }
771
772 // ============================================================================
773 // Segmentation: Init / Free
774 // ============================================================================
775 static void segmentation_initcxx . . $ segmentation_init(1797d58214d88945).(segmentation_contextcxx . . $ segmentation_context# & sctx, diarize_model_loader * loader) {
776 //TRACE
777 try {
778 segmentation_load_modelcxx . . $ segmentation_load_model(a8bd3d8b0e1e30a6).(loader, sctx.modelcxx . . $ segmentation_context#model.);
779 } catch (MelderErrorcxx . . $ MelderError#) {
780 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (U"Could not load segmentation model.");
781 }
782
783 sctx.sinc_filterscxx . . $ segmentation_context#sinc_filters. =cxx . . $ std/vector#`operator=`(1104576815caab1a). compute_sinc_filterscxx . . $ compute_sinc_filters(1de572a9a165651f).(sctx.modelcxx . . $ segmentation_context#model.);
784 sctx.backendcxx . . $ segmentation_context#backend. = ggml_backend_cpu_init();
785
786 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"Initialized (", sctx.model.hparams.n_filters(), U" sinc filters, ", sctx.model.hparams.sincnet_kernel_0, U" kernel)");
787 }
788
789 static void segmentation_freecxx . . $ segmentation_free(26075c468d49fb47).(segmentation_contextcxx . . $ segmentation_context# & sctx) {
790 if (sctx.backendcxx . . $ segmentation_context#backend.)
791 ggml_backend_free(sctx.backendcxx . . $ segmentation_context#backend.);
792 for (auto buf : sctx.modelcxx . . $ segmentation_context#model..bufferscxx . . $ segmentation_model#buffers.)
793 ggml_backend_buffer_free(buf);
794 for (auto ctx : sctx.modelcxx . . $ segmentation_context#model..ctxscxx . . $ segmentation_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_hparamscxx . . $ embedding_hparams# {
818 int32_t m_channelscxx . . $ embedding_hparams#m_channels.; // 32
819 int32_t feat_dimcxx . . $ embedding_hparams#feat_dim.; // 80 (mel bins)
820 int32_t embed_dimcxx . . $ embedding_hparams#embed_dim.; // 256
821 int32_t num_blockscxx . . $ embedding_hparams#num_blocks.[4]; // [3, 4, 6, 3]
822 int32_t two_emb_layercxx . . $ embedding_hparams#two_emb_layer.; // 0
823
824 int chcxx . . $ embedding_hparams#ch(7ccb52b1bfe01045).(int layer) const { return m_channelscxx . . $ embedding_hparams#m_channels. * (1 << (layer - 1)); }
825 };
826
827 struct embedding_modelcxx . . $ embedding_model# {
828 embedding_hparamscxx . . $ embedding_hparams# hparamscxx . . $ embedding_model#hparams.;
829 stdcxx . . $ std/::mapcxx . . $ std/map#<stdcxx . . $ std/::stringcxx . . $ std/string#, struct ggml_tensor *> tensorscxx . . $ embedding_model#tensors.;
830 int n_loadedcxx . . $ embedding_model#n_loaded. = 0;
831 stdcxx . . $ std/::vectorcxx . . $ std/vector#<ggml_context *> ctxscxx . . $ embedding_model#ctxs.;
832 stdcxx . . $ std/::vectorcxx . . $ std/vector#<ggml_backend_buffer_t> bufferscxx . . $ embedding_model#buffers.;
833 };
834
835 struct embedding_contextcxx . . $ embedding_context# {
836 embedding_modelcxx . . $ embedding_model# modelcxx . . $ embedding_context#model.;
837 ggml_backend_t backendcxx . . $ embedding_context#backend. = nullptr;
838 };
839
840 // ============================================================================
841 // Embedding: Model loading
842 // ============================================================================
843 static void embedding_load_modelcxx . . $ embedding_load_model(7c5c81a58be2be40).(diarize_model_loader * loader, embedding_modelcxx . . $ embedding_model# & model) {
844 //TRACE
845 uint32_tcxx . . $ uint32_t# magic;
846 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, magic);
847 if (magic != GGML_FILE_MAGICcxx . . $ `external/whispercpp/diarize.cpp:67:9`!)
848 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (U"Invalid model data (bad magic).");
849
850 auto & hp = model.hparamscxx . . $ embedding_model#hparams.;
851 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.m_channelscxx . . $ embedding_hparams#m_channels.);
852 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.feat_dimcxx . . $ embedding_hparams#feat_dim.);
853 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.embed_dimcxx . . $ embedding_hparams#embed_dim.);
854 for (int i = 0; i < 4; i++)
855 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.num_blockscxx . . $ embedding_hparams#num_blocks.[i]);
856 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, hp.two_emb_layercxx . . $ embedding_hparams#two_emb_layer.);
857
858 tracecxx . . $ `melder/melder_debug.h:60:10`! (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_blockscxx . . $ embedding_hparams#num_blocks.[0] + hp.num_blockscxx . . $ embedding_hparams#num_blocks.[1] + hp.num_blockscxx . . $ embedding_hparams#num_blocks.[2] + hp.num_blockscxx . . $ embedding_hparams#num_blocks.[3];
864 size_t n_tensors = 5 + total_blocks * 10 + 3 * 5 + 2;
865 if (hp.two_emb_layercxx . . $ embedding_hparams#two_emb_layer.)
866 n_tensors += 2;
867
868 // Create tensors
869 stdcxx . . $ std/::mapcxx . . $ std/map#<ggml_backend_buffer_type_t, ggml_context *> ctx_mapcxx . . $ std/map#map(49f6e7a06ebc5aa8).;
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.findcxx . . $ std/map#find(36f8d56706583706).(buft);
874 if (it ==cxx . . $ std/`operator==`(be6a71a859368080). ctx_map.endcxx . . $ std/map#end(7e4de33083b6e738).()) {
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[cxx . . $ std/map#`operator[]`(bbd415b616967878).buft] = ctx;
882 model.ctxscxx . . $ embedding_model#ctxs..push_backcxx . . $ std/vector#push_back(77d9f17553126ecb).(ctx);
883 return ctx;
884 }
885 return it->cxx . . $ std/_Rb_tree_iterator#`operator->`(34d6acfd341ba7ab).second;
886 };
887
888 auto CT = [&](const stdcxx . . $ std/::stringcxx . . $ std/string# & name, ggml_tensor * meta) -> ggml_tensor * {
889 ggml_context * ctx = get_ctx(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_4#`operator()`(986c283657a23dc8).cpu_buft);
890 ggml_tensor * t = ggml_dup_tensor(ctx, meta);
891 ggml_set_name(t, name.c_strcxx . . $ std/__cxx11/basic_string#c_str(8e614c7de0b1573e).());
892 model.tensorscxx . . $ embedding_model#tensors.[cxx . . $ std/map#`operator[]`(bbd415b616967878).name] = t;
893 return t;
894 };
895
896 auto create_bn = [&](ggml_context * ctx, const stdcxx . . $ std/::stringcxx . . $ std/string# & prefix, int channels) {
897 CT(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_5#`operator()`(f703bb206d6e343f).prefix +cxx . . $ std/operator+(40fc1db9226233c6). ".weight", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, channels));
898 CT(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_5#`operator()`(f703bb206d6e343f).prefix +cxx . . $ std/operator+(40fc1db9226233c6). ".bias", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, channels));
899 CT(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_5#`operator()`(f703bb206d6e343f).prefix +cxx . . $ std/operator+(40fc1db9226233c6). ".running_mean", ggml_new_tensor_1d(ctx, GGML_TYPE_F32, channels));
900 CT(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_5#`operator()`(f703bb206d6e343f).prefix +cxx . . $ std/operator+(40fc1db9226233c6). ".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(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_5#`operator()`(f703bb206d6e343f)."resnet.conv1.weight"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 3, 3, 1, hp.m_channelscxx . . $ embedding_hparams#m_channels.));
913 create_bn(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_6#`operator()`(92b5b1b8dfb0a47b).ctx, "resnet.bn1"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., hp.m_channelscxx . . $ embedding_hparams#m_channels.);
914
915 // ResNet layers
916 int in_ch = hp.m_channelscxx . . $ embedding_hparams#m_channels.;
917 for (int layer = 1; layer <= 4; layer++) {
918 int out_ch = hp.chcxx . . $ embedding_hparams#ch(7ccb52b1bfe01045).(layer);
919 int stride_first = (layer == 1) ? 1 : 2;
920 stdcxx . . $ std/::stringcxx . . $ std/string# lp = "resnet.layer" +cxx . . $ std/operator+(39ed2c165380f78e). stdcxx . . $ std/::to_stringcxx . . $ std/__cxx11/to_string(3d81e17e7a87eecc).(layer);
921 for (int blk = 0; blk < hp.num_blockscxx . . $ embedding_hparams#num_blocks.[layer-1]; blk++) {
922 stdcxx . . $ std/::stringcxx . . $ std/string# bp = lp +cxx . . $ std/operator+(40fc1db9226233c6). "." +cxx . . $ std/operator+(aa1c00e85b87da6b). stdcxx . . $ std/::to_stringcxx . . $ std/__cxx11/to_string(3d81e17e7a87eecc).(blk);
923 int blk_in = (blk == 0) ? in_ch : out_ch;
924 CT(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_5#`operator()`(f703bb206d6e343f).bp +cxx . . $ std/operator+(40fc1db9226233c6). ".conv1.weight", ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 3, 3, blk_in, out_ch));
925 create_bn(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_6#`operator()`(92b5b1b8dfb0a47b).ctx, bp +cxx . . $ std/operator+(40fc1db9226233c6). ".bn1", out_ch);
926 CT(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_5#`operator()`(f703bb206d6e343f).bp +cxx . . $ std/operator+(40fc1db9226233c6). ".conv2.weight", ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 3, 3, out_ch, out_ch));
927 create_bn(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_6#`operator()`(92b5b1b8dfb0a47b).ctx, bp +cxx . . $ std/operator+(40fc1db9226233c6). ".bn2", out_ch);
928 if (blk == 0 && (stride_first != 1 || in_ch != out_ch)) {
929 CT(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_5#`operator()`(f703bb206d6e343f).bp +cxx . . $ std/operator+(40fc1db9226233c6). ".shortcut.0.weight", ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, 1, in_ch, out_ch));
930 create_bn(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_6#`operator()`(92b5b1b8dfb0a47b).ctx, bp +cxx . . $ std/operator+(40fc1db9226233c6). ".shortcut.1", out_ch);
931 }
932 }
933 in_ch = out_ch;
934 }
935
936 // seg_1
937 int stats_dim = (hp.feat_dimcxx . . $ embedding_hparams#feat_dim. / 8) * hp.m_channelscxx . . $ embedding_hparams#m_channels. * 8;
938 int pool_out = stats_dim * 2;
939 CT(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_5#`operator()`(f703bb206d6e343f)."resnet.seg_1.weight"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_2d(ctx, GGML_TYPE_F32, pool_out, hp.embed_dimcxx . . $ embedding_hparams#embed_dim.));
940 CT(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_5#`operator()`(f703bb206d6e343f)."resnet.seg_1.bias"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.embed_dimcxx . . $ embedding_hparams#embed_dim.));
941 if (hp.two_emb_layercxx . . $ embedding_hparams#two_emb_layer.) {
942 CT(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_5#`operator()`(f703bb206d6e343f)."resnet.seg_2.weight"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_2d(ctx, GGML_TYPE_F32, hp.embed_dimcxx . . $ embedding_hparams#embed_dim., hp.embed_dimcxx . . $ embedding_hparams#embed_dim.));
943 CT(cxx . . $ embedding_load_model(7c5c81a58be2be40).$anonymous_type_5#`operator()`(f703bb206d6e343f)."resnet.seg_2.bias"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.embed_dimcxx . . $ embedding_hparams#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.bufferscxx . . $ embedding_model#buffers..push_backcxx . . $ std/vector#push_back(77d9f17553126ecb).(buf);
953 }
954
955 // Load weights
956 model.n_loadedcxx . . $ embedding_model#n_loaded. = 0;
957 stdcxx . . $ std/::vectorcxx . . $ std/vector#<char> read_bufcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
958 while (true) {
959 int32_t n_dims, length, ttype;
960 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, n_dims);
961 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, length);
962 read_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(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_safecxx . . $ read_safe(aa6b70e9e1f8ed33).(loader, ne[i]);
970 n_elements *= ne[i];
971 }
972 stdcxx . . $ std/::stringcxx . . $ std/string# namecxx . . $ std/__cxx11/basic_string#basic_string(57f9c416bbf2a7d6).(length, 0);
973 loader->read(loader->context, name.datacxx . . $ std/__cxx11/basic_string#data(258ee1c9e0a18a5c).(), length);
974
975 auto it = model.tensorscxx . . $ embedding_model#tensors..findcxx . . $ std/map#find(36f8d56706583706).(name);
976 if (it ==cxx . . $ std/`operator==`(be6a71a859368080). model.tensorscxx . . $ embedding_model#tensors..endcxx . . $ std/map#end(7e4de33083b6e738).())
977 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (U"Unknown tensor '", Melder_peek8to32_u (name.c_str()), U"'");
978
979 auto tensor = it->cxx . . $ std/_Rb_tree_iterator#`operator->`(34d6acfd341ba7ab).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_TENSORcxx . . $ `external/whispercpp/diarize.cpp:132:9`!(tensor);
985 } else {
986 read_buf.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(ggml_nbytes(tensor));
987 loader->read(loader->context, read_buf.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), read_buf.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).());
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.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), 0, ggml_nbytes(tensor));
991 }
992 model.n_loadedcxx . . $ embedding_model#n_loaded.++;
993 }
994
995 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"Loaded ", model.n_loaded, U"/", model.tensors.size(), U" tensors");
996 if (model.n_loadedcxx . . $ embedding_model#n_loaded. != model.tensorscxx . . $ embedding_model#tensors..sizecxx . . $ std/map#size(a08d7b23eb6940f6).())
997 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (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_scalecxx . . $ mel_scale(fbcf3211dfe1bfd1).(float freq) {
1004 return 1127.0f * logf(1.0f + freq / 700.0f);
1005 }
1006
1007 static void build_mel_filterbankcxx . . $ build_mel_filterbank(8b845384afff1540).(int num_mel_bins, int padded_window_size,
1008 float sample_rate, float low_freq, float high_freq,
1009 stdcxx . . $ std/::vectorcxx . . $ std/vector#<stdcxx . . $ std/::vectorcxx . . $ 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_scalecxx . . $ mel_scale(fbcf3211dfe1bfd1).(low_freq), mel_high = mel_scalecxx . . $ mel_scale(fbcf3211dfe1bfd1).(high_freq);
1014 int num_bins = num_mel_bins + 2;
1015 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> mel_pointscxx . . $ std/vector#vector(83fdeebbe0501a83).(num_bins);
1016 for (int i = 0; i < num_bins; i++)
1017 mel_points[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = mel_low + (mel_high - mel_low) * i / (num_bins - 1);
1018 filterbank.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(num_mel_bins);
1019 for (int m = 0; m < num_mel_bins; m++) {
1020 float left = mel_points[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).m], center = mel_points[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).m+1], right = mel_points[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).m+2];
1021 filterbank[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).m].assigncxx . . $ std/vector#assign(3804226c8c0acbc3).(num_fft_bins, 0.0f);
1022 for (int k = 0; k < num_fft_bins; k++) {
1023 float fmel = mel_scalecxx . . $ mel_scale(fbcf3211dfe1bfd1).(fft_bin_width * k);
1024 if (fmel > left && fmel <= center)
1025 filterbank[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).m][cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k] = (fmel - left) / (center - left);
1026 else if (fmel > center && fmel < right)
1027 filterbank[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).m][cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k] = (right - fmel) / (right - center);
1028 }
1029 }
1030 }
1031
1032 static void fft_radix2cxx . . $ fft_radix2(b7d9f7ea4f4e34d4).(const float * in, int N, float * out) {
1033 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> bufcxx . . $ std/vector#vector(83fdeebbe0501a83).(2 * N);
1034 for (int i = 0; i < N; i++) { buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*i] = in[i]; buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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) { stdcxx . . $ std/::swap(buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*i], buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*j]); stdcxx . . $ std/::swap(buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*i+1], buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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_PIcxx . . $ `melder/NUMmath.h:48:9`! / m), wm_im = sinf(-2.0f * (float)M_PIcxx . . $ `melder/NUMmath.h:48:9`! / 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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*o] - w_im*buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*o+1], t_im = w_re*buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*o+1] + w_im*buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*o];
1050 buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*o] = buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*e] - t_re; buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*o+1] = buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*e+1] - t_im;
1051 buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*e] += t_re; buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*i]; out[2*i+1] = buf[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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_fbankcxx . . $ compute_fbank(e1bee4b1e008b39e).(const float * samples, int n_samples,
1063 stdcxx . . $ std/::vectorcxx . . $ 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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> scaledcxx . . $ std/vector#vector(83fdeebbe0501a83).(n_samples);
1075 for (int i = 0; i < n_samples; i++) scaled[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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.clearcxx . . $ std/vector#clear(ced63f7c635d850d).(); return; }
1081
1082 // Hamming window
1083 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> hammingcxx . . $ std/vector#vector(83fdeebbe0501a83).(frame_length);
1084 for (int i = 0; i < frame_length; i++)
1085 hamming[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = 0.54f - 0.46f * cosf(2.0f * (float)M_PIcxx . . $ `melder/NUMmath.h:48:9`! * i / (frame_length - 1));
1086
1087 // Mel filterbank
1088 stdcxx . . $ std/::vectorcxx . . $ std/vector#<stdcxx . . $ std/::vectorcxx . . $ std/vector#<float>> mel_filterscxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1089 build_mel_filterbankcxx . . $ build_mel_filterbank(8b845384afff1540).(num_mel_bins, padded_window_size, sample_rate, 20.0f, 0.0f, mel_filters);
1090
1091 // Process frames
1092 fbank_out.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(num_frames * num_mel_bins);
1093 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> framecxx . . $ std/vector#vector(229e4d6bd205de31).(padded_window_size, 0.0f);
1094 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> fft_outcxx . . $ std/vector#vector(83fdeebbe0501a83).(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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = scaled[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).offset + i];
1099 for (int i = frame_length; i < padded_window_size; i++) frame[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = 0.0f;
1100
1101 // Remove DC offset
1102 float dc = 0.0f;
1103 for (int i = 0; i < frame_length; i++) dc += frame[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i];
1104 dc /= frame_length;
1105 for (int i = 0; i < frame_length; i++) frame[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] -= dc;
1106
1107 // Pre-emphasis
1108 for (int i = frame_length - 1; i > 0; i--) frame[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] -= preemphasis * frame[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i-1];
1109 frame[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).0] -= preemphasis * frame[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).0];
1110
1111 // Hamming window
1112 for (int i = 0; i < frame_length; i++) frame[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] *= hamming[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i];
1113
1114 // FFT -> power spectrum
1115 fft_radix2cxx . . $ fft_radix2(b7d9f7ea4f4e34d4).(frame.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), padded_window_size, fft_out.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).());
1116 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> powercxx . . $ std/vector#vector(83fdeebbe0501a83).(n_fft_bins + 1);
1117 for (int k = 0; k <= n_fft_bins; k++)
1118 power[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k] = fft_out[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*k]*fft_out[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*k] + fft_out[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).2*k+1]*fft_out[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k] * mel_filters[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).m][cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k];
1124 float val = (float)sum;
1125 if (val < epsilon) val = epsilon;
1126 fbank_out[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).f * num_mel_bins + m];
1134 float mean = (float)(sum / num_frames);
1135 for (int f = 0; f < num_frames; f++) fbank_out[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).f * num_mel_bins + m] -= mean;
1136 }
1137 }
1138
1139 // ============================================================================
1140 // Embedding: Conv2d via GGML graph
1141 // ============================================================================
1142 static bool conv2d_forwardcxx . . $ conv2d_forward(a0305881f32e30fb).(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 stdcxx . . $ std/::vectorcxx . . $ 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_NODEScxx . . $ `external/whispercpp/diarize.cpp:78:9`! + 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_NODEScxx . . $ `external/whispercpp/diarize.cpp:78:9`!, 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.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(N * OC * OH * OW);
1168 ggml_backend_tensor_get(conv_out, output.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), 0, output.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).() * 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 batchnorm2dcxx . . $ batchnorm2d(de1d33f7beb748c9).(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_bncxx . . $ apply_bn(2e525d099eb78946).(embedding_modelcxx . . $ embedding_model# & m, const stdcxx . . $ std/::stringcxx . . $ std/string# & pfx,
1190 float * data, int N, int C, int H, int W) {
1191 batchnorm2dcxx . . $ batchnorm2d(de1d33f7beb748c9).(data, N, C, H, W,
1192 (float*)m.tensorscxx . . $ embedding_model#tensors.[cxx . . $ std/map#`operator[]`(da459db78e6e18a3).pfx+cxx . . $ std/operator+(40fc1db9226233c6).".weight"]->data, (float*)m.tensorscxx . . $ embedding_model#tensors.[cxx . . $ std/map#`operator[]`(da459db78e6e18a3).pfx+cxx . . $ std/operator+(40fc1db9226233c6).".bias"]->data,
1193 (float*)m.tensorscxx . . $ embedding_model#tensors.[cxx . . $ std/map#`operator[]`(da459db78e6e18a3).pfx+cxx . . $ std/operator+(40fc1db9226233c6).".running_mean"]->data, (float*)m.tensorscxx . . $ embedding_model#tensors.[cxx . . $ std/map#`operator[]`(da459db78e6e18a3).pfx+cxx . . $ std/operator+(40fc1db9226233c6).".running_var"]->data);
1194 }
1195
1196 static void relu_inplacecxx . . $ relu_inplace(119c4c84b133c40b).(float * d, int n) { for (int i = 0; i < n; i++) if (d[i] < 0.f) d[i] = 0.f; }
1197 static void add_inplacecxx . . $ add_inplace(8e5bb7dd50cd87b6).(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_forwardcxx . . $ basic_block_forward(788188f2ed5b3119).(ggml_backend_t backend, embedding_modelcxx . . $ embedding_model# & model,
1203 const stdcxx . . $ std/::stringcxx . . $ std/string# & prefix, const float * input,
1204 int N, int in_C, int H, int W, int stride, bool has_shortcut,
1205 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> & output, int & oH, int & oW, int & oC) {
1206 // Main path: conv1 + bn1 + relu
1207 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> t1cxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1208 int h1, w1, c1;
1209 conv2d_forwardcxx . . $ conv2d_forward(a0305881f32e30fb).(backend, model.tensorscxx . . $ embedding_model#tensors.[cxx . . $ std/map#`operator[]`(da459db78e6e18a3).prefix+cxx . . $ std/operator+(40fc1db9226233c6).".conv1.weight"], input, N, in_C, H, W, stride, 1, t1, h1, w1, c1);
1210 apply_bncxx . . $ apply_bn(2e525d099eb78946).(model, prefix+cxx . . $ std/operator+(40fc1db9226233c6).".bn1", t1.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), N, c1, h1, w1);
1211 relu_inplacecxx . . $ relu_inplace(119c4c84b133c40b).(t1.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), t1.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).());
1212
1213 // Main path: conv2 + bn2
1214 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> t2cxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1215 conv2d_forwardcxx . . $ conv2d_forward(a0305881f32e30fb).(backend, model.tensorscxx . . $ embedding_model#tensors.[cxx . . $ std/map#`operator[]`(da459db78e6e18a3).prefix+cxx . . $ std/operator+(40fc1db9226233c6).".conv2.weight"], t1.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), N, c1, h1, w1, 1, 1, t2, oH, oW, oC);
1216 apply_bncxx . . $ apply_bn(2e525d099eb78946).(model, prefix+cxx . . $ std/operator+(40fc1db9226233c6).".bn2", t2.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), N, oC, oH, oW);
1217
1218 // Residual
1219 if (has_shortcut) {
1220 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> sccxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1221 int sH, sW, sC;
1222 conv2d_forwardcxx . . $ conv2d_forward(a0305881f32e30fb).(backend, model.tensorscxx . . $ embedding_model#tensors.[cxx . . $ std/map#`operator[]`(da459db78e6e18a3).prefix+cxx . . $ std/operator+(40fc1db9226233c6).".shortcut.0.weight"], input, N, in_C, H, W, stride, 0, sc, sH, sW, sC);
1223 apply_bncxx . . $ apply_bn(2e525d099eb78946).(model, prefix+cxx . . $ std/operator+(40fc1db9226233c6).".shortcut.1", sc.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), N, sC, sH, sW);
1224 add_inplacecxx . . $ add_inplace(8e5bb7dd50cd87b6).(t2.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), sc.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), t2.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).());
1225 } else {
1226 add_inplacecxx . . $ add_inplace(8e5bb7dd50cd87b6).(t2.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), input, t2.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).());
1227 }
1228 relu_inplacecxx . . $ relu_inplace(119c4c84b133c40b).(t2.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), t2.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).());
1229 output =cxx . . $ std/vector#`operator=`(1104576815caab1a). stdcxx . . $ std/::move(t2);
1230 return true;
1231 }
1232
1233 // ============================================================================
1234 // Embedding: Run a full ResNet layer
1235 // ============================================================================
1236 static bool run_layercxx . . $ run_layer(30e05a31a4d69dc4).(ggml_backend_t backend, embedding_modelcxx . . $ embedding_model# & model, int layer_idx,
1237 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> & cur, int & N, int & C, int & H, int & W) {
1238 int out_ch = model.hparamscxx . . $ embedding_model#hparams..chcxx . . $ embedding_hparams#ch(7ccb52b1bfe01045).(layer_idx);
1239 int stride_first = (layer_idx == 1) ? 1 : 2;
1240 stdcxx . . $ std/::stringcxx . . $ std/string# lp = "resnet.layer" +cxx . . $ std/operator+(39ed2c165380f78e). stdcxx . . $ std/::to_stringcxx . . $ std/__cxx11/to_string(3d81e17e7a87eecc).(layer_idx);
1241
1242 for (int blk = 0; blk < model.hparamscxx . . $ embedding_model#hparams..num_blockscxx . . $ embedding_hparams#num_blocks.[layer_idx-1]; blk++) {
1243 stdcxx . . $ std/::stringcxx . . $ std/string# prefix = lp +cxx . . $ std/operator+(40fc1db9226233c6). "." +cxx . . $ std/operator+(aa1c00e85b87da6b). stdcxx . . $ std/::to_stringcxx . . $ std/__cxx11/to_string(3d81e17e7a87eecc).(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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> outcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1249 int bH, bW, bC;
1250 if (!basic_block_forwardcxx . . $ basic_block_forward(788188f2ed5b3119).(backend, model, prefix, cur.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), N, blk_in_ch, H, W,
1251 blk_stride, has_sc, out, bH, bW, bC)) return false;
1252 cur =cxx . . $ std/vector#`operator=`(1104576815caab1a). stdcxx . . $ 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_poolingcxx . . $ tstp_pooling(3e301e20c4f77aa0).(const float * data, int N, int C, int H, int W,
1262 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> & stats) {
1263 int feat_dim = C * H;
1264 stats.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(N * feat_dim * 2);
1265 for (int n = 0; n < N; n++) {
1266 float * mean_out = &stats[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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)sqrtcxx . . $ sqrt(fee4f1d22bc8e617).(var_sum / (W - 1) + 1e-7);
1278 }
1279 }
1280 }
1281 }
1282
1283 // ============================================================================
1284 // Embedding: Linear layer
1285 // ============================================================================
1286 static void linear_forwardcxx . . $ linear_forward(abd8016ae042aaee).(const float * input, int N, int in_dim,
1287 const float * weight, const float * bias, int out_dim,
1288 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> & output) {
1289 output.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).n*out_dim + o] = sum;
1296 }
1297 }
1298
1299 // ============================================================================
1300 // Embedding: Full forward pass: raw PCM -> 256-d embedding
1301 // ============================================================================
1302 static bool embedding_forwardcxx . . $ embedding_forward(8dcc40b580703ae0).(embedding_contextcxx . . $ embedding_context# & ectx,
1303 const float * samples, int n_samples,
1304 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> & embedding_out) {
1305 //TRACE
1306 auto & model = ectx.modelcxx . . $ embedding_context#model.;
1307 auto & hp = model.hparamscxx . . $ embedding_model#hparams.;
1308
1309 auto t0 = stdcxx . . $ std/::chronocxx . . $ std/chrono/::high_resolution_clockcxx . . $ std/chrono/_V2/high_resolution_clock#::nowcxx . . $ std/chrono/_V2/system_clock#now(3657dacbd9b4f607).();
1310
1311 // 1. Fbank extraction
1312 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> fbankcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1313 int num_frames;
1314 compute_fbankcxx . . $ compute_fbank(e1bee4b1e008b39e).(samples, n_samples, fbank, num_frames);
1315 if (num_frames == 0) {
1316 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"Audio too short for fbank");
1317 return false;
1318 }
1319 tracecxx . . $ `melder/melder_debug.h:60:10`! (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_dimcxx . . $ embedding_hparams#feat_dim., W = num_frames;
1323 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> curcxx . . $ std/vector#vector(83fdeebbe0501a83).(N * C * H * W);
1324 for (int t = 0; t < W; t++)
1325 for (int f = 0; f < H; f++)
1326 cur[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).f * W + t] = fbank[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).t * H + f];
1327 auto t1 = stdcxx . . $ std/::chronocxx . . $ std/chrono/::high_resolution_clockcxx . . $ std/chrono/_V2/high_resolution_clock#::nowcxx . . $ std/chrono/_V2/system_clock#now(3657dacbd9b4f607).();
1328
1329 // 3. Stem: conv1 + bn1 + relu
1330 {
1331 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> conv_outcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1332 int OH, OW, OC;
1333 conv2d_forwardcxx . . $ conv2d_forward(a0305881f32e30fb).(ectx.backendcxx . . $ embedding_context#backend., model.tensorscxx . . $ embedding_model#tensors.[cxx . . $ std/map#`operator[]`(da459db78e6e18a3)."resnet.conv1.weight"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d).],
1334 cur.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), N, C, H, W, 1, 1, conv_out, OH, OW, OC);
1335 apply_bncxx . . $ apply_bn(2e525d099eb78946).(model, "resnet.bn1"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d)., conv_out.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), N, OC, OH, OW);
1336 relu_inplacecxx . . $ relu_inplace(119c4c84b133c40b).(conv_out.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), conv_out.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).());
1337 cur =cxx . . $ std/vector#`operator=`(e6b68e61becad66f). conv_out; C = OC; H = OH; W = OW;
1338 }
1339 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"stem: (", N, U", ", C, U", ", H, U", ", W, U")");
1340 auto t2 = stdcxx . . $ std/::chronocxx . . $ std/chrono/::high_resolution_clockcxx . . $ std/chrono/_V2/high_resolution_clock#::nowcxx . . $ std/chrono/_V2/system_clock#now(3657dacbd9b4f607).();
1341
1342 // 4. ResNet layers 1-4
1343 for (int layer = 1; layer <= 4; layer++) {
1344 if (!run_layercxx . . $ run_layer(30e05a31a4d69dc4).(ectx.backendcxx . . $ embedding_context#backend., model, layer, cur, N, C, H, W)) return false;
1345 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"layer ", layer, U": (", N, U", ", C, U", ", H, U", ", W, U")");
1346 }
1347 auto t3 = stdcxx . . $ std/::chronocxx . . $ std/chrono/::high_resolution_clockcxx . . $ std/chrono/_V2/high_resolution_clock#::nowcxx . . $ std/chrono/_V2/system_clock#now(3657dacbd9b4f607).();
1348
1349 // 5. TSTP pooling
1350 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> poolcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1351 tstp_poolingcxx . . $ tstp_pooling(3e301e20c4f77aa0).(cur.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), N, C, H, W, pool);
1352 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"pool: (", N, U", ", (int)pool.size() / N, U")");
1353
1354 // 6. seg_1 linear
1355 linear_forwardcxx . . $ linear_forward(abd8016ae042aaee).(pool.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), N, (int)pool.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).() / N,
1356 (float*)model.tensorscxx . . $ embedding_model#tensors.[cxx . . $ std/map#`operator[]`(da459db78e6e18a3)."resnet.seg_1.weight"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d).]->data,
1357 (float*)model.tensorscxx . . $ embedding_model#tensors.[cxx . . $ std/map#`operator[]`(da459db78e6e18a3)."resnet.seg_1.bias"cxx . . $ std/__cxx11/basic_string#basic_string(e36662616dba894d).]->data,
1358 hp.embed_dimcxx . . $ embedding_hparams#embed_dim., embedding_out);
1359
1360 auto t4 = stdcxx . . $ std/::chronocxx . . $ std/chrono/::high_resolution_clockcxx . . $ std/chrono/_V2/high_resolution_clock#::nowcxx . . $ std/chrono/_V2/system_clock#now(3657dacbd9b4f607).();
1361
1362 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"embedding: (", N, U", ", hp.embed_dim, U")");
1363
1364 if (Melder_debugcxx . . $ Melder_debug. == 2004) {
1365 auto us = [](auto a, auto b) {
1366 return stdcxx . . $ std/::chronocxx . . $ std/chrono/::duration_castcxx . . $ std/chrono/duration_cast(b7f67bf9c2f19806).<stdcxx . . $ std/::chronocxx . . $ std/chrono/::microsecondscxx . . $ std/chrono/microseconds#>(b -cxx . . $ operator-(8538f57502d6bea9). a).count();
1367 };
1368 g_emb_fbank_uscxx . . $ g_emb_fbank_us. +=cxx . . $ std/__atomic_base#`operator+=`(73de6b30e1938209). us(cxx . . $ embedding_forward(8dcc40b580703ae0).$anonymous_type_7#`operator()`(e5e5cabccbaf6ef5).t0, t1);
1369 g_emb_conv1bn1relu_uscxx . . $ g_emb_conv1bn1relu_us. +=cxx . . $ std/__atomic_base#`operator+=`(73de6b30e1938209). us(cxx . . $ embedding_forward(8dcc40b580703ae0).$anonymous_type_7#`operator()`(e5e5cabccbaf6ef5).t1, t2);
1370 g_emb_resnet_uscxx . . $ g_emb_resnet_us. +=cxx . . $ std/__atomic_base#`operator+=`(73de6b30e1938209). us(cxx . . $ embedding_forward(8dcc40b580703ae0).$anonymous_type_7#`operator()`(e5e5cabccbaf6ef5).t2, t3);
1371 g_emb_tail_uscxx . . $ g_emb_tail_us. +=cxx . . $ std/__atomic_base#`operator+=`(73de6b30e1938209). us(cxx . . $ embedding_forward(8dcc40b580703ae0).$anonymous_type_7#`operator()`(e5e5cabccbaf6ef5).t3, t4);
1372 ++cxx . . $ std/__atomic_base#operator++(6390f2d371ad8d1d).g_emb_callscxx . . $ g_emb_calls.;
1373 }
1374
1375 return true;
1376 }
1377 struct ggml_backend_cpu_contextcxx . . $ ggml_backend_cpu_context#;
1378 // ============================================================================
1379 // Embedding: Init / Free
1380 // ============================================================================
1381 static void embedding_initcxx . . $ embedding_init(3e08fb0b99fe760c).(embedding_contextcxx . . $ embedding_context# & ectx, diarize_model_loader * loader) {
1382 //TRACE
1383 try {
1384 embedding_load_modelcxx . . $ embedding_load_model(7c5c81a58be2be40).(loader, ectx.modelcxx . . $ embedding_context#model.);
1385 } catch (MelderErrorcxx . . $ MelderError#) {
1386 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (U"Could not load embedding model.");
1387 }
1388
1389 ectx.backendcxx . . $ embedding_context#backend. = ggml_backend_cpu_init();
1390
1391 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"Embedding model initialized (", ectx.model.n_loaded, U" tensors)");
1392 }
1393
1394 static void embedding_freecxx . . $ embedding_free(aadd496f7a76d907).(embedding_contextcxx . . $ embedding_context# & ectx) {
1395 if (ectx.backendcxx . . $ embedding_context#backend.)
1396 ggml_backend_free(ectx.backendcxx . . $ embedding_context#backend.);
1397 for (auto buf : ectx.modelcxx . . $ embedding_context#model..bufferscxx . . $ embedding_model#buffers.)
1398 ggml_backend_buffer_free(buf);
1399 for (auto ctx : ectx.modelcxx . . $ embedding_context#model..ctxscxx . . $ embedding_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_paramscxx . . $ diarization_params# {
1411 // Segmentation
1412 float seg_durationcxx . . $ diarization_params#seg_duration. = 10.0f; // chunk duration (seconds)
1413 float seg_step_ratiocxx . . $ diarization_params#seg_step_ratio. = 0.1f; // step = 10% of duration (90% overlap)
1414 int seg_num_framescxx . . $ diarization_params#seg_num_frames. = 589; // frames per chunk (segmentation-3.0)
1415 int seg_num_classescxx . . $ diarization_params#seg_num_classes. = 7; // powerset classes
1416 int seg_num_speakerscxx . . $ diarization_params#seg_num_speakers. = 3; // max local speakers per chunk
1417 int seg_max_set_sizecxx . . $ diarization_params#seg_max_set_size. = 2; // powerset max set size
1418
1419 // Embedding
1420 int emb_dimensioncxx . . $ diarization_params#emb_dimension. = 256; // WeSpeaker ResNet34 output dim
1421 int emb_sample_ratecxx . . $ diarization_params#emb_sample_rate. = 16000;
1422 bool emb_exclude_overlapcxx . . $ diarization_params#emb_exclude_overlap. = true;
1423
1424 // Clustering
1425 double cluster_thresholdcxx . . $ diarization_params#cluster_threshold. = 0.7f; // https://huggingface.co/pyannote/speaker-diarization-3.1/blob/main/config.yaml
1426 int cluster_min_sizecxx . . $ diarization_params#cluster_min_size. = 12;
1427 float min_active_ratiocxx . . $ diarization_params#min_active_ratio. = 0.2f; // for filter_embeddings
1428 int num_speakerscxx . . $ diarization_params#num_speakers. = 0; // unspecified
1429 int min_speakerscxx . . $ diarization_params#min_speakers. = 0; // unspecified
1430 int max_speakerscxx . . $ diarization_params#max_speakers. = 0; // unspecified
1431
1432 // Post-processing
1433 float min_duration_offcxx . . $ diarization_params#min_duration_off. = 0.0f;
1434
1435 // Derived
1436 int seg_step_samplescxx . . $ diarization_params#seg_step_samples(455f465bc33b4cdf).() const { return (int)(seg_durationcxx . . $ diarization_params#seg_duration. * seg_step_ratiocxx . . $ diarization_params#seg_step_ratio. * emb_sample_ratecxx . . $ diarization_params#emb_sample_rate.); }
1437 int seg_chunk_samplescxx . . $ diarization_params#seg_chunk_samples(455f465bc33b4cdf).() const { return (int)(seg_durationcxx . . $ diarization_params#seg_duration. * emb_sample_ratecxx . . $ diarization_params#emb_sample_rate.); }
1438 int seg_step_framescxx . . $ diarization_params#seg_step_frames(455f465bc33b4cdf).() const { return (int)(seg_num_framescxx . . $ diarization_params#seg_num_frames. * seg_step_ratiocxx . . $ diarization_params#seg_step_ratio.); }
1439 };
1440
1441 // ============================================================================
1442 // Output structures
1443 // ============================================================================
1444 struct diarization_segmentcxx . . $ diarization_segment# {
1445 float startcxx . . $ diarization_segment#start.; // seconds
1446 float endcxx . . $ diarization_segment#end.; // seconds
1447 int speakercxx . . $ diarization_segment#speaker.; // 0-indexed speaker ID
1448 };
1449
1450 struct diarization_resultcxx . . $ diarization_result# {
1451 stdcxx . . $ std/::vectorcxx . . $ std/vector#<diarization_segmentcxx . . $ diarization_segment#> segmentscxx . . $ diarization_result#segments.;
1452 int num_speakerscxx . . $ diarization_result#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_mappingcxx . . $ 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_multilabelcxx . . $ powerset_to_multilabel(22505042d4ba8e1a).(
1485 const float * logits, int num_frames, int num_powerset_classes, int num_speakers,
1486 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> & binary
1487 ) {
1488 binary.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).f * num_speakers + s] = (float)powerset_mappingcxx . . $ 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_multilabelcxx . . $ powerset_to_soft_multilabel(3e301e20c4f77aa0).(
1517 const float * logits, int num_chunks, int num_frames,
1518 int num_powerset_classes, int num_speakers,
1519 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> & soft
1520 ) {
1521 soft.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).((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.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).() + (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_mappingcxx . . $ 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_countcxx . . $ compute_speaker_count(1d1112d7fcd7aeef).(
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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> & count // [total_frames]
1552 ) {
1553 // Sum speakers per frame, then aggregate over overlapping chunks
1554 stdcxx . . $ std/::vectorcxx . . $ std/vector#<double> sumcxx . . $ std/vector#vector(229e4d6bd205de31).(total_frames, 0.0);
1555 stdcxx . . $ std/::vectorcxx . . $ std/vector#<double> cntcxx . . $ std/vector#vector(229e4d6bd205de31).(total_frames, 0.0);
1556
1557 for (int c = 0; c < num_chunks; c++) {
1558 int start = c * chunk_step_frames;
1559 int end = stdcxx . . $ std/::mincxx . . $ std/min(2a338fce5842aa6a).(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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).start + f] += spk_count;
1566 cnt[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).start + f] += 1.0;
1567 }
1568 }
1569
1570 count.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(total_frames);
1571 for (int f = 0; f < total_frames; f++) {
1572 count[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).f] = (cnt[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).f] > 0) ? (int32_t)stdcxx . . $ std/::round(sum[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).f] / cnt[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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_resultcxx . . $ filter_result# {
1584 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> filtered_embeddingscxx . . $ filter_result#filtered_embeddings.; // [num_filtered * dim]
1585 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> chunk_idxcxx . . $ filter_result#chunk_idx.;
1586 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> speaker_idxcxx . . $ filter_result#speaker_idx.;
1587 int num_filteredcxx . . $ filter_result#num_filtered.;
1588 };
1589
1590 static filter_resultcxx . . $ filter_result# filter_embeddingscxx . . $ filter_embeddings(5a513ee84b9734c6).(
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_resultcxx . . $ filter_result# result;
1597 result.num_filteredcxx . . $ filter_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 (stdcxx . . $ 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_idxcxx . . $ filter_result#chunk_idx..push_backcxx . . $ std/vector#push_back(77d9f17553126ecb).(c);
1622 result.speaker_idxcxx . . $ filter_result#speaker_idx..push_backcxx . . $ std/vector#push_back(77d9f17553126ecb).(s);
1623 for (int d = 0; d < dim; d++) {
1624 result.filtered_embeddingscxx . . $ filter_result#filtered_embeddings..push_backcxx . . $ std/vector#push_back(77d9f17553126ecb).(emb[d]);
1625 }
1626 result.num_filteredcxx . . $ filter_result#num_filtered.++;
1627 }
1628 }
1629 return result;
1630 }
1631
1632 // ============================================================================
1633 // Agglomerative clustering (centroid linkage)
1634 // ============================================================================
1635 static void l2_normalize_f32_to_f64cxx . . $ l2_normalize_f32_to_f64(eb70dd3dbd221d1b).(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 = stdcxx . . $ 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_distcxx . . $ euclidean_dist(b9250f2b4e5d6625).(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 stdcxx . . $ std/::sqrt(s);
1650 }
1651
1652 static double cosine_distancecxx . . $ cosine_distance(b9250f2b4e5d6625).(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 = stdcxx . . $ std/::sqrt(na) * stdcxx . . $ std/::sqrt(nb);
1656 return (denom < 1e-30) ? 1.0 : 1.0 - dot / denom;
1657 }
1658
1659 struct linkage_mergecxx . . $ linkage_merge# { double idx1cxx . . $ linkage_merge#idx1., idx2cxx . . $ linkage_merge#idx2., distancecxx . . $ linkage_merge#distance., countcxx . . $ linkage_merge#count.; };
1660
1661 static void centroid_linkagecxx . . $ centroid_linkage(ceed2e579deade24).(const double * emb, int n, int dim,
1662 stdcxx . . $ std/::vectorcxx . . $ std/vector#<linkage_mergecxx . . $ linkage_merge#> & dendrogram) {
1663 dendrogram.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(n - 1);
1664 int max_cl = 2 * n - 1;
1665 stdcxx . . $ std/::vectorcxx . . $ std/vector#<double> centroidscxx . . $ std/vector#vector(83fdeebbe0501a83).(max_cl * dim);
1666 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int> countscxx . . $ std/vector#vector(229e4d6bd205de31).(max_cl, 0);
1667 stdcxx . . $ std/::vectorcxx . . $ std/vector#<bool> activecxx . . $ std/vector#vector(3413bcf9e068cf98).(max_cl, false);
1668
1669 for (int i = 0; i < n; i++) {
1670 for (int j = 0; j < dim; j++) centroids[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i * dim + j] = emb[i * dim + j];
1671 counts[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = 1; active[cxx . . $ std/vector#`operator[]`(1450282ea0befc17).i] =cxx . . $ std/_Bit_reference#`operator=`(2a6c206c8bbf32aa). 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[cxx . . $ std/vector#`operator[]`(1450282ea0befc17).i]) continue;
1678 for (int j = i + 1; j < n + step; j++) {
1679 if (!active[cxx . . $ std/vector#`operator[]`(1450282ea0befc17).j]) continue;
1680 double d = euclidean_distcxx . . $ euclidean_dist(b9250f2b4e5d6625).(centroids.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).()+i*dim, centroids.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).()+j*dim, dim);
1681 if (d < best_d) { best_d = d; bi = i; bj = j; }
1682 }
1683 }
1684 int ni = n + step;
1685 dendrogram[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).step] =cxx . . $ linkage_merge#`operator=`(84a3b707e6f0ceab). {(double)bi, (double)bj, best_d, (double)(counts[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).bi]+counts[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).bj])};
1686 int nc = counts[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).bi] + counts[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).bj];
1687 for (int j = 0; j < dim; j++)
1688 centroids[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).ni*dim+j] = (counts[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).bi]*centroids[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).bi*dim+j]+counts[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).bj]*centroids[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).bj*dim+j])/nc;
1689 counts[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).ni] = nc; active[cxx . . $ std/vector#`operator[]`(1450282ea0befc17).bi] =cxx . . $ std/_Bit_reference#`operator=`(2a6c206c8bbf32aa). false; active[cxx . . $ std/vector#`operator[]`(1450282ea0befc17).bj] =cxx . . $ std/_Bit_reference#`operator=`(2a6c206c8bbf32aa). false; active[cxx . . $ std/vector#`operator[]`(1450282ea0befc17).ni] =cxx . . $ std/_Bit_reference#`operator=`(2a6c206c8bbf32aa). true;
1690 }
1691 }
1692
1693 static void fcluster_distancecxx . . $ fcluster_distance(69a31c3472d8a20f).(const stdcxx . . $ std/::vectorcxx . . $ std/vector#<linkage_mergecxx . . $ linkage_merge#> & dend, int n, double threshold,
1694 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> & labels) {
1695 int mx = 2 * n - 1;
1696 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int> parentcxx . . $ std/vector#vector(83fdeebbe0501a83).(mx);
1697 for (int i = 0; i < mx; i++) parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = i;
1698 auto find = [&](int x) -> int {
1699 while (parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).x] != x) { parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).x] = parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).x]]; x = parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).x]; } return x;
1700 };
1701 for (int i = 0; i < n - 1; i++) {
1702 int a = (int)dend[cxx . . $ std/vector#`operator[]`(c8255e0fa326ac32).i].idx1cxx . . $ linkage_merge#idx1., b = (int)dend[cxx . . $ std/vector#`operator[]`(c8255e0fa326ac32).i].idx2cxx . . $ linkage_merge#idx2., ni = n + i;
1703 parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).ni] = ni;
1704 if (dend[cxx . . $ std/vector#`operator[]`(c8255e0fa326ac32).i].distancecxx . . $ linkage_merge#distance. <= threshold) { parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).find(cxx . . $ fcluster_distance(69a31c3472d8a20f).$anonymous_type_8#`operator()`(7ccb52b1bfe01045).a)] = ni; parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).find(cxx . . $ fcluster_distance(69a31c3472d8a20f).$anonymous_type_8#`operator()`(7ccb52b1bfe01045).b)] = ni; }
1705 }
1706 labels.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(n);
1707 for (int i = 0; i < n; i++) labels[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = find(cxx . . $ fcluster_distance(69a31c3472d8a20f).$anonymous_type_8#`operator()`(7ccb52b1bfe01045).i);
1708 // Renumber 0..K-1
1709 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int> uqcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1710 for (int i = 0; i < n; i++) {
1711 bool found = false;
1712 for (int u : uq) { if (u == labels[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i]) { found = true; break; } }
1713 if (!found) uq.push_backcxx . . $ std/vector#push_back(77d9f17553126ecb).(labels[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i]);
1714 }
1715 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int> mpcxx . . $ std/vector#vector(229e4d6bd205de31).(mx, -1);
1716 for (int k = 0; k < (int)uq.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).(); k++) mp[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).uq[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k]] = k;
1717 for (int i = 0; i < n; i++) labels[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = mp[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).labels[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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_byiterationcxx . . $ fcluster_byiteration(50135a5b234b3587).(const stdcxx . . $ std/::vectorcxx . . $ std/vector#<linkage_mergecxx . . $ linkage_merge#> & dend, int n,
1727 int cut_index,
1728 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> & labels) {
1729 int mx = 2 * n - 1;
1730 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int> parentcxx . . $ std/vector#vector(83fdeebbe0501a83).(mx);
1731 for (int i = 0; i < mx; i++) parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = i;
1732 auto find = [&](int x) -> int {
1733 while (parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).x] != x) { parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).x] = parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).x]]; x = parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).x]; } return x;
1734 };
1735 for (int i = 0; i < n - 1; i++) {
1736 int a = (int)dend[cxx . . $ std/vector#`operator[]`(c8255e0fa326ac32).i].idx1cxx . . $ linkage_merge#idx1., b = (int)dend[cxx . . $ std/vector#`operator[]`(c8255e0fa326ac32).i].idx2cxx . . $ linkage_merge#idx2., ni = n + i;
1737 parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).ni] = ni;
1738 if (i <= cut_index) { parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).find(cxx . . $ fcluster_byiteration(50135a5b234b3587).$anonymous_type_9#`operator()`(7ccb52b1bfe01045).a)] = ni; parent[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).find(cxx . . $ fcluster_byiteration(50135a5b234b3587).$anonymous_type_9#`operator()`(7ccb52b1bfe01045).b)] = ni; }
1739 }
1740 labels.resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(n);
1741 for (int i = 0; i < n; i++) labels[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = find(cxx . . $ fcluster_byiteration(50135a5b234b3587).$anonymous_type_9#`operator()`(7ccb52b1bfe01045).i);
1742 // Renumber 0..K-1 (same as fcluster_distance)
1743 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int> uqcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1744 for (int i = 0; i < n; i++) {
1745 bool found = false;
1746 for (int u : uq) { if (u == labels[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i]) { found = true; break; } }
1747 if (!found) uq.push_backcxx . . $ std/vector#push_back(77d9f17553126ecb).(labels[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i]);
1748 }
1749 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int> mpcxx . . $ std/vector#vector(229e4d6bd205de31).(mx, -1);
1750 for (int k = 0; k < (int)uq.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).(); k++) mp[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).uq[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k]] = k;
1751 for (int i = 0; i < n; i++) labels[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = mp[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).labels[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i]];
1752 }
1753
1754 // Helper: count "large" clusters (size >= min_cluster_size) given labels.
1755 static int count_large_clusterscxx . . $ count_large_clusters(501b7b51574f918e).(const stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> & labels, int min_cluster_size) {
1756 stdcxx . . $ std/::mapcxx . . $ std/map#<int32_t, int> countscxx . . $ std/map#map(49f6e7a06ebc5aa8).;
1757 for (auto l : labels) counts[cxx . . $ std/map#`operator[]`(bbd415b616967878).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_clusterscxx . . $ set_num_clusters(6b13987def099956).(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 = stdcxx . . $ std/::maxcxx . . $ std/max(2a338fce5842aa6a).(1, stdcxx . . $ std/::mincxx . . $ std/min(2a338fce5842aa6a).(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 = stdcxx . . $ std/::maxcxx . . $ std/max(2a338fce5842aa6a).(1, stdcxx . . $ std/::mincxx . . $ std/min(2a338fce5842aa6a).(num_embeddings, max_clusters));
1781
1782 if (min_clusters > max_clusters)
1783 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> agglomerative_clustercxx . . $ agglomerative_cluster(2303716dfd361469).(
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 = stdcxx . . $ std/::mincxx . . $ std/min(2a338fce5842aa6a).(min_cluster_size_param, stdcxx . . $ std/::maxcxx . . $ std/max(2a338fce5842aa6a).(1, (int)stdcxx . . $ std/::round(0.1 * n)));
1798
1799 if (n == 1) return {cxx . . $ std/vector#vector(9619226211e5a241).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_clusterscxx . . $ set_num_clusters(6b13987def099956).(n, num_clusters, min_clusters, max_clusters);
1806
1807 // L2-normalize
1808 stdcxx . . $ std/::vectorcxx . . $ std/vector#<double> embcxx . . $ std/vector#vector(83fdeebbe0501a83).(n * dim);
1809 for (int i = 0; i < n; i++)
1810 l2_normalize_f32_to_f64cxx . . $ l2_normalize_f32_to_f64(eb70dd3dbd221d1b).(embeddings_raw + i * dim, emb.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).() + i * dim, dim);
1811
1812 // Centroid linkage
1813 stdcxx . . $ std/::vectorcxx . . $ std/vector#<linkage_mergecxx . . $ linkage_merge#> dendcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1814 centroid_linkagecxx . . $ centroid_linkage(ceed2e579deade24).(emb.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), n, dim, dend);
1815
1816 // Initial cut at threshold (clustering.py:385)
1817 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> clusterscxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1818 fcluster_distancecxx . . $ fcluster_distance(69a31c3472d8a20f).(dend, n, threshold, clusters);
1819
1820 // Count large clusters (clustering.py:387-394)
1821 int n_large = count_large_clusterscxx . . $ count_large_clusters(501b7b51574f918e).(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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int> ordercxx . . $ std/vector#vector(83fdeebbe0501a83). (n - 1);
1834 for (int i = 0; i < n - 1; i++) order[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = i;
1835 stdcxx . . $ std/::sortcxx . . $ std/sort(4d3091562df4e52e). (order.begincxx . . $ std/vector#begin(55a6de06420d4903).(), order.endcxx . . $ std/vector#end(55a6de06420d4903).(), [&](int a, int b) {
1836 return stdcxx . . $ std/::abs(dend[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).a].distancecxx . . $ linkage_merge#distance. - threshold)
1837 < stdcxx . . $ std/::abs(dend[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).b].distancecxx . . $ linkage_merge#distance. - threshold);
1838 });
1839
1840 int best_iteration = n - 2; // default: cut after all merges (1 cluster)
1841 int best_n_large = 1;
1842 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> best_clusters = stdcxx . . $ std/vector#vector(229e4d6bd205de31).::vectorcxx . . $ 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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).it].countcxx . . $ linkage_merge#count.;
1848 if (new_size < mcs) continue;
1849
1850 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> trialcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1851 fcluster_byiterationcxx . . $ fcluster_byiteration(50135a5b234b3587).(dend, n, it, trial);
1852 int n_l = count_large_clusterscxx . . $ count_large_clusters(501b7b51574f918e).(trial, mcs);
1853
1854 if (stdcxx . . $ std/::abs(n_l - num_clusters) < stdcxx . . $ std/::abs(best_n_large - num_clusters)) {
1855 best_iteration = it;
1856 best_n_large = n_l;
1857 best_clusters =cxx . . $ std/vector#`operator=`(1104576815caab1a). stdcxx . . $ std/::move(trial);
1858 }
1859 if (n_l == num_clusters) break; // perfect candidate
1860 }
1861
1862 clusters =cxx . . $ std/vector#`operator=`(1104576815caab1a). stdcxx . . $ 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_warningcxx . . $ Melder_warning(6298c93241566110). (U"Diarization: detected only ", n_large, U" speakers (requested ", num_clusters, U").");
1868 }
1869
1870 // Large/small split
1871 stdcxx . . $ std/::mapcxx . . $ std/map#<int32_t, int> cccxx . . $ std/map#map(49f6e7a06ebc5aa8).;
1872 for (int i = 0; i < n; i++) cc[cxx . . $ std/map#`operator[]`(bbd415b616967878).clusters[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i]]++;
1873 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> largecxx . . $ std/vector#vector(49f6e7a06ebc5aa8)., smallcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1874 for (auto & [l, c] : cc) { if (c >= mcs) large.push_backcxx . . $ std/vector#push_back(77d9f17553126ecb).(l); else small.push_backcxx . . $ std/vector#push_back(77d9f17553126ecb).(l); }
1875
1876 if (large.emptycxx . . $ std/vector#empty(3482b152b9333168).()) {
1877 return stdcxx . . $ std/vector#vector(229e4d6bd205de31).::vectorcxx . . $ std/vector#<int32_t>(n, 0);
1878 }
1879
1880 if (!small.emptycxx . . $ std/vector#empty(3482b152b9333168).()) {
1881 // Reassign small -> nearest large (cosine distance between centroids)
1882 int nl = (int)large.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).(), ns = (int)small.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).();
1883 stdcxx . . $ std/::vectorcxx . . $ std/vector#<double> lccxx . . $ std/vector#vector(229e4d6bd205de31).(nl * dim, 0.0), sccxx . . $ std/vector#vector(229e4d6bd205de31).(ns * dim, 0.0);
1884 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int> lcntcxx . . $ std/vector#vector(229e4d6bd205de31).(nl, 0), scntcxx . . $ std/vector#vector(229e4d6bd205de31).(ns, 0);
1885 for (int i = 0; i < n; i++) {
1886 for (int k = 0; k < nl; k++) if (clusters[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] == large[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k]) {
1887 for (int j = 0; j < dim; j++) lc[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k*dim+j] += emb[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i*dim+j];
1888 lcnt[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k]++; break;
1889 }
1890 for (int k = 0; k < ns; k++) if (clusters[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] == small[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k]) {
1891 for (int j = 0; j < dim; j++) sc[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k*dim+j] += emb[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i*dim+j];
1892 scnt[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k]++; break;
1893 }
1894 }
1895 for (int k = 0; k < nl; k++) for (int j = 0; j < dim; j++) lc[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k*dim+j] /= lcnt[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k];
1896 for (int k = 0; k < ns; k++) for (int j = 0; j < dim; j++) sc[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k*dim+j] /= scnt[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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_distancecxx . . $ cosine_distance(b9250f2b4e5d6625).(lc.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).()+lk*dim, sc.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).()+sk*dim, dim);
1902 if (d < bd) { bd = d; blk = lk; }
1903 }
1904 int ol = small[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).sk], nl_ = large[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).blk];
1905 for (int i = 0; i < n; i++) if (clusters[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] == ol) clusters[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = nl_;
1906 }
1907 }
1908
1909 // Renumber
1910 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> uscxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
1911 { auto t = clusterscxx . . $ std/vector#vector(a1201200cf0efa42).; stdcxx . . $ std/::sortcxx . . $ std/sort(249673c20e2b8d5).(t.begincxx . . $ std/vector#begin(55a6de06420d4903).(),t.endcxx . . $ std/vector#end(55a6de06420d4903).()); t.erasecxx . . $ std/vector#erase(cc2a997b00bceed8).(stdcxx . . $ std/::uniquecxx . . $ std/unique(f80f7d6260b3ee3a).(t.begincxx . . $ std/vector#begin(55a6de06420d4903).(),t.endcxx . . $ std/vector#end(55a6de06420d4903).()),t.endcxx . . $ std/vector#end(55a6de06420d4903).()); us =cxx . . $ std/vector#`operator=`(e6b68e61becad66f). t; }
1912 stdcxx . . $ std/::mapcxx . . $ std/map#<int32_t,int32_t> rmcxx . . $ std/map#map(49f6e7a06ebc5aa8).;
1913 for (int k = 0; k < (int)us.sizecxx . . $ std/vector#size(c9b1e749b64d5edc).(); k++) rm[cxx . . $ std/map#`operator[]`(bbd415b616967878).us[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k]] = k;
1914 for (int i = 0; i < n; i++) clusters[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = rm[cxx . . $ std/map#`operator[]`(bbd415b616967878).clusters[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i]];
1915 return clusterscxx . . $ std/vector#vector(6f559d22b039ccdb).;
1916 }
1917
1918 // ============================================================================
1919 // Assign embeddings — compute centroids, then assign ALL embeddings
1920 // ============================================================================
1921 struct assign_resultcxx . . $ assign_result# {
1922 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> hard_clusterscxx . . $ assign_result#hard_clusters.; // [num_chunks * num_speakers]
1923 stdcxx . . $ std/::vectorcxx . . $ std/vector#<double> centroidscxx . . $ assign_result#centroids.; // [num_clusters * dim]
1924 int num_clusterscxx . . $ assign_result#num_clusters.;
1925 };
1926
1927 static assign_resultcxx . . $ assign_result# assign_embeddingscxx . . $ assign_embeddings(24059d11c4fcb855).(
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 = stdcxx . . $ std/::maxcxx . . $ std/max(2a338fce5842aa6a).(num_clusters, train_clusters[i] + 1);
1936
1937 assign_resultcxx . . $ assign_result# r;
1938 r.num_clusterscxx . . $ assign_result#num_clusters. = num_clusters;
1939 r.centroidscxx . . $ assign_result#centroids..resizecxx . . $ std/vector#resize(3804226c8c0acbc3).(num_clusters * dim, 0.0);
1940 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int> cccxx . . $ std/vector#vector(229e4d6bd205de31).(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.centroidscxx . . $ assign_result#centroids.[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k*dim+d] += (double)e[d];
1946 cc[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k]++;
1947 }
1948 for (int k = 0; k < num_clusters; k++)
1949 if (cc[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k] > 0) for (int d = 0; d < dim; d++) r.centroidscxx . . $ assign_result#centroids.[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k*dim+d] /= cc[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).k];
1950
1951 int total = num_chunks * num_speakers;
1952 r.hard_clusterscxx . . $ assign_result#hard_clusters..resizecxx . . $ std/vector#resize(2c44cd906ae4e829).(total);
1953 for (int cs = 0; cs < total; cs++) {
1954 const float * e = embeddings + cs * dim;
1955 stdcxx . . $ std/::vectorcxx . . $ std/vector#<double> efcxx . . $ std/vector#vector(83fdeebbe0501a83).(dim);
1956 for (int d = 0; d < dim; d++) ef[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).d] = (double)e[d];
1957 int bk = 0; double bs = -1e30;
1958 for (int k = 0; k < num_clusters; k++) {
1959 double dist = cosine_distancecxx . . $ cosine_distance(b9250f2b4e5d6625).(ef.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), r.centroidscxx . . $ assign_result#centroids..datacxx . . $ std/vector#data(258ee1c9e0a18a5c).()+k*dim, dim);
1960 double score = 2.0 - dist;
1961 if (score > bs) { bs = score; bk = k; }
1962 }
1963 r.hard_clusterscxx . . $ assign_result#hard_clusters.[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).cs] = bk;
1964 }
1965 return r;
1966 }
1967
1968 // ============================================================================
1969 // Reconstruct — remap local speakers -> global clusters
1970 // ============================================================================
1971 struct reconstruct_resultcxx . . $ reconstruct_result# {
1972 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> clusteredcxx . . $ reconstruct_result#clustered.; // [num_chunks * num_frames * num_global]
1973 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int8_t> nan_maskcxx . . $ reconstruct_result#nan_mask.; // 1=NaN, 0=valid
1974 int num_global_speakerscxx . . $ reconstruct_result#num_global_speakers.;
1975 };
1976
1977 static reconstruct_resultcxx . . $ reconstruct_result# reconstructcxx . . $ reconstruct(b43826f8f304a2ac).(
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 = stdcxx . . $ std/::maxcxx . . $ std/max(2a338fce5842aa6a).(ng, hard_clusters[i] + 1);
1985
1986 reconstruct_resultcxx . . $ reconstruct_result# r;
1987 r.num_global_speakerscxx . . $ reconstruct_result#num_global_speakers. = ng;
1988 size_t total = (size_t)num_chunks * num_frames * ng;
1989 r.clusteredcxx . . $ reconstruct_result#clustered..resizecxx . . $ std/vector#resize(3804226c8c0acbc3).(total, -1.0f);
1990 r.nan_maskcxx . . $ reconstruct_result#nan_mask..resizecxx . . $ std/vector#resize(3804226c8c0acbc3).(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.clusteredcxx . . $ reconstruct_result#clustered.[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).idx] = mx; r.nan_maskcxx . . $ reconstruct_result#nan_mask.[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> aggregate_overlappingcxx . . $ aggregate_overlapping(487b5b0e07d87e4b).(
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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<double> activation_sumcxx . . $ std/vector#vector(229e4d6bd205de31).(n_total_frames * n_global_speakers, 0.0);
2029 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int> contributor_countcxx . . $ std/vector#vector(229e4d6bd205de31).(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 = stdcxx . . $ std/::mincxx . . $ std/min(2a338fce5842aa6a).(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 [cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).dst] += (double) frame_activations[src];
2046 contributor_count[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> averaged_activationscxx . . $ std/vector#vector(83fdeebbe0501a83).(n_total_frames * n_global_speakers);
2055 for (int i = 0; i < n_total_frames * n_global_speakers; i++) {
2056 averaged_activations[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] = (contributor_count[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] > 0)
2057 ? (float) (activation_sum[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i] / contributor_count[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i])
2058 : 0.0f;
2059 }
2060 return averaged_activationscxx . . $ std/vector#vector(6f559d22b039ccdb).;
2061 }
2062
2063 // ============================================================================
2064 // to_diarization — top-N speaker selection per frame
2065 // ============================================================================
2066 static stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> to_diarizationcxx . . $ to_diarization(c02718ec0c3aaa5c).(
2067 const float * act, const int32_t * count, int total_frames, int ns
2068 ) {
2069 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> bincxx . . $ std/vector#vector(229e4d6bd205de31).(total_frames * ns, 0.0f);
2070 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int> idxcxx . . $ std/vector#vector(83fdeebbe0501a83).(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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).s] = s;
2074 stdcxx . . $ std/::sortcxx . . $ std/sort(4d3091562df4e52e).(idx.begincxx . . $ std/vector#begin(55a6de06420d4903).(), idx.endcxx . . $ std/vector#end(55a6de06420d4903).(), [&](int a, int b) {
2075 return act[t*ns+a] > act[t*ns+b];
2076 });
2077 for (int i = 0; i < stdcxx . . $ std/::mincxx . . $ std/min(2a338fce5842aa6a).(c, ns); i++) bin[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).t*ns+idx[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i]] = 1.0f;
2078 }
2079 return bincxx . . $ std/vector#vector(6f559d22b039ccdb).;
2080 }
2081
2082 // ============================================================================
2083 // to_annotation — binary frames -> time-stamped segments
2084 // ============================================================================
2085 static stdcxx . . $ std/::vectorcxx . . $ std/vector#<diarization_segmentcxx . . $ diarization_segment#> to_annotationcxx . . $ to_annotation(c309b257c691724e).(
2086 const float * binary, int total_frames, int ns, float frame_step
2087 ) {
2088 stdcxx . . $ std/::vectorcxx . . $ std/vector#<diarization_segmentcxx . . $ diarization_segment#> segscxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
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_backcxx . . $ std/vector#push_back(fe7a8a4d1eddb70).({sf * frame_step, t * frame_step, s});
2096 in_seg = false;
2097 }
2098 }
2099 if (in_seg) segs.push_backcxx . . $ std/vector#push_back(fe7a8a4d1eddb70).({sf * frame_step, total_frames * frame_step, s});
2100 }
2101 stdcxx . . $ std/::sortcxx . . $ std/sort(4d3091562df4e52e).(segs.begincxx . . $ std/vector#begin(55a6de06420d4903).(), segs.endcxx . . $ std/vector#end(55a6de06420d4903).(), [](auto & a, auto & b) {
2102 if (stdcxx . . $ std/::abscxx . . $ std/abs(bb57395c51337e15).(a.start-cxx . . $ operator-(8538f57502d6bea9).b.start) > 1e-6f) return a.start < b.start;
2103 return a.speaker < b.speaker;
2104 });
2105 return segscxx . . $ std/vector#vector(6f559d22b039ccdb).;
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_resultcxx . . $ diarization_result# run_diarization_pipelinecxx . . $ run_diarization_pipeline(77248a60b43f039d).(
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_paramscxx . . $ diarization_params# & params,
2128 int max_simultaneous_speakers // per-frame cap
2129 ) {
2130 //TRACE
2131 int step_frames = params.seg_step_framescxx . . $ diarization_params#seg_step_frames(455f465bc33b4cdf).();
2132 int total_frames = (num_chunks - 1) * step_frames + num_frames;
2133 float frame_step = params.seg_durationcxx . . $ diarization_params#seg_duration. / num_frames;
2134
2135 tracecxx . . $ `melder/melder_debug.h:60:10`! (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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> soft_segmentationscxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
2144 powerset_to_soft_multilabelcxx . . $ powerset_to_soft_multilabel(3e301e20c4f77aa0).(powerset_logits, num_chunks, num_frames,
2145 num_powerset_classes, num_speakers,
2146 soft_segmentations);
2147
2148 // --- Speaker count ---
2149 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> spk_countcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
2150 compute_speaker_countcxx . . $ compute_speaker_count(1d1112d7fcd7aeef).(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 = stdcxx . . $ std/::mincxx . . $ std/min(2a338fce5842aa6a).(c, (int32_t)max_simultaneous_speakers);
2155
2156 // Check if any speaker is ever active
2157 int max_count = *stdcxx . . $ std/::max_elementcxx . . $ std/max_element(f80f7d6260b3ee3a).(spk_count.begincxx . . $ std/vector#begin(55a6de06420d4903).(), spk_count.endcxx . . $ std/vector#end(55a6de06420d4903).());
2158 if (max_count == 0) {
2159 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"diarize: no speakers detected");
2160 return {{}, 0};
2161 }
2162
2163 // --- Filter embeddings ---
2164 auto filt = filter_embeddingscxx . . $ filter_embeddings(5a513ee84b9734c6).(embeddings, binarized_segmentations,
2165 num_chunks, num_frames, num_speakers, emb_dim,
2166 params.min_active_ratiocxx . . $ diarization_params#min_active_ratio.);
2167 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"diarize: ", filt.num_filtered, U"/", num_chunks * num_speakers, U" embeddings pass filter");
2168
2169 if (filt.num_filteredcxx . . $ filter_result#num_filtered. < 2) {
2170 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"diarize: too few embeddings, single speaker");
2171 // Single speaker fallback — all frames assigned to speaker 0
2172 diarization_resultcxx . . $ diarization_result# result;
2173 result.num_speakerscxx . . $ diarization_result#num_speakers. = 1;
2174 result.segmentscxx . . $ diarization_result#segments..push_backcxx . . $ std/vector#push_back(fe7a8a4d1eddb70).({0.0f, total_frames * frame_step, 0});
2175 return result;
2176 }
2177
2178 // --- Cluster ---
2179 auto train_clusters = agglomerative_clustercxx . . $ agglomerative_cluster(2303716dfd361469).(
2180 filt.filtered_embeddingscxx . . $ filter_result#filtered_embeddings..datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), filt.num_filteredcxx . . $ filter_result#num_filtered., emb_dim,
2181 params.cluster_thresholdcxx . . $ diarization_params#cluster_threshold., params.cluster_min_sizecxx . . $ diarization_params#cluster_min_size.,
2182 params.num_speakerscxx . . $ diarization_params#num_speakers., params.min_speakerscxx . . $ diarization_params#min_speakers., params.max_speakerscxx . . $ diarization_params#max_speakers.);
2183
2184 int num_clusters = *stdcxx . . $ std/::max_elementcxx . . $ std/max_element(f80f7d6260b3ee3a).(train_clusters.begincxx . . $ std/vector#begin(55a6de06420d4903).(), train_clusters.endcxx . . $ std/vector#end(55a6de06420d4903).()) + 1;
2185 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"diarize: ", num_clusters, U" clusters");
2186
2187 // --- Assign all embeddings ---
2188 auto asgn = assign_embeddingscxx . . $ assign_embeddings(24059d11c4fcb855).(embeddings, num_chunks, num_speakers, emb_dim,
2189 filt.chunk_idxcxx . . $ filter_result#chunk_idx..datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), filt.speaker_idxcxx . . $ filter_result#speaker_idx..datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(),
2190 train_clusters.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), filt.num_filteredcxx . . $ filter_result#num_filtered.);
2191
2192 // --- Mark inactive speakers as -2 ---
2193 stdcxx . . $ std/::vectorcxx . . $ std/vector#<int32_t> hard = asgncxx . . $ std/vector#vector(a1201200cf0efa42)..hard_clusterscxx . . $ assign_result#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[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).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 = reconstructcxx . . $ reconstruct(b43826f8f304a2ac).(soft_segmentations.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), hard.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(),
2212 num_chunks, num_frames, num_speakers);
2213 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"diarize: ", recon.num_global_speakers, U" global speakers in reconstruction");
2214
2215 // --- Aggregate ---
2216 auto aggregated = aggregate_overlappingcxx . . $ aggregate_overlapping(487b5b0e07d87e4b).(recon.clusteredcxx . . $ reconstruct_result#clustered..datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), recon.nan_maskcxx . . $ reconstruct_result#nan_mask..datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(),
2217 num_chunks, num_frames, recon.num_global_speakerscxx . . $ reconstruct_result#num_global_speakers.,
2218 step_frames, total_frames);
2219
2220 // --- to_diarization ---
2221 auto binary = to_diarizationcxx . . $ to_diarization(c02718ec0c3aaa5c).(aggregated.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), spk_count.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(),
2222 total_frames, recon.num_global_speakerscxx . . $ reconstruct_result#num_global_speakers.);
2223
2224 // --- to_annotation ---
2225 auto segs = to_annotationcxx . . $ to_annotation(c309b257c691724e).(binary.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), total_frames,
2226 recon.num_global_speakerscxx . . $ reconstruct_result#num_global_speakers., frame_step);
2227
2228 diarization_resultcxx . . $ diarization_result# result;
2229 result.segmentscxx . . $ diarization_result#segments. =cxx . . $ std/vector#`operator=`(e6b68e61becad66f). segs;
2230 result.num_speakerscxx . . $ diarization_result#num_speakers. = recon.num_global_speakerscxx . . $ reconstruct_result#num_global_speakers.;
2231
2232 tracecxx . . $ `melder/melder_debug.h:60:10`! (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_contextcxx . . $ diarize_context# {
2245 segmentation_contextcxx . . $ segmentation_context# seg_ctxcxx . . $ diarize_context#seg_ctx.;
2246 embedding_contextcxx . . $ embedding_context# emb_ctxcxx . . $ diarize_context#emb_ctx.;
2247 bool models_loadedcxx . . $ diarize_context#models_loaded.;
2248
2249 // Last result
2250 diarization_resultcxx . . $ diarization_result# resultcxx . . $ diarize_context#result.;
2251
2252 // Threadpool
2253 ggml_threadpool_t threadpoolcxx . . $ diarize_context#threadpool. = nullptr;
2254 int current_n_threadscxx . . $ diarize_context#current_n_threads. = 0;
2255 };
2256
2257 // ============================================================================
2258 // Memory stream helper (for init_from_memory)
2259 // ============================================================================
2260 struct diarize_mem_streamcxx . . $ diarize_mem_stream# {
2261 const uint8_tcxx . . $ uint8_t# * datacxx . . $ diarize_mem_stream#data.;
2262 size_t sizecxx . . $ diarize_mem_stream#size.;
2263 size_t poscxx . . $ diarize_mem_stream#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) stdcxx . . $ std/::threadcxx . . $ std/thread#::hardware_concurrencycxx . . $ std/thread#hardware_concurrency(2658d6455debfaef).() / 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_MAXcxx . . $ `melder/melder_int.h:41:10`!;
2283 return p;
2284 }
2285
2286 static void ensure_n_threads (diarize_contextcxx . . $ diarize_context# *ctx, int n_threads) {
2287 if (ctx->threadpoolcxx . . $ diarize_context#threadpool. && ctx->current_n_threadscxx . . $ diarize_context#current_n_threads. == n_threads) // already configured correctly
2288 return;
2289
2290 if (ctx->threadpoolcxx . . $ diarize_context#threadpool.) {
2291 ggml_threadpool_free (ctx->threadpoolcxx . . $ diarize_context#threadpool.);
2292 ctx->threadpoolcxx . . $ diarize_context#threadpool. = nullptr;
2293 }
2294
2295 ggml_threadpool_params tp_params = ggml_threadpool_params_default (n_threads);
2296 ctx->threadpoolcxx . . $ diarize_context#threadpool. = ggml_threadpool_new (& tp_params);
2297 ggml_backend_cpu_set_threadpool (ctx->seg_ctxcxx . . $ diarize_context#seg_ctx..backendcxx . . $ segmentation_context#backend., ctx->threadpoolcxx . . $ diarize_context#threadpool.);
2298 ggml_backend_cpu_set_threadpool (ctx->emb_ctxcxx . . $ diarize_context#emb_ctx..backendcxx . . $ embedding_context#backend., ctx->threadpoolcxx . . $ diarize_context#threadpool.);
2299 ggml_backend_cpu_set_n_threads (ctx->seg_ctxcxx . . $ diarize_context#seg_ctx..backendcxx . . $ segmentation_context#backend., n_threads);
2300 ggml_backend_cpu_set_n_threads (ctx->emb_ctxcxx . . $ diarize_context#emb_ctx..backendcxx . . $ embedding_context#backend., n_threads);
2301 ctx->current_n_threadscxx . . $ diarize_context#current_n_threads. = n_threads;
2302
2303 if (Melder_debugcxx . . $ Melder_debug. == 2004)
2304 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (U"Diarization: using ", n_threads, U" GGML CPU threads");
2305 }
2306
2307 struct diarize_contextcxx . . $ diarize_context# * diarize_init(struct diarize_model_loader * seg_loader, struct diarize_model_loader * emb_loader) {
2308 //TRACE
2309 auto * ctx = new diarize_contextcxx . . $ diarize_context#();
2310 ctx->models_loadedcxx . . $ diarize_context#models_loaded. = false;
2311
2312 try {
2313 segmentation_initcxx . . $ segmentation_init(1797d58214d88945).(ctx->seg_ctxcxx . . $ diarize_context#seg_ctx., seg_loader);
2314 } catch (MelderErrorcxx . . $ MelderError#) {
2315 delete ctx;
2316 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (U"Failed to initialize diarization: segmentation model could not be loaded.");
2317 }
2318
2319 try {
2320 embedding_initcxx . . $ embedding_init(3e08fb0b99fe760c).(ctx->emb_ctxcxx . . $ diarize_context#emb_ctx., emb_loader);
2321 } catch (MelderErrorcxx . . $ MelderError#) {
2322 segmentation_freecxx . . $ segmentation_free(26075c468d49fb47).(ctx->seg_ctxcxx . . $ diarize_context#seg_ctx.);
2323 delete ctx;
2324 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (U"Failed to initialize diarization: embedding model could not be loaded.");
2325 }
2326
2327 ctx->models_loadedcxx . . $ diarize_context#models_loaded. = true;
2328 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"diarize_init: models loaded");
2329 return ctx;
2330 }
2331
2332 static diarize_model_loader create_file_loader(stdcxx . . $ std/::ifstreamcxx . . $ 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 = (stdcxx . . $ std/::ifstreamcxx . . $ std/ifstream# *)ctx;
2338 f->readcxx . . $ std/basic_istream#read(ec7d6f01d31dcb96).((char *)output, read_size);
2339 return read_size;
2340 };
2341
2342 loader.eof = [](void * ctx) -> bool {
2343 auto * f = (stdcxx . . $ std/::ifstreamcxx . . $ std/ifstream# *)ctx;
2344 return f->eofcxx . . $ std/basic_ios#eof(50ce9a9e25b4a850).();
2345 };
2346
2347 loader.close = [](void * ctx) {
2348 auto * f = (stdcxx . . $ std/::ifstreamcxx . . $ std/ifstream# *)ctx;
2349 f->closecxx . . $ std/basic_ifstream#close(49f6e7a06ebc5aa8).();
2350 delete f;
2351 };
2352 return loader;
2353 }
2354
2355 struct diarize_contextcxx . . $ diarize_context# * diarize_init_from_file(const char * seg_model_path, const char * emb_model_path) {
2356 //TRACE
2357 auto * seg_fin = new stdcxx . . $ std/::ifstreamcxx . . $ std/ifstream#(seg_model_path, stdcxx . . $ std/::ioscxx . . $ std/ios#::binarycxx . . $ std/ios_base#binary.);
2358 if (!seg_fin->is_opencxx . . $ std/basic_ifstream#is_open(c9857a73d68e59ba).()) {
2359 delete seg_fin;
2360 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (U"Failed to open '", Melder_peek8to32_u (seg_model_path), U"'.");
2361 }
2362
2363 auto * emb_fin = new stdcxx . . $ std/::ifstreamcxx . . $ std/ifstream#(emb_model_path, stdcxx . . $ std/::ioscxx . . $ std/ios#::binarycxx . . $ std/ios_base#binary.);
2364 if (!emb_fin->is_opencxx . . $ std/basic_ifstream#is_open(c9857a73d68e59ba).()) {
2365 delete seg_fin;
2366 delete emb_fin;
2367 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (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 (MelderErrorcxx . . $ MelderError#) {
2379 seg_loader.close(seg_loader.context);
2380 emb_loader.close(emb_loader.context);
2381 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (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_streamcxx . . $ diarize_mem_stream#{(const uint8_tcxx . . $ 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_streamcxx . . $ diarize_mem_stream# *)ctx;
2392 size_t available = s->sizecxx . . $ diarize_mem_stream#size. - s->poscxx . . $ diarize_mem_stream#pos.;
2393 size_t to_read = (read_size < available) ? read_size : available;
2394 memcpy(output, s->datacxx . . $ diarize_mem_stream#data. + s->poscxx . . $ diarize_mem_stream#pos., to_read);
2395 s->poscxx . . $ diarize_mem_stream#pos. += to_read;
2396 return to_read;
2397 };
2398
2399 loader.eof = [](void * ctx) -> bool {
2400 auto * s = (diarize_mem_streamcxx . . $ diarize_mem_stream# *)ctx;
2401 return s->poscxx . . $ diarize_mem_stream#pos. >= s->sizecxx . . $ diarize_mem_stream#size.;
2402 };
2403
2404 loader.close = [](void * ctx) {
2405 delete (diarize_mem_streamcxx . . $ diarize_mem_stream# *)ctx;
2406 };
2407 return loader;
2408 }
2409
2410 struct diarize_contextcxx . . $ 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 (MelderErrorcxx . . $ MelderError#) {
2420 seg_loader.close(seg_loader.context);
2421 emb_loader.close(emb_loader.context);
2422 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (U"Failed to initialize diarization from memory.");
2423 }
2424 }
2425
2426 void diarize_free(struct diarize_contextcxx . . $ diarize_context# * ctx) {
2427 if (!ctx) return;
2428 if (ctx->threadpoolcxx . . $ diarize_context#threadpool.) {
2429 ggml_threadpool_free(ctx->threadpoolcxx . . $ diarize_context#threadpool.);
2430 ctx->threadpoolcxx . . $ diarize_context#threadpool. = nullptr;
2431 }
2432 if (ctx->models_loadedcxx . . $ diarize_context#models_loaded.) {
2433 segmentation_freecxx . . $ segmentation_free(26075c468d49fb47).(ctx->seg_ctxcxx . . $ diarize_context#seg_ctx.);
2434 embedding_freecxx . . $ embedding_free(aadd496f7a76d907).(ctx->emb_ctxcxx . . $ diarize_context#emb_ctx.);
2435 }
2436 delete ctx;
2437 }
2438
2439 void diarize_full(
2440 struct diarize_contextcxx . . $ diarize_context# * ctx,
2441 struct diarize_full_params params,
2442 const float * samples,
2443 int n_samples)
2444 {
2445 //TRACE
2446 if (Melder_debugcxx . . $ 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_uscxx . . $ g_seg_sincnet_us. =cxx . . $ std/__atomic_base#`operator=`(73de6b30e1938209). 0;
2452 g_seg_lstm_uscxx . . $ g_seg_lstm_us. =cxx . . $ std/__atomic_base#`operator=`(73de6b30e1938209). 0;
2453 g_seg_linear_uscxx . . $ g_seg_linear_us. =cxx . . $ std/__atomic_base#`operator=`(73de6b30e1938209). 0;
2454 g_seg_callscxx . . $ g_seg_calls. =cxx . . $ std/__atomic_base#`operator=`(73de6b30e1938209). 0;
2455 g_emb_fbank_uscxx . . $ g_emb_fbank_us. =cxx . . $ std/__atomic_base#`operator=`(73de6b30e1938209). 0;
2456 g_emb_conv1bn1relu_uscxx . . $ g_emb_conv1bn1relu_us. =cxx . . $ std/__atomic_base#`operator=`(73de6b30e1938209). 0;
2457 g_emb_resnet_uscxx . . $ g_emb_resnet_us. =cxx . . $ std/__atomic_base#`operator=`(73de6b30e1938209). 0;
2458 g_emb_tail_uscxx . . $ g_emb_tail_us. =cxx . . $ std/__atomic_base#`operator=`(73de6b30e1938209). 0;
2459 g_emb_callscxx . . $ g_emb_calls. =cxx . . $ std/__atomic_base#`operator=`(73de6b30e1938209). 0;
2460 }
2461
2462 if (!ctx || !ctx->models_loadedcxx . . $ diarize_context#models_loaded. || !samples || n_samples <= 0)
2463 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (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->resultcxx . . $ diarize_context#result. =cxx . . $ diarization_result#`operator=`(e01851d137b6c9db). {};
2470
2471 // --- Pipeline parameters ---
2472 diarization_paramscxx . . $ diarization_params# dp;
2473 dp.seg_durationcxx . . $ diarization_params#seg_duration. = params.seg_duration;
2474 dp.seg_step_ratiocxx . . $ diarization_params#seg_step_ratio. = params.seg_step_ratio;
2475 dp.cluster_thresholdcxx . . $ diarization_params#cluster_threshold. = (double)params.cluster_threshold;
2476 dp.cluster_min_sizecxx . . $ diarization_params#cluster_min_size. = params.cluster_min_size;
2477 dp.min_active_ratiocxx . . $ diarization_params#min_active_ratio. = params.min_active_ratio;
2478 dp.num_speakerscxx . . $ diarization_params#num_speakers. = params.num_speakers;
2479 dp.min_speakerscxx . . $ diarization_params#min_speakers. = params.min_speakers;
2480 dp.max_speakerscxx . . $ diarization_params#max_speakers. = params.max_speakers;
2481
2482 const int sample_rate = 16000;
2483 const int chunk_samples = (int)(dp.seg_durationcxx . . $ diarization_params#seg_duration. * sample_rate);
2484 const int step_samples = (int)(dp.seg_durationcxx . . $ diarization_params#seg_duration. * dp.seg_step_ratiocxx . . $ diarization_params#seg_step_ratio. * sample_rate);
2485
2486 float duration = (float)n_samples / sample_rate;
2487 tracecxx . . $ `melder/melder_debug.h:60:10`! (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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> all_segmentationscxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
2498
2499 for (int c = 0; c < num_chunks; c++) {
2500 int start = c * step_samples;
2501 int end = stdcxx . . $ std/::mincxx . . $ std/min(2a338fce5842aa6a).(start + chunk_samples, n_samples);
2502 int len = end - start;
2503
2504 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> chunkcxx . . $ std/vector#vector(229e4d6bd205de31).(chunk_samples, 0.0f);
2505 stdcxx . . $ std/::memcpy(chunk.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), samples + start, len * sizeof(float));
2506
2507 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> seg_outcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
2508 int nf, nc;
2509 if (!segmentation_forwardcxx . . $ segmentation_forward(135b33e7526ba24b).(ctx->seg_ctxcxx . . $ diarize_context#seg_ctx., chunk.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), chunk_samples, seg_out, nf, nc))
2510 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (U"Segmentation failed on chunk ", c, U".");
2511
2512 if (c == 0) {
2513 num_frames = nf;
2514 num_classes = nc;
2515 dp.seg_num_framescxx . . $ diarization_params#seg_num_frames. = nf;
2516 dp.seg_num_classescxx . . $ diarization_params#seg_num_classes. = nc;
2517 all_segmentations.reservecxx . . $ std/vector#reserve(2c44cd906ae4e829).(num_chunks * nf * nc);
2518 }
2519
2520 all_segmentations.insertcxx . . $ std/vector#insert(134ef7853f0b3ebe).(all_segmentations.endcxx . . $ std/vector#end(55a6de06420d4903).(), seg_out.begincxx . . $ std/vector#begin(55a6de06420d4903).(), seg_out.endcxx . . $ std/vector#end(55a6de06420d4903).());
2521 }
2522
2523 if (Melder_debugcxx . . $ Melder_debug. == 2004) {
2524 int n = g_seg_callscxx . . $ g_seg_calls..loadcxx . . $ std/__atomic_base#load(1776886d83107284).();
2525 int64_t s = g_seg_sincnet_uscxx . . $ g_seg_sincnet_us..loadcxx . . $ std/__atomic_base#load(1776886d83107284).();
2526 int64_t l = g_seg_lstm_uscxx . . $ g_seg_lstm_us..loadcxx . . $ std/__atomic_base#load(1776886d83107284).();
2527 int64_t f = g_seg_linear_uscxx . . $ g_seg_linear_us..loadcxx . . $ std/__atomic_base#load(1776886d83107284).();
2528 int64_t total = s + l + f;
2529 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (U"=== Segmentation timing over ", n, U" chunks ===");
2530 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (U" SincNet (GGML): ", s / 1000, U" ms (", (total ? 100*s/total : 0), U"%)");
2531 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (U" LSTM (plain C++): ", l / 1000, U" ms (", (total ? 100*l/total : 0), U"%)");
2532 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (U" Linear+Cls (plain C++):", f / 1000, U" ms (", (total ? 100*f/total : 0), U"%)");
2533 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (U" Total segmentation: ", total / 1000, U" ms");
2534 }
2535
2536 int num_speakers = dp.seg_num_speakerscxx . . $ diarization_params#seg_num_speakers.; // 3
2537
2538 tracecxx . . $ `melder/melder_debug.h:60:10`! (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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> all_binarizedcxx . . $ std/vector#vector(83fdeebbe0501a83).(num_chunks * num_frames * num_speakers);
2542
2543 for (int c = 0; c < num_chunks; c++) {
2544 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> chunk_binarycxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
2545 powerset_to_multilabelcxx . . $ powerset_to_multilabel(22505042d4ba8e1a).(
2546 all_segmentations.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).() + c * num_frames * num_classes,
2547 num_frames, num_classes, num_speakers, chunk_binary);
2548 stdcxx . . $ std/::memcpy(all_binarized.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).() + c * num_frames * num_speakers,
2549 chunk_binary.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), num_frames * num_speakers * sizeof(float));
2550 }
2551
2552 // --- Step 3: Embedding extraction ---
2553 int emb_dim = dp.emb_dimensioncxx . . $ diarization_params#emb_dimension.;
2554 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> all_embeddingscxx . . $ std/vector#vector(83fdeebbe0501a83).(num_chunks * num_speakers * emb_dim);
2555 stdcxx . . $ std/::fillcxx . . $ std/fill(4a9bfaed88eccda7).(all_embeddings.begincxx . . $ std/vector#begin(55a6de06420d4903).(), all_embeddings.endcxx . . $ std/vector#end(55a6de06420d4903).(), stdcxx . . $ std/::nanf(""));
2556
2557 for (int c = 0; c < num_chunks; c++) {
2558 int start_sample = c * step_samples;
2559 int end_sample = stdcxx . . $ std/::mincxx . . $ std/min(2a338fce5842aa6a).(start_sample + chunk_samples, n_samples);
2560 int len = end_sample - start_sample;
2561
2562 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> chunk_wavcxx . . $ std/vector#vector(229e4d6bd205de31).(chunk_samples, 0.0f);
2563 stdcxx . . $ std/::memcpy(chunk_wav.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), samples + start_sample, len * sizeof(float));
2564
2565 for (int s = 0; s < num_speakers; s++) {
2566 const float * mask = all_binarized.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).() +
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 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> masked_wavcxx . . $ std/vector#vector(83fdeebbe0501a83).(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 = stdcxx . . $ std/::mincxx . . $ std/min(2a338fce5842aa6a).(frame, num_frames - 1);
2582 float m = mask[frame * num_speakers];
2583 if (m > 0.5f) {
2584 masked_wav[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).active_samples++] = chunk_wav[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).t];
2585 }
2586 }
2587
2588 if (active_samples < 1000) continue;
2589
2590 stdcxx . . $ std/::vectorcxx . . $ std/vector#<float> emb_outcxx . . $ std/vector#vector(49f6e7a06ebc5aa8).;
2591 if (!embedding_forwardcxx . . $ embedding_forward(8dcc40b580703ae0).(ctx->emb_ctxcxx . . $ diarize_context#emb_ctx., masked_wav.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), active_samples, emb_out)) {
2592 continue;
2593 }
2594
2595 stdcxx . . $ std/::memcpy(all_embeddings.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).() + (c * num_speakers + s) * emb_dim,
2596 emb_out.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(), emb_dim * sizeof(float));
2597 }
2598
2599 if ((c + 1) % 10 == 0 || c == num_chunks - 1) {
2600 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"diarize_full: embeddings ", c + 1, U"/", num_chunks);
2601 }
2602 }
2603
2604 if (Melder_debugcxx . . $ Melder_debug. == 2004) {
2605 int n = g_emb_callscxx . . $ g_emb_calls.. loadcxx . . $ std/__atomic_base#load(1776886d83107284).();
2606 int64_t fb = g_emb_fbank_uscxx . . $ g_emb_fbank_us.. loadcxx . . $ std/__atomic_base#load(1776886d83107284).();
2607 int64_t cb = g_emb_conv1bn1relu_uscxx . . $ g_emb_conv1bn1relu_us.. loadcxx . . $ std/__atomic_base#load(1776886d83107284).();
2608 int64_t rn = g_emb_resnet_uscxx . . $ g_emb_resnet_us.. loadcxx . . $ std/__atomic_base#load(1776886d83107284).();
2609 int64_t tl = g_emb_tail_uscxx . . $ g_emb_tail_us.. loadcxx . . $ std/__atomic_base#load(1776886d83107284).();
2610 int64_t total = fb + cb + rn + tl;
2611 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (U"=== Embedding timing over ", n, U" calls ===");
2612 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (U" Fbank (plain C++): ", fb / 1000, U" ms (", (total ? 100*fb/total : 0), U"%)");
2613 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (U" Conv1+bn+Relu (plain C++): ", cb / 1000, U" ms (", (total ? 100*cb/total : 0), U"%)");
2614 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (U" ResNet (GGML+C++): ", rn / 1000, U" ms (", (total ? 100*rn/total : 0), U"%)");
2615 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (U" TSTP+Linear (C++): ", tl / 1000, U" ms (", (total ? 100*tl/total : 0), U"%)");
2616 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (U" Total embedding: ", total / 1000, U" ms");
2617 }
2618
2619 // --- Step 4: Clustering + reconstruction pipeline ---
2620 ctx->resultcxx . . $ diarize_context#result. =cxx . . $ diarization_result#`operator=`(e01851d137b6c9db). run_diarization_pipelinecxx . . $ run_diarization_pipeline(77248a60b43f039d).(
2621 all_segmentations.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(),
2622 all_binarized.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(),
2623 all_embeddings.datacxx . . $ std/vector#data(258ee1c9e0a18a5c).(),
2624 num_chunks, num_frames, num_classes, num_speakers, emb_dim,
2625 dp, params.max_simultaneous_speakers);
2626 tracecxx . . $ `melder/melder_debug.h:60:10`! (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_contextcxx . . $ diarize_context# * ctx) {
2630 if (!ctx) return 0;
2631 return ctx->resultcxx . . $ diarize_context#result..segmentscxx . . $ diarization_result#segments..sizecxx . . $ std/vector#size(c9b1e749b64d5edc).();
2632 }
2633
2634 int diarize_full_n_speakers(struct diarize_contextcxx . . $ diarize_context# * ctx) {
2635 if (!ctx) return 0;
2636 return ctx->resultcxx . . $ diarize_context#result..num_speakerscxx . . $ diarization_result#num_speakers.;
2637 }
2638
2639 float diarize_full_get_segment_t0(struct diarize_contextcxx . . $ diarize_context# * ctx, int i_segment) {
2640 if (!ctx || i_segment < 0 || i_segment >= (int)ctx->resultcxx . . $ diarize_context#result..segmentscxx . . $ diarization_result#segments..sizecxx . . $ std/vector#size(c9b1e749b64d5edc).()) return 0.0f;
2641 return ctx->resultcxx . . $ diarize_context#result..segmentscxx . . $ diarization_result#segments.[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i_segment].startcxx . . $ diarization_segment#start.;
2642 }
2643
2644 float diarize_full_get_segment_t1(struct diarize_contextcxx . . $ diarize_context# * ctx, int i_segment) {
2645 if (!ctx || i_segment < 0 || i_segment >= (int)ctx->resultcxx . . $ diarize_context#result..segmentscxx . . $ diarization_result#segments..sizecxx . . $ std/vector#size(c9b1e749b64d5edc).()) return 0.0f;
2646 return ctx->resultcxx . . $ diarize_context#result..segmentscxx . . $ diarization_result#segments.[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i_segment].endcxx . . $ diarization_segment#end.;
2647 }
2648
2649 int diarize_full_get_segment_speaker(struct diarize_contextcxx . . $ diarize_context# * ctx, int i_segment) {
2650 if (!ctx || i_segment < 0 || i_segment >= (int)ctx->resultcxx . . $ diarize_context#result..segmentscxx . . $ diarization_result#segments..sizecxx . . $ std/vector#size(c9b1e749b64d5edc).()) return -1;
2651 return ctx->resultcxx . . $ diarize_context#result..segmentscxx . . $ diarization_result#segments.[cxx . . $ std/vector#`operator[]`(81207c53da4b73ce).i_segment].speakercxx . . $ diarization_segment#speaker.;
2652 }
2653
2654 } // extern "C"