-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
ivector-extractor.cc
1820 lines (1600 loc) · 66.7 KB
/
ivector-extractor.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ivector/ivector-extractor.cc
// Copyright 2013 Daniel Povey
// 2015 David Snyder
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include <vector>
#include "ivector/ivector-extractor.h"
#include "util/kaldi-thread.h"
namespace kaldi {
int32 IvectorExtractor::FeatDim() const {
KALDI_ASSERT(!M_.empty());
return M_[0].NumRows();
}
int32 IvectorExtractor::IvectorDim() const {
if (M_.empty()) { return 0.0; }
else { return M_[0].NumCols(); }
}
int32 IvectorExtractor::NumGauss() const {
return static_cast<int32>(M_.size());
}
// This function basically inverts the input and puts it in the output, but it's
// smart numerically. It uses the prior knowledge that the "inverse_floor" can
// have no eigenvalues less than one, so it applies that floor (in double
// precision) before inverting. This avoids certain numerical problems that can
// otherwise occur.
// static
void IvectorExtractor::InvertWithFlooring(const SpMatrix<double> &inverse_var,
SpMatrix<double> *var) {
SpMatrix<double> dbl_var(inverse_var);
int32 dim = inverse_var.NumRows();
Vector<double> s(dim);
Matrix<double> P(dim, dim);
// Solve the symmetric eigenvalue problem, inverse_var = P diag(s) P^T.
inverse_var.Eig(&s, &P);
s.ApplyFloor(1.0);
s.InvertElements();
var->AddMat2Vec(1.0, P, kNoTrans, s, 0.0);
}
void IvectorExtractor::GetIvectorDistribution(
const IvectorExtractorUtteranceStats &utt_stats,
VectorBase<double> *mean,
SpMatrix<double> *var) const {
if (!IvectorDependentWeights()) {
Vector<double> linear(IvectorDim());
SpMatrix<double> quadratic(IvectorDim());
GetIvectorDistMean(utt_stats, &linear, &quadratic);
GetIvectorDistPrior(utt_stats, &linear, &quadratic);
if (var != NULL) {
var->CopyFromSp(quadratic);
var->Invert(); // now it's a variance.
// mean of distribution = quadratic^{-1} * linear...
mean->AddSpVec(1.0, *var, linear, 0.0);
} else {
quadratic.Invert();
mean->AddSpVec(1.0, quadratic, linear, 0.0);
}
} else {
Vector<double> linear(IvectorDim());
SpMatrix<double> quadratic(IvectorDim());
GetIvectorDistMean(utt_stats, &linear, &quadratic);
GetIvectorDistPrior(utt_stats, &linear, &quadratic);
// At this point, "linear" and "quadratic" contain
// the mean and prior-related terms, and we avoid
// recomputing those.
Vector<double> cur_mean(IvectorDim());
SpMatrix<double> quadratic_inv(IvectorDim());
InvertWithFlooring(quadratic, &quadratic_inv);
cur_mean.AddSpVec(1.0, quadratic_inv, linear, 0.0);
KALDI_VLOG(3) << "Trace of quadratic is " << quadratic.Trace()
<< ", condition is " << quadratic.Cond();
KALDI_VLOG(3) << "Trace of quadratic_inv is " << quadratic_inv.Trace()
<< ", condition is " << quadratic_inv.Cond();
// The loop is finding successively better approximation points
// for the quadratic expansion of the weights.
int32 num_iters = 4;
double change_threshold = 0.1; // If the iVector changes by less than
// this (in 2-norm), we abort early.
for (int32 iter = 0; iter < num_iters; iter++) {
if (GetVerboseLevel() >= 3) {
KALDI_VLOG(3) << "Auxf on iter " << iter << " is "
<< GetAuxf(utt_stats, cur_mean, &quadratic_inv);
int32 show_dim = 5;
if (show_dim > cur_mean.Dim()) show_dim = cur_mean.Dim();
KALDI_VLOG(3) << "Current distribution mean is "
<< cur_mean.Range(0, show_dim) << "... "
<< ", var trace is " << quadratic_inv.Trace();
}
Vector<double> this_linear(linear);
SpMatrix<double> this_quadratic(quadratic);
GetIvectorDistWeight(utt_stats, cur_mean,
&this_linear, &this_quadratic);
InvertWithFlooring(this_quadratic, &quadratic_inv);
Vector<double> mean_diff(cur_mean);
cur_mean.AddSpVec(1.0, quadratic_inv, this_linear, 0.0);
mean_diff.AddVec(-1.0, cur_mean);
double change = mean_diff.Norm(2.0);
KALDI_VLOG(2) << "On iter " << iter << ", iVector changed by " << change;
if (change < change_threshold)
break;
}
mean->CopyFromVec(cur_mean);
if (var != NULL)
var->CopyFromSp(quadratic_inv);
}
}
IvectorExtractor::IvectorExtractor(
const IvectorExtractorOptions &opts,
const FullGmm &fgmm) {
KALDI_ASSERT(opts.ivector_dim > 0);
Sigma_inv_.resize(fgmm.NumGauss());
for (int32 i = 0; i < fgmm.NumGauss(); i++) {
const SpMatrix<BaseFloat> &inv_var = fgmm.inv_covars()[i];
Sigma_inv_[i].Resize(inv_var.NumRows());
Sigma_inv_[i].CopyFromSp(inv_var);
}
Matrix<double> gmm_means;
fgmm.GetMeans(&gmm_means);
KALDI_ASSERT(!Sigma_inv_.empty());
int32 feature_dim = Sigma_inv_[0].NumRows(),
num_gauss = Sigma_inv_.size();
prior_offset_ = 100.0; // hardwired for now. Must be nonzero.
gmm_means.Scale(1.0 / prior_offset_);
M_.resize(num_gauss);
for (int32 i = 0; i < num_gauss; i++) {
M_[i].Resize(feature_dim, opts.ivector_dim);
M_[i].SetRandn();
M_[i].CopyColFromVec(gmm_means.Row(i), 0);
}
if (opts.use_weights) { // will regress the log-weights on the iVector.
w_.Resize(num_gauss, opts.ivector_dim);
} else {
w_vec_.Resize(fgmm.NumGauss());
w_vec_.CopyFromVec(fgmm.weights());
}
ComputeDerivedVars();
}
class IvectorExtractorComputeDerivedVarsClass {
public:
IvectorExtractorComputeDerivedVarsClass(IvectorExtractor *extractor,
int32 i):
extractor_(extractor), i_(i) { }
void operator () () { extractor_->ComputeDerivedVars(i_); }
private:
IvectorExtractor *extractor_;
int32 i_;
};
void IvectorExtractor::ComputeDerivedVars() {
KALDI_LOG << "Computing derived variables for iVector extractor";
gconsts_.Resize(NumGauss());
for (int32 i = 0; i < NumGauss(); i++) {
double var_logdet = -Sigma_inv_[i].LogPosDefDet();
gconsts_(i) = -0.5 * (var_logdet + FeatDim() * M_LOG_2PI);
// the gconsts don't contain any weight-related terms.
}
U_.Resize(NumGauss(), IvectorDim() * (IvectorDim() + 1) / 2);
Sigma_inv_M_.resize(NumGauss());
// Note, we could have used RunMultiThreaded for this and similar tasks we
// have here, but we found that we don't get as complete CPU utilization as we
// could because some tasks finish before others.
{
TaskSequencerConfig sequencer_opts;
sequencer_opts.num_threads = g_num_threads;
TaskSequencer<IvectorExtractorComputeDerivedVarsClass> sequencer(
sequencer_opts);
for (int32 i = 0; i < NumGauss(); i++)
sequencer.Run(new IvectorExtractorComputeDerivedVarsClass(this, i));
}
KALDI_LOG << "Done.";
}
void IvectorExtractor::ComputeDerivedVars(int32 i) {
SpMatrix<double> temp_U(IvectorDim());
// temp_U = M_i^T Sigma_i^{-1} M_i
temp_U.AddMat2Sp(1.0, M_[i], kTrans, Sigma_inv_[i], 0.0);
SubVector<double> temp_U_vec(temp_U.Data(),
IvectorDim() * (IvectorDim() + 1) / 2);
U_.Row(i).CopyFromVec(temp_U_vec);
Sigma_inv_M_[i].Resize(FeatDim(), IvectorDim());
Sigma_inv_M_[i].AddSpMat(1.0, Sigma_inv_[i], M_[i], kNoTrans, 0.0);
}
void IvectorExtractor::GetIvectorDistWeight(
const IvectorExtractorUtteranceStats &utt_stats,
const VectorBase<double> &mean,
VectorBase<double> *linear,
SpMatrix<double> *quadratic) const {
// If there is no w_, then weights do not depend on the iVector
// and the weights contribute nothing to the distribution.
if (!IvectorDependentWeights())
return;
Vector<double> logw_unnorm(NumGauss());
logw_unnorm.AddMatVec(1.0, w_, kNoTrans, mean, 0.0);
Vector<double> w(logw_unnorm);
w.ApplySoftMax(); // now w is the weights.
// See eq.58 in SGMM paper
// http://www.sciencedirect.com/science/article/pii/S088523081000063X
// linear_coeff(i) = \gamma_{jmi} - \gamma_{jm} \hat{w}_{jmi} + \max(\gamma_{jmi}, \gamma_{jm} \hat{w}_{jmi} \hat{\w}_i \v_{jm}
// here \v_{jm} corresponds to the iVector. Ignore the j,m indices.
Vector<double> linear_coeff(NumGauss());
Vector<double> quadratic_coeff(NumGauss());
double gamma = utt_stats.gamma_.Sum();
for (int32 i = 0; i < NumGauss(); i++) {
double gamma_i = utt_stats.gamma_(i);
double max_term = std::max(gamma_i, gamma * w(i));
linear_coeff(i) = gamma_i - gamma * w(i) + max_term * logw_unnorm(i);
quadratic_coeff(i) = max_term;
}
linear->AddMatVec(1.0, w_, kTrans, linear_coeff, 1.0);
// *quadratic += \sum_i quadratic_coeff(i) w_i w_i^T, where w_i is
// i'th row of w_.
quadratic->AddMat2Vec(1.0, w_, kTrans, quadratic_coeff, 1.0);
}
void IvectorExtractor::GetIvectorDistMean(
const IvectorExtractorUtteranceStats &utt_stats,
VectorBase<double> *linear,
SpMatrix<double> *quadratic) const {
int32 I = NumGauss();
for (int32 i = 0; i < I; i++) {
double gamma = utt_stats.gamma_(i);
if (gamma != 0.0) {
SubVector<double> x(utt_stats.X_, i); // == \gamma(i) \m_i
// next line: a += \gamma_i \M_i^T \Sigma_i^{-1} \m_i
linear->AddMatVec(1.0, Sigma_inv_M_[i], kTrans, x, 1.0);
}
}
SubVector<double> q_vec(quadratic->Data(), IvectorDim()*(IvectorDim()+1)/2);
q_vec.AddMatVec(1.0, U_, kTrans, utt_stats.gamma_, 1.0);
}
void IvectorExtractor::GetIvectorDistPrior(
const IvectorExtractorUtteranceStats &utt_stats,
VectorBase<double> *linear,
SpMatrix<double> *quadratic) const {
(*linear)(0) += prior_offset_; // the zero'th dimension has an offset mean.
/// The inverse-variance for the prior is the unit matrix.
quadratic->AddToDiag(1.0);
}
double IvectorExtractor::GetAcousticAuxfWeight(
const IvectorExtractorUtteranceStats &utt_stats,
const VectorBase<double> &mean,
const SpMatrix<double> *var) const {
if (!IvectorDependentWeights()) { // Not using the weight-projection matrices.
Vector<double> log_w_vec(w_vec_);
log_w_vec.ApplyLog();
return VecVec(log_w_vec, utt_stats.gamma_);
} else {
Vector<double> w(NumGauss());
w.AddMatVec(1.0, w_, kNoTrans, mean, 0.0); // now w is unnormalized
// log-weights.
double lse = w.LogSumExp();
w.Add(-lse); // Normalize so log-weights sum to one.
// "ans" below is the point-value of the weight auxf, without
// considering the variance. At the moment, "w" contains
// the normalized log weights.
double ans = VecVec(w, utt_stats.gamma_);
w.ApplyExp(); // now w is the weights.
if (var == NULL) {
return ans;
} else {
// Below, "Jacobian" will be the derivative d(log_w) / d(ivector)
// = (I - w w^T) W, where W (w_ in the code) is the projection matrix
// from iVector space to unnormalized log-weights, and w is the normalized
// weight values at the current point.
Matrix<double> Jacobian(w_);
Vector<double> WTw(IvectorDim()); // W^T w
WTw.AddMatVec(1.0, w_, kTrans, w, 0.0);
Jacobian.AddVecVec(1.0, w, WTw); // Jacobian += (w (W^T w)^T = w^T w W)
// the matrix S is the negated 2nd derivative of the objf w.r.t. the iVector \x.
SpMatrix<double> S(IvectorDim());
S.AddMat2Vec(1.0, Jacobian, kTrans, Vector<double>(utt_stats.gamma_), 0.0);
ans += -0.5 * TraceSpSp(S, *var);
return ans;
}
}
}
double IvectorExtractor::GetAuxf(const IvectorExtractorUtteranceStats &utt_stats,
const VectorBase<double> &mean,
const SpMatrix<double> *var) const {
double acoustic_auxf = GetAcousticAuxf(utt_stats, mean, var),
prior_auxf = GetPriorAuxf(mean, var), num_frames = utt_stats.gamma_.Sum();
KALDI_VLOG(3) << "Acoustic auxf is " << (acoustic_auxf/num_frames) << "/frame over "
<< num_frames << " frames, prior auxf is " << prior_auxf
<< " = " << (prior_auxf/num_frames) << " per frame.";
return acoustic_auxf + prior_auxf;
}
// gets logdet of a matrix while suppressing exceptions; always returns finite
// value even if there was a problem.
static double GetLogDetNoFailure(const SpMatrix<double> &var) {
try {
return var.LogPosDefDet();
} catch (...) {
Vector<double> eigs(var.NumRows());
var.Eig(&eigs);
int32 floored;
eigs.ApplyFloor(1.0e-20, &floored);
if (floored > 0)
KALDI_WARN << "Floored " << floored << " eigenvalues of variance.";
eigs.ApplyLog();
return eigs.Sum();
}
}
/*
Get the prior-related part of the auxiliary function. Suppose
the ivector is x, the prior distribution is p(x), the likelihood
of the data given x (itself an auxiliary function) is q(x) and
the prior is r(x).
In the case where we just have a point ivector x and no p(x),
the prior-related term we return will just be q(x).
If we have a distribution over x, we define an auxiliary function
t(x) = \int p(x) log(q(x)r(x) / p(x)) dx.
We separate this into data-dependent and prior parts, where the prior
part is
\int p(x) log(q(x) / p(x)) dx
(which this function returns), and the acoustic part is
\int p(x) log(r(x)) dx.
Note that the fact that we divide by p(x) in the prior part and not
the acoustic part is a bit arbitrary, at least the way we have written
it down here; it doesn't matter where we do it, but this way seems
more natural.
*/
double IvectorExtractor::GetPriorAuxf(
const VectorBase<double> &mean,
const SpMatrix<double> *var) const {
KALDI_ASSERT(mean.Dim() == IvectorDim());
Vector<double> offset(mean);
offset(0) -= prior_offset_; // The mean of the prior distribution
// may only be nonzero in the first dimension. Now, "offset" is the
// offset of ivector from the prior's mean.
if (var == NULL) {
// The log-determinant of the variance of the prior distribution is one,
// since it's the unit matrix.
return -0.5 * (VecVec(offset, offset) + IvectorDim()*M_LOG_2PI);
} else {
// The mean-related part of the answer will be
// -0.5 * (VecVec(offset, offset), just like above.
// The variance-related part will be
// \int p(x) . -0.5 (x^T I x - x^T var^{-1} x + logdet(I) - logdet(var)) dx
// and using the fact that x is distributed with variance "var", this is:
//= \int p(x) . -0.5 (x^T I x - x^T var^{-1} x + logdet(I) - logdet(var)) dx
// = -0.5 ( trace(var I) - trace(var^{-1} var) + 0.0 - logdet(var))
// = -0.5 ( trace(var) - dim(var) - logdet(var))
KALDI_ASSERT(var->NumRows() == IvectorDim());
return -0.5 * (VecVec(offset, offset) + var->Trace() -
IvectorDim() - GetLogDetNoFailure(*var));
}
}
/* Gets the acoustic-related part of the auxf.
If the distribution over the ivector given by "mean" and
"var" is p(x), and the acoustic auxiliary-function given
x is r(x), this function returns
\int p(x) log r(x) dx
*/
double IvectorExtractor::GetAcousticAuxf(
const IvectorExtractorUtteranceStats &utt_stats,
const VectorBase<double> &mean,
const SpMatrix<double> *var) const {
double weight_auxf = GetAcousticAuxfWeight(utt_stats, mean, var),
gconst_auxf = GetAcousticAuxfGconst(utt_stats),
mean_auxf = GetAcousticAuxfMean(utt_stats, mean, var),
var_auxf = GetAcousticAuxfVariance(utt_stats),
T = utt_stats.gamma_.Sum();
KALDI_VLOG(3) << "Per frame, auxf is: weight " << (weight_auxf/T) << ", gconst "
<< (gconst_auxf/T) << ", mean " << (mean_auxf/T) << ", var "
<< (var_auxf/T) << ", over " << T << " frames.";
return weight_auxf + gconst_auxf + mean_auxf + var_auxf;
}
/* This is the part of the auxf that involves the data
means, and we also involve the gconsts here.
Let \m_i be the observed data mean vector for the
i'th Gaussian (which we get from the utterance-specific
stats). Let \mu_i(\x) be the mean of the i'th Gaussian,
written as a function of the iVector \x.
\int_\x p(\x) (\sum_i \gamma_i -0.5 (\mu(\x) - \m_i)^T \Sigma_i^{-1} (\mu(\x) - \m_i)) d\x
To compute this integral we'll first write out the summation as a function of \x.
\sum_i -0.5 \gamma_i \m_i^T \Sigma_i^{-1} \m_i
+ \gamma_i \mu(\x)^T \Sigma_i^{-1} \m_i
-0.5 \gamma_i \mu(\x)^T \Sigma_i^{-1} \m_i
= \sum_i -0.5 \gamma_i \m_i^T \Sigma_i^{-1} \m_i
+ \gamma_i \x^T \M_i^T \Sigma_i^{-1} \m_i
-0.5 \gamma_i \x^T \M_i^T \Sigma_i^{-1} \x
= K + \x^T \a - 0.5 \x^T \B \x,
where K = \sum_i -0.5 \gamma_i \m_i^T \Sigma_i^{-1} \m_i
\a = \sum_i \gamma_i \M_i^T \Sigma_i^{-1} \m_i
\B = \sum_i \gamma_i \U_i (where \U_i = \M_i^T \Sigma_i^{-1} \M_i
has been stored previously).
Note: the matrix M in the stats actually contains \gamma_i \m_i,
i.e. the mean times the count, so we need to modify the definitions
above accordingly.
*/
double IvectorExtractor::GetAcousticAuxfMean(
const IvectorExtractorUtteranceStats &utt_stats,
const VectorBase<double> &mean,
const SpMatrix<double> *var) const {
double K = 0.0;
Vector<double> a(IvectorDim()), temp(FeatDim());
int32 I = NumGauss();
for (int32 i = 0; i < I; i++) {
double gamma = utt_stats.gamma_(i);
if (gamma != 0.0) {
Vector<double> x(utt_stats.X_.Row(i)); // == \gamma(i) \m_i
temp.AddSpVec(1.0 / gamma, Sigma_inv_[i], x, 0.0);
// now temp = Sigma_i^{-1} \m_i.
// next line: K += -0.5 \gamma_i \m_i^T \Sigma_i^{-1} \m_i
K += -0.5 * VecVec(x, temp);
// next line: a += \gamma_i \M_i^T \Sigma_i^{-1} \m_i
a.AddMatVec(gamma, M_[i], kTrans, temp, 1.0);
}
}
SpMatrix<double> B(IvectorDim());
SubVector<double> B_vec(B.Data(), IvectorDim()*(IvectorDim()+1)/2);
B_vec.AddMatVec(1.0, U_, kTrans, Vector<double>(utt_stats.gamma_), 0.0);
double ans = K + VecVec(mean, a) - 0.5 * VecSpVec(mean, B, mean);
if (var != NULL)
ans -= 0.5 * TraceSpSp(*var, B);
return ans;
}
double IvectorExtractor::GetAcousticAuxfGconst(
const IvectorExtractorUtteranceStats &utt_stats) const {
return VecVec(Vector<double>(utt_stats.gamma_),
gconsts_);
}
double IvectorExtractor::GetAcousticAuxfVariance(
const IvectorExtractorUtteranceStats &utt_stats) const {
if (utt_stats.S_.empty()) {
// we did not store the variance, so assume it's as predicted
// by the model itself.
// for each Gaussian i, we have a term -0.5 * gamma(i) * trace(Sigma[i] * Sigma[i]^{-1})
// = -0.5 * gamma(i) * FeatDim().
return -0.5 * utt_stats.gamma_.Sum() * FeatDim();
} else {
int32 I = NumGauss();
double ans = 0.0;
for (int32 i = 0; i < I; i++) {
double gamma = utt_stats.gamma_(i);
if (gamma != 0.0) {
SpMatrix<double> var(utt_stats.S_[i]);
var.Scale(1.0 / gamma);
Vector<double> mean(utt_stats.X_.Row(i));
mean.Scale(1.0 / gamma);
var.AddVec2(-1.0, mean); // get centered covariance..
ans += -0.5 * gamma * TraceSpSp(var, Sigma_inv_[i]);
}
}
return ans;
}
}
void IvectorExtractor::TransformIvectors(const MatrixBase<double> &T,
double new_prior_offset) {
Matrix<double> Tinv(T);
Tinv.Invert();
// w <-- w Tinv. (construct temporary copy with Matrix<double>(w))
if (IvectorDependentWeights())
w_.AddMatMat(1.0, Matrix<double>(w_), kNoTrans, Tinv, kNoTrans, 0.0);
// next: M_i <-- M_i Tinv. (construct temporary copy with Matrix<double>(M_[i]))
for (int32 i = 0; i < NumGauss(); i++)
M_[i].AddMatMat(1.0, Matrix<double>(M_[i]), kNoTrans, Tinv, kNoTrans, 0.0);
KALDI_LOG << "Setting iVector prior offset to " << new_prior_offset;
prior_offset_ = new_prior_offset;
}
void OnlineIvectorEstimationStats::AccStats(
const IvectorExtractor &extractor,
const VectorBase<BaseFloat> &feature,
const std::vector<std::pair<int32, BaseFloat> > &gauss_post) {
KALDI_ASSERT(extractor.IvectorDim() == this->IvectorDim());
KALDI_ASSERT(!extractor.IvectorDependentWeights());
Vector<double> feature_dbl(feature);
double tot_weight = 0.0;
int32 ivector_dim = this->IvectorDim(),
quadratic_term_dim = (ivector_dim * (ivector_dim + 1)) / 2;
SubVector<double> quadratic_term_vec(quadratic_term_.Data(),
quadratic_term_dim);
for (size_t idx = 0; idx < gauss_post.size(); idx++) {
int32 g = gauss_post[idx].first;
double weight = gauss_post[idx].second;
// allow negative weights; it's needed in the online iVector extraction
// with speech-silence detection based on decoder traceback (we subtract
// stuff we previously added if the traceback changes).
if (weight == 0.0)
continue;
linear_term_.AddMatVec(weight, extractor.Sigma_inv_M_[g], kTrans,
feature_dbl, 1.0);
SubVector<double> U_g(extractor.U_, g);
quadratic_term_vec.AddVec(weight, U_g);
tot_weight += weight;
}
if (max_count_ > 0.0) {
// see comments in header RE max_count for explanation. It relates to
// prior scaling when the count exceeds max_count_
double old_num_frames = num_frames_,
new_num_frames = num_frames_ + tot_weight;
double old_prior_scale = std::max(old_num_frames, max_count_) / max_count_,
new_prior_scale = std::max(new_num_frames, max_count_) / max_count_;
// The prior_scales are the inverses of the scales we would put on the stats
// if we were implementing this by scaling the stats. Instead we
// scale the prior term.
double prior_scale_change = new_prior_scale - old_prior_scale;
if (prior_scale_change != 0.0) {
linear_term_(0) += prior_offset_ * prior_scale_change;
quadratic_term_.AddToDiag(prior_scale_change);
}
}
num_frames_ += tot_weight;
}
// This is used in OnlineIvectorEstimationStats::AccStats().
struct GaussInfo {
// total weight for this Gaussian.
BaseFloat tot_weight;
// vector of pairs of (frame-index, weight for this Gaussian)
std::vector<std::pair<int32, BaseFloat> > frame_weights;
GaussInfo(): tot_weight(0.0) { }
};
static void ConvertPostToGaussInfo(
const std::vector<std::vector<std::pair<int32, BaseFloat> > > &gauss_post,
std::unordered_map<int32, GaussInfo> *gauss_info) {
int32 num_frames = gauss_post.size();
for (int32 t = 0; t < num_frames; t++) {
const std::vector<std::pair<int32, BaseFloat> > &this_post = gauss_post[t];
auto iter = this_post.begin(), end = this_post.end();
for (; iter != end; ++iter) {
int32 gauss_idx = iter->first;
GaussInfo &info = (*gauss_info)[gauss_idx];
BaseFloat weight = iter->second;
info.tot_weight += weight;
info.frame_weights.push_back(std::pair<int32, BaseFloat>(t, weight));
}
}
}
void OnlineIvectorEstimationStats::AccStats(
const IvectorExtractor &extractor,
const MatrixBase<BaseFloat> &features,
const std::vector<std::vector<std::pair<int32, BaseFloat> > > &gauss_post) {
KALDI_ASSERT(extractor.IvectorDim() == this->IvectorDim());
KALDI_ASSERT(!extractor.IvectorDependentWeights());
int32 feat_dim = features.NumCols();
std::unordered_map<int32, GaussInfo> gauss_info;
ConvertPostToGaussInfo(gauss_post, &gauss_info);
Vector<double> weighted_feats(feat_dim, kUndefined);
double tot_weight = 0.0;
int32 ivector_dim = this->IvectorDim(),
quadratic_term_dim = (ivector_dim * (ivector_dim + 1)) / 2;
SubVector<double> quadratic_term_vec(quadratic_term_.Data(),
quadratic_term_dim);
std::unordered_map<int32, GaussInfo>::const_iterator
iter = gauss_info.begin(), end = gauss_info.end();
for (; iter != end; ++iter) {
int32 gauss_idx = iter->first;
const GaussInfo &info = iter->second;
weighted_feats.SetZero();
std::vector<std::pair<int32, BaseFloat> >::const_iterator
f_iter = info.frame_weights.begin(), f_end = info.frame_weights.end();
for (; f_iter != f_end; ++f_iter) {
int32 t = f_iter->first;
BaseFloat weight = f_iter->second;
weighted_feats.AddVec(weight, features.Row(t));
}
BaseFloat this_tot_weight = info.tot_weight;
linear_term_.AddMatVec(1.0, extractor.Sigma_inv_M_[gauss_idx], kTrans,
weighted_feats, 1.0);
SubVector<double> U_g(extractor.U_, gauss_idx);
quadratic_term_vec.AddVec(this_tot_weight, U_g);
tot_weight += this_tot_weight;
}
if (max_count_ > 0.0) {
// see comments in header RE max_count for explanation. It relates to
// prior scaling when the count exceeds max_count_
double old_num_frames = num_frames_,
new_num_frames = num_frames_ + tot_weight;
double old_prior_scale = std::max(old_num_frames, max_count_) / max_count_,
new_prior_scale = std::max(new_num_frames, max_count_) / max_count_;
// The prior_scales are the inverses of the scales we would put on the stats
// if we were implementing this by scaling the stats. Instead we
// scale the prior term.
double prior_scale_change = new_prior_scale - old_prior_scale;
if (prior_scale_change != 0.0) {
linear_term_(0) += prior_offset_ * prior_scale_change;
quadratic_term_.AddToDiag(prior_scale_change);
}
}
num_frames_ += tot_weight;
}
void OnlineIvectorEstimationStats::Scale(double scale) {
KALDI_ASSERT(scale >= 0.0 && scale <= 1.0);
double old_num_frames = num_frames_;
num_frames_ *= scale;
quadratic_term_.Scale(scale);
linear_term_.Scale(scale);
// Scale back up the prior term, by adding in whatever we scaled down.
if (max_count_ == 0.0) {
linear_term_(0) += prior_offset_ * (1.0 - scale);
quadratic_term_.AddToDiag(1.0 - scale);
} else {
double new_num_frames = num_frames_;
double old_prior_scale =
scale * std::max(old_num_frames, max_count_) / max_count_,
new_prior_scale = std::max(new_num_frames, max_count_) / max_count_;
// old_prior_scale is the scale the prior term currently has in the stats,
// i.e. the previous scale times "scale" as we just scaled the stats.
// new_prior_scale is the scale we want the prior term to have.
linear_term_(0) += prior_offset_ * (new_prior_scale - old_prior_scale);
quadratic_term_.AddToDiag(new_prior_scale - old_prior_scale);
}
}
void OnlineIvectorEstimationStats::Write(std::ostream &os, bool binary) const {
WriteToken(os, binary, "<OnlineIvectorEstimationStats>");
WriteToken(os, binary, "<PriorOffset>");
WriteBasicType(os, binary, prior_offset_);
WriteToken(os, binary, "<MaxCount>");
WriteBasicType(os, binary, max_count_);
WriteToken(os, binary, "<NumFrames>");
WriteBasicType(os, binary, num_frames_);
WriteToken(os, binary, "<QuadraticTerm>");
quadratic_term_.Write(os, binary);
WriteToken(os, binary, "<LinearTerm>");
linear_term_.Write(os, binary);
WriteToken(os, binary, "</OnlineIvectorEstimationStats>");
}
void OnlineIvectorEstimationStats::Read(std::istream &is, bool binary) {
ExpectToken(is, binary, "<OnlineIvectorEstimationStats>");
ExpectToken(is, binary, "<PriorOffset>");
ReadBasicType(is, binary, &prior_offset_);
std::string tok;
ReadToken(is, binary, &tok);
if (tok == "<MaxCount>") {
ReadBasicType(is, binary, &max_count_);
ExpectToken(is, binary, "<NumFrames>");
ReadBasicType(is, binary, &num_frames_);
} else {
KALDI_ASSERT(tok == "<NumFrames>");
max_count_ = 0.0;
ReadBasicType(is, binary, &num_frames_);
}
ExpectToken(is, binary, "<QuadraticTerm>");
quadratic_term_.Read(is, binary);
ExpectToken(is, binary, "<LinearTerm>");
linear_term_.Read(is, binary);
ExpectToken(is, binary, "</OnlineIvectorEstimationStats>");
}
void OnlineIvectorEstimationStats::GetIvector(
int32 num_cg_iters,
VectorBase<double> *ivector) const {
KALDI_ASSERT(ivector != NULL && ivector->Dim() ==
this->IvectorDim());
if (num_frames_ > 0.0) {
// could be done exactly as follows:
// SpMatrix<double> quadratic_inv(quadratic_term_);
// quadratic_inv.Invert();
// ivector->AddSpVec(1.0, quadratic_inv, linear_term_, 0.0);
if ((*ivector)(0) == 0.0)
(*ivector)(0) = prior_offset_; // better initial guess.
LinearCgdOptions opts;
opts.max_iters = num_cg_iters;
LinearCgd(opts, quadratic_term_, linear_term_, ivector);
} else {
// Use 'default' value.
ivector->SetZero();
(*ivector)(0) = prior_offset_;
}
KALDI_VLOG(4) << "Objective function improvement from estimating the "
<< "iVector (vs. default value) is "
<< ObjfChange(*ivector);
}
double OnlineIvectorEstimationStats::ObjfChange(
const VectorBase<double> &ivector) const {
double ans = Objf(ivector) - DefaultObjf();
KALDI_ASSERT(!KALDI_ISNAN(ans));
return ans;
}
double OnlineIvectorEstimationStats::Objf(
const VectorBase<double> &ivector) const {
if (num_frames_ == 0.0) {
return 0.0;
} else {
return (1.0 / num_frames_) * (-0.5 * VecSpVec(ivector, quadratic_term_,
ivector)
+ VecVec(ivector, linear_term_));
}
}
double OnlineIvectorEstimationStats::DefaultObjf() const {
if (num_frames_ == 0.0) {
return 0.0;
} else {
double x = prior_offset_;
return (1.0 / num_frames_) * (-0.5 * quadratic_term_(0, 0) * x * x
+ x * linear_term_(0));
}
}
OnlineIvectorEstimationStats::OnlineIvectorEstimationStats(int32 ivector_dim,
BaseFloat prior_offset,
BaseFloat max_count):
prior_offset_(prior_offset), max_count_(max_count), num_frames_(0.0),
quadratic_term_(ivector_dim), linear_term_(ivector_dim) {
if (ivector_dim != 0) {
linear_term_(0) += prior_offset;
quadratic_term_.AddToDiag(1.0);
}
}
OnlineIvectorEstimationStats::OnlineIvectorEstimationStats(
const OnlineIvectorEstimationStats &other):
prior_offset_(other.prior_offset_),
max_count_(other.max_count_),
num_frames_(other.num_frames_),
quadratic_term_(other.quadratic_term_),
linear_term_(other.linear_term_) { }
void IvectorExtractor::Write(std::ostream &os, bool binary) const {
WriteToken(os, binary, "<IvectorExtractor>");
WriteToken(os, binary, "<w>");
w_.Write(os, binary);
WriteToken(os, binary, "<w_vec>");
w_vec_.Write(os, binary);
WriteToken(os, binary, "<M>");
int32 size = M_.size();
WriteBasicType(os, binary, size);
for (int32 i = 0; i < size; i++)
M_[i].Write(os, binary);
WriteToken(os, binary, "<SigmaInv>");
KALDI_ASSERT(size == static_cast<int32>(Sigma_inv_.size()));
for (int32 i = 0; i < size; i++)
Sigma_inv_[i].Write(os, binary);
WriteToken(os, binary, "<IvectorOffset>");
WriteBasicType(os, binary, prior_offset_);
WriteToken(os, binary, "</IvectorExtractor>");
}
void IvectorExtractor::Read(std::istream &is, bool binary) {
ExpectToken(is, binary, "<IvectorExtractor>");
ExpectToken(is, binary, "<w>");
w_.Read(is, binary);
ExpectToken(is, binary, "<w_vec>");
w_vec_.Read(is, binary);
ExpectToken(is, binary, "<M>");
int32 size;
ReadBasicType(is, binary, &size);
KALDI_ASSERT(size > 0);
M_.resize(size);
for (int32 i = 0; i < size; i++)
M_[i].Read(is, binary);
ExpectToken(is, binary, "<SigmaInv>");
Sigma_inv_.resize(size);
for (int32 i = 0; i < size; i++)
Sigma_inv_[i].Read(is, binary);
ExpectToken(is, binary, "<IvectorOffset>");
ReadBasicType(is, binary, &prior_offset_);
ExpectToken(is, binary, "</IvectorExtractor>");
ComputeDerivedVars();
}
void IvectorExtractorUtteranceStats::AccStats(
const MatrixBase<BaseFloat> &feats,
const Posterior &post) {
typedef std::vector<std::pair<int32, BaseFloat> > VecType;
int32 num_frames = feats.NumRows(),
num_gauss = X_.NumRows(),
feat_dim = feats.NumCols();
KALDI_ASSERT(X_.NumCols() == feat_dim);
KALDI_ASSERT(feats.NumRows() == static_cast<int32>(post.size()));
bool update_variance = (!S_.empty());
SpMatrix<double> outer_prod(feat_dim);
for (int32 t = 0; t < num_frames; t++) {
SubVector<BaseFloat> frame(feats, t);
const VecType &this_post(post[t]);
if (update_variance) {
outer_prod.SetZero();
outer_prod.AddVec2(1.0, frame);
}
for (VecType::const_iterator iter = this_post.begin();
iter != this_post.end(); ++iter) {
int32 i = iter->first; // Gaussian index.
KALDI_ASSERT(i >= 0 && i < num_gauss &&
"Out-of-range Gaussian (mismatched posteriors?)");
double weight = iter->second;
gamma_(i) += weight;
X_.Row(i).AddVec(weight, frame);
if (update_variance)
S_[i].AddSp(weight, outer_prod);
}
}
}
void IvectorExtractorUtteranceStats::Scale(double scale) {
gamma_.Scale(scale);
X_.Scale(scale);
for (size_t i = 0; i < S_.size(); i++)
S_[i].Scale(scale);
}
IvectorExtractorStats::IvectorExtractorStats(
const IvectorExtractor &extractor,
const IvectorExtractorStatsOptions &stats_opts):
config_(stats_opts) {
int32 S = extractor.IvectorDim(), D = extractor.FeatDim(),
I = extractor.NumGauss();
KALDI_ASSERT(config_.num_samples_for_weights > 1);
tot_auxf_ = 0.0;
gamma_.Resize(I);
Y_.resize(I);
for (int32 i = 0; i < I; i++)
Y_[i].Resize(D, S);
R_.Resize(I, S * (S + 1) / 2);
R_num_cached_ = 0;
KALDI_ASSERT(stats_opts.cache_size > 0 && "--cache-size=0 not allowed");
R_gamma_cache_.Resize(stats_opts.cache_size, I);
R_ivec_scatter_cache_.Resize(stats_opts.cache_size, S*(S+1)/2);
if (extractor.IvectorDependentWeights()) {
Q_.Resize(I, S * (S + 1) / 2);
G_.Resize(I, S);
}
if (stats_opts.update_variances) {
S_.resize(I);
for (int32 i = 0; i < I; i++)
S_[i].Resize(D);
}
num_ivectors_ = 0;
ivector_sum_.Resize(S);
ivector_scatter_.Resize(S);
}
void IvectorExtractorStats::CommitStatsForM(
const IvectorExtractor &extractor,
const IvectorExtractorUtteranceStats &utt_stats,
const VectorBase<double> &ivec_mean,
const SpMatrix<double> &ivec_var) {
gamma_Y_lock_.lock();
// We do the occupation stats here also.
gamma_.AddVec(1.0, utt_stats.gamma_);
// Stats for the linear term in M:
for (int32 i = 0; i < extractor.NumGauss(); i++) {
Y_[i].AddVecVec(1.0, utt_stats.X_.Row(i),
Vector<double>(ivec_mean));
}
gamma_Y_lock_.unlock();
SpMatrix<double> ivec_scatter(ivec_var);
ivec_scatter.AddVec2(1.0, ivec_mean);
R_cache_lock_.lock();
while (R_num_cached_ == R_gamma_cache_.NumRows()) {
// Cache full. The "while" statement is in case of certain race conditions.
R_cache_lock_.unlock();
FlushCache();
R_cache_lock_.lock();
}
R_gamma_cache_.Row(R_num_cached_).CopyFromVec(utt_stats.gamma_);
int32 ivector_dim = ivec_mean.Dim();
SubVector<double> ivec_scatter_vec(ivec_scatter.Data(),
ivector_dim * (ivector_dim + 1) / 2);
R_ivec_scatter_cache_.Row(R_num_cached_).CopyFromVec(ivec_scatter_vec);
R_num_cached_++;
R_cache_lock_.unlock();
}
void IvectorExtractorStats::FlushCache() {
R_cache_lock_.lock();
if (R_num_cached_ > 0) {
KALDI_VLOG(1) << "Flushing cache for IvectorExtractorStats";
// Store these quantities as copies in memory so other threads can use the
// cache while we update R_ from the cache.
Matrix<double> R_gamma_cache(
R_gamma_cache_.Range(0, R_num_cached_,
0, R_gamma_cache_.NumCols()));
Matrix<double> R_ivec_scatter_cache(
R_ivec_scatter_cache_.Range(0, R_num_cached_,
0, R_ivec_scatter_cache_.NumCols()));
R_num_cached_ = 0; // As far as other threads are concerned, the cache is
// cleared and they may write to it.
R_cache_lock_.unlock();
R_lock_.lock();
R_.AddMatMat(1.0, R_gamma_cache, kTrans,
R_ivec_scatter_cache, kNoTrans, 1.0);
R_lock_.unlock();
} else {
R_cache_lock_.unlock();
}
}
void IvectorExtractorStats::CommitStatsForSigma(
const IvectorExtractor &extractor,
const IvectorExtractorUtteranceStats &utt_stats) {
variance_stats_lock_.lock();
// Storing the raw scatter statistics per Gaussian. In the update phase we'll
// take into account some other terms relating to the model means and their
// correlation with the data.
for (int32 i = 0; i < extractor.NumGauss(); i++)
S_[i].AddSp(1.0, utt_stats.S_[i]);
variance_stats_lock_.unlock();
}