forked from microsoft/CNTK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TrainingNodes.h
1895 lines (1625 loc) · 76.9 KB
/
TrainingNodes.h
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
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#pragma once
#include "Basics.h"
#include "ComputationNode.h"
#include "ConvolutionEngine.h"
#include <map>
#include <string>
#include <vector>
#include <stdexcept>
#include <list>
#include <memory>
namespace Microsoft { namespace MSR { namespace CNTK {
// -----------------------------------------------------------------------
/// SquareErrorNode (left, right)
// -----------------------------------------------------------------------
//note: to save computation the gradient may be scaled by an constant.
template <class ElemType>
class SquareErrorNode : public ComputationNodeNonLooping /*ComputationNode*/<ElemType>, public NumInputs<2>
{
typedef ComputationNodeNonLooping<ElemType> Base;
UsingComputationNodeMembersBoilerplate;
static const std::wstring TypeName()
{
return L"SquareError";
}
public:
DeclareConstructorFromConfigWithNumInputs(SquareErrorNode);
SquareErrorNode(DEVICEID_TYPE deviceId, const wstring& name)
: Base(deviceId, name)
{
}
virtual void BackpropToNonLooping(size_t inputIndex) override
{
FrameRange fr(Input(0)->GetMBLayout());
auto gradient = Input(inputIndex)->GradientFor(fr);
Matrix<ElemType>::Multiply1x1AndWeightedAdd(inputIndex == 0 ? 1.0f : -1.0f, Gradient() /*1x1*/, *m_leftMinusRight, 1.0f, gradient);
}
virtual bool OutputUsedInComputingInputNodesGradients() const override
{
return false;
}
virtual bool InputUsedInComputingInputNodesGradients(size_t /*childIndex*/) const override
{
return false;
}
virtual void UpdateFunctionMBSize() override
{
m_leftMinusRight->Resize(Input(0)->Value());
}
virtual void /*ComputationNodeNonLooping::*/ ForwardPropNonLooping() override
{
FrameRange fr(Input(0)->GetMBLayout());
m_leftMinusRight->AssignDifferenceOf(Input(0)->ValueFor(fr), Input(1)->ValueFor(fr));
MaskMissingColumnsToZero(*m_leftMinusRight, Input(0)->GetMBLayout(), fr); // we are fine since it will only be called with full minibatch.
ElemType v = m_leftMinusRight->FrobeniusNorm();
Value().VerifySize(1, 1);
Value().SetValue(v * v / 2);
#if NANCHECK
Value().HasNan("SquareError");
#endif
}
virtual void /*ComputationNodeBase::*/ Validate(bool isFinalValidationPass) override
{
ValidateBinaryReduce(isFinalValidationPass);
}
virtual void CopyTo(ComputationNodeBasePtr nodeP, const std::wstring& newName, const CopyNodeFlags flags) const override
{
Base::CopyTo(nodeP, newName, flags);
if (flags & CopyNodeFlags::copyNodeValue)
{
auto node = dynamic_pointer_cast<SquareErrorNode<ElemType>>(nodeP);
*node->m_leftMinusRight = *m_leftMinusRight;
}
}
// request matrices needed to do node function value evaluation
virtual void RequestMatricesBeforeForwardProp(MatrixPool& matrixPool)
{
Base::RequestMatricesBeforeForwardProp(matrixPool);
RequestMatrixFromPool(m_leftMinusRight, matrixPool);
}
// release gradient and temp matrices that no longer needed after all the children's gradients are computed.
virtual void ReleaseMatricesAfterBackprop(MatrixPool& matrixPool)
{
Base::ReleaseMatricesAfterBackprop(matrixPool);
ReleaseMatrixToPool(m_leftMinusRight, matrixPool);
}
private:
shared_ptr<Matrix<ElemType>> m_leftMinusRight;
};
template class SquareErrorNode<float>;
template class SquareErrorNode<double>;
// -----------------------------------------------------------------------
// CrossEntropyWithSoftmaxNode (labels, prediction)
// calculates: -sum(left_i * log(softmax_i(right)))
// -----------------------------------------------------------------------
template <class ElemType>
class CrossEntropyWithSoftmaxNode : public ComputationNodeNonLooping /*ComputationNode*/<ElemType>, public NumInputs<2>
{
typedef ComputationNodeNonLooping<ElemType> Base;
UsingComputationNodeMembersBoilerplate;
static const std::wstring TypeName()
{
return L"CrossEntropyWithSoftmax";
}
public:
DeclareConstructorFromConfigWithNumInputs(CrossEntropyWithSoftmaxNode);
CrossEntropyWithSoftmaxNode(DEVICEID_TYPE deviceId, const wstring& name)
: Base(deviceId, name)
{
}
virtual void BackpropToNonLooping(size_t inputIndex) override
{
FrameRange fr(Input(0)->GetMBLayout());
// left input is scalar
if (inputIndex == 0) // left derivative
{
#if DUMPOUTPUT
*m_logSoftmaxOfRight.Print("CrossEntropyWithSoftmax Partial-logSoftmaxOfRight");
Gradient().Print("CrossEntropyWithSoftmax Partial-gradientValues");
Input(0)->GradientFor(fr).Print("CrossEntropyWithSoftmaxNode Partial-Left-in");
#endif
auto gradient = Input(0)->GradientFor(fr);
Matrix<ElemType>::Multiply1x1AndWeightedAdd(-1.0f, Gradient() /*1x1*/, *m_logSoftmaxOfRight, 1.0f, gradient);
#if DUMPOUTPUT
Input(0)->GradientFor(fr).Print("CrossEntropyWithSoftmaxNode Partial-Left-out");
#endif
}
else if (inputIndex == 1) // right derivative
{
#if DUMPOUTPUT
*m_softmaxOfRight.Print("CrossEntropyWithSoftmax Partial-softmaxOfRight");
Input(0)->ValueFor(fr).Print("CrossEntropyWithSoftmax Partial-inputFunctionValues");
Gradient().Print("CrossEntropyWithSoftmax Partial-gradientValues");
Input(1)->GradientFor(fr).Print("CrossEntropyWithSoftmaxNode Partial-Right-in");
#endif
auto gradient = Input(1)->GradientFor(fr);
Matrix<ElemType>::AddScaledDifference(Gradient(), *m_softmaxOfRight, Input(0)->ValueFor(fr), gradient);
#if DUMPOUTPUT
Input(1)->GradientFor(fr).Print("CrossEntropyWithSoftmaxNode Partial-Right");
#endif
#ifdef _DEBUG
Input(1)->InvalidateMissingGradientColumns(fr); // TODO: This should not be necessary.
#endif
}
}
virtual bool OutputUsedInComputingInputNodesGradients() const override
{
return false;
}
virtual void UpdateFunctionMBSize() override
{
m_logSoftmaxOfRight->Resize(Input(1)->Value());
m_softmaxOfRight->Resize(*m_logSoftmaxOfRight);
}
virtual void /*ComputationNodeNonLooping::*/ ForwardPropNonLooping() override // -sum(left_i * log(softmax_i(right)))
{
FrameRange fr(Input(0)->GetMBLayout());
// first compute the softmax (column-wise)
// Note that we need both log and non-log for gradient computation.
m_logSoftmaxOfRight->AssignLogSoftmaxOf(Input(1)->ValueFor(fr), true);
m_softmaxOfRight->SetValue(*m_logSoftmaxOfRight);
m_softmaxOfRight->InplaceExp();
// flatten all gaps to zero, such that gaps will contribute zero to the sum
MaskMissingColumnsToZero(*m_logSoftmaxOfRight, Input(1)->GetMBLayout(), fr);
// reduce over all frames
Value().AssignInnerProductOfMatrices(Input(0)->MaskedValueFor(fr), *m_logSoftmaxOfRight);
Value() *= -1;
#if NANCHECK
Value().HasNan("CrossEntropyWithSoftmax");
#endif
#if DUMPOUTPUT
Value().Print("CrossEntropyWithSoftmaxNode");
#endif
}
virtual void /*ComputationNodeBase::*/ Validate(bool isFinalValidationPass) override
{
ValidateBinaryReduce(isFinalValidationPass);
}
virtual void CopyTo(ComputationNodeBasePtr nodeP, const std::wstring& newName, const CopyNodeFlags flags) const override
{
Base::CopyTo(nodeP, newName, flags);
if (flags & CopyNodeFlags::copyNodeValue)
{
auto node = dynamic_pointer_cast<CrossEntropyWithSoftmaxNode<ElemType>>(nodeP);
*node->m_logSoftmaxOfRight = *m_logSoftmaxOfRight;
*node->m_softmaxOfRight = *m_softmaxOfRight;
}
}
// request matrices needed to do node function value evaluation
virtual void RequestMatricesBeforeForwardProp(MatrixPool& matrixPool)
{
Base::RequestMatricesBeforeForwardProp(matrixPool);
RequestMatrixFromPool(m_logSoftmaxOfRight, matrixPool);
RequestMatrixFromPool(m_softmaxOfRight, matrixPool);
}
protected:
shared_ptr<Matrix<ElemType>> m_logSoftmaxOfRight;
shared_ptr<Matrix<ElemType>> m_softmaxOfRight;
};
template class CrossEntropyWithSoftmaxNode<float>;
template class CrossEntropyWithSoftmaxNode<double>;
// -----------------------------------------------------------------------
/// CrossEntropyNode (labels, prediction)
// -----------------------------------------------------------------------
// calculates: -sum(left_i * log(right_i))
// assume softmax is already done
// You probably want to use CrossEntropyWithSoftMaxNode instead, it is more efficient in most cases.
template <class ElemType>
class CrossEntropyNode : public ComputationNodeNonLooping /*ComputationNode*/<ElemType>, public NumInputs<2>
{
typedef ComputationNodeNonLooping<ElemType> Base;
UsingComputationNodeMembersBoilerplate;
static const std::wstring TypeName()
{
return L"CrossEntropy";
}
public:
DeclareConstructorFromConfigWithNumInputs(CrossEntropyNode);
CrossEntropyNode(DEVICEID_TYPE deviceId, const wstring& name)
: Base(deviceId, name)
{
}
virtual void BackpropToNonLooping(size_t inputIndex) override
{
FrameRange fr(Input(0)->GetMBLayout());
// left Node must be a scalar
if (inputIndex == 0) // left derivative
{
BackpropToLeft(*m_logOfRight, Input(0)->GradientFor(fr), Gradient());
}
else
{
BackpropToRight(*m_leftDivRight, Input(0)->ValueFor(fr), Input(1)->ValueFor(fr), Input(1)->GradientFor(fr), Gradient());
}
}
virtual bool OutputUsedInComputingInputNodesGradients() const override
{
return false;
}
/*TODO: merge with call site*/ void BackpropToLeft(const Matrix<ElemType>& logOfRight, Matrix<ElemType> inputGradientValues,
const Matrix<ElemType>& gradientValues)
{
Matrix<ElemType>::Multiply1x1AndWeightedAdd(-1.0f, gradientValues /*1x1*/, logOfRight, 1.0f, inputGradientValues);
}
/*TODO: merge with call site*/ void BackpropToRight(Matrix<ElemType>& leftDivRight,
const Matrix<ElemType> inputFunctionValues0, const Matrix<ElemType> inputFunctionValues1,
Matrix<ElemType> inputGradientValues, const Matrix<ElemType>& gradientValues)
{
FrameRange fr(Input(0)->GetMBLayout());
leftDivRight.AssignElementDivisionOf(inputFunctionValues0, inputFunctionValues1);
MaskMissingColumnsToZero(leftDivRight, Input(0)->GetMBLayout(), fr);
Matrix<ElemType>::Multiply1x1AndWeightedAdd(-1.0f, gradientValues /*1x1*/, leftDivRight, 1.0f, inputGradientValues);
}
virtual void UpdateFunctionMBSize() override
{
m_logOfRight->Resize(Input(1)->Value());
m_leftDivRight->Resize(Input(1)->Value());
}
// -sum(left_i * log(right_i))
virtual void /*ComputationNodeNonLooping::*/ ForwardPropNonLooping() override
{
FrameRange fr(Input(0)->GetMBLayout());
m_logOfRight->SetValue(Input(1)->ValueFor(fr));
m_logOfRight->InplaceLog();
MaskMissingColumnsToZero(*m_logOfRight, Input(1)->GetMBLayout(), fr);
Value().AssignInnerProductOfMatrices(Input(0)->MaskedValueFor(fr), *m_logOfRight);
Value() *= -1;
#if NANCHECK
functionValues.HasNan("CrossEntropy");
#endif
}
virtual void /*ComputationNodeBase::*/ Validate(bool isFinalValidationPass) override
{
ValidateBinaryReduce(isFinalValidationPass);
}
virtual void CopyTo(ComputationNodeBasePtr nodeP, const std::wstring& newName, const CopyNodeFlags flags) const override
{
Base::CopyTo(nodeP, newName, flags);
if (flags & CopyNodeFlags::copyNodeValue)
{
auto node = dynamic_pointer_cast<CrossEntropyNode<ElemType>>(nodeP);
*node->m_logOfRight = *m_logOfRight;
*node->m_leftDivRight = *m_leftDivRight;
}
}
// request matrices needed to do node function value evaluation
virtual void RequestMatricesBeforeForwardProp(MatrixPool& matrixPool)
{
Base::RequestMatricesBeforeForwardProp(matrixPool);
RequestMatrixFromPool(m_logOfRight, matrixPool);
}
// request matrices that are needed for gradient computation
virtual void RequestMatricesBeforeBackprop(MatrixPool& matrixPool)
{
Base::RequestMatricesBeforeBackprop(matrixPool);
RequestMatrixFromPool(m_leftDivRight, matrixPool);
}
// release gradient and temp matrices that no longer needed after all the children's gradients are computed.
virtual void ReleaseMatricesAfterBackprop(MatrixPool& matrixPool)
{
Base::ReleaseMatricesAfterBackprop(matrixPool);
ReleaseMatrixToPool(m_logOfRight, matrixPool);
ReleaseMatrixToPool(m_leftDivRight, matrixPool);
}
private:
// matrix value passed from evaluate to computePartial
shared_ptr<Matrix<ElemType>> m_logOfRight;
// temporary
shared_ptr<Matrix<ElemType>> m_leftDivRight;
};
template class CrossEntropyNode<float>;
template class CrossEntropyNode<double>;
// -----------------------------------------------------------------------
// MatrixL1RegNode (input)
// TODO: share most code with MatrixL2RegNode
// -----------------------------------------------------------------------
template <class ElemType>
class MatrixL1RegNode : public ComputationNodeNonLooping /*ComputationNode*/<ElemType>, public NumInputs<1>
{
typedef ComputationNodeNonLooping<ElemType> Base;
UsingComputationNodeMembersBoilerplate;
static const std::wstring TypeName()
{
return L"MatrixL1Reg";
}
public:
DeclareConstructorFromConfigWithNumInputs(MatrixL1RegNode);
MatrixL1RegNode(DEVICEID_TYPE deviceId, const wstring& name)
: Base(deviceId, name)
{
}
virtual void BackpropToNonLooping(size_t inputIndex) override // scale by number of cols (or samples)
{
FrameRange fr(Input(0)->GetMBLayout());
assert(inputIndex == 0);
inputIndex;
BackpropToS(*m_gradientOfL1Norm, Input(0)->GradientFor(fr), Gradient(), Input(0)->ValueFor(fr));
}
virtual bool OutputUsedInComputingInputNodesGradients() const override
{
return false;
}
/*TODO: merge with call site*/ void BackpropToS(Matrix<ElemType>& gradientOfL1Norm,
Matrix<ElemType> inputGradientValues, const Matrix<ElemType>& gradientValues, const Matrix<ElemType>& inputFunctionValues)
{
gradientOfL1Norm.AssignSignOf(inputFunctionValues);
Matrix<ElemType>::Multiply1x1AndWeightedAdd(+1.0f, gradientValues /*1x1*/, gradientOfL1Norm, 1.0f, inputGradientValues);
}
virtual void UpdateFunctionMBSize() override
{
m_gradientOfL1Norm->Resize(Input(0)->Value());
}
virtual void /*ComputationNodeNonLooping::*/ ForwardPropNonLooping() override
{
FrameRange fr(Input(0)->GetMBLayout());
Value().VerifySize(1, 1);
Value().SetValue(Input(0)->MaskedValueFor(fr).MatrixNorm1());
#if NANCHECK
Value().HasNan("MatrixL1Reg");
#endif
}
virtual void /*ComputationNodeBase::*/ Validate(bool isFinalValidationPass) override
{
ValidateUnaryReduce(isFinalValidationPass);
}
virtual void CopyTo(ComputationNodeBasePtr nodeP, const std::wstring& newName, const CopyNodeFlags flags) const override
{
Base::CopyTo(nodeP, newName, flags);
if (flags & CopyNodeFlags::copyNodeValue)
{
auto node = dynamic_pointer_cast<MatrixL1RegNode<ElemType>>(nodeP);
*node->m_gradientOfL1Norm = *m_gradientOfL1Norm;
}
}
// request matrices that are needed for gradient computation
virtual void RequestMatricesBeforeBackprop(MatrixPool& matrixPool)
{
Base::RequestMatricesBeforeBackprop(matrixPool);
RequestMatrixFromPool(m_gradientOfL1Norm, matrixPool);
}
// release gradient and temp matrices that no longer needed after all the children's gradients are computed.
virtual void ReleaseMatricesAfterBackprop(MatrixPool& matrixPool)
{
Base::ReleaseMatricesAfterBackprop(matrixPool);
ReleaseMatrixToPool(m_gradientOfL1Norm, matrixPool);
}
private:
shared_ptr<Matrix<ElemType>> m_gradientOfL1Norm; // temporary
};
template class MatrixL1RegNode<float>;
template class MatrixL1RegNode<double>;
// -----------------------------------------------------------------------
// MatrixL2RegNode (input)
// TODO: share most code with MatrixL1RegNode
// -----------------------------------------------------------------------
template <class ElemType>
class MatrixL2RegNode : public ComputationNodeNonLooping /*ComputationNode*/<ElemType>, public NumInputs<1>
{
typedef ComputationNodeNonLooping<ElemType> Base;
UsingComputationNodeMembersBoilerplate;
static const std::wstring TypeName()
{
return L"MatrixL2Reg";
}
public:
DeclareConstructorFromConfigWithNumInputs(MatrixL2RegNode);
MatrixL2RegNode(DEVICEID_TYPE deviceId, const wstring& name)
: Base(deviceId, name)
{
}
virtual void BackpropToNonLooping(size_t inputIndex) override // scale by number of cols (or samples)
{
FrameRange fr(Input(0)->GetMBLayout());
assert(inputIndex == 0);
inputIndex;
BackpropToS(Input(0)->GradientFor(fr), Gradient(), Input(0)->ValueFor(fr), Value());
}
/*TODO: merge with call site*/ void BackpropToS(Matrix<ElemType> inputGradientValues, const Matrix<ElemType>& gradientValues, const Matrix<ElemType>& inputFunctionValues, const Matrix<ElemType>& functionValues)
{
ElemType v = gradientValues.Get00Element() / (functionValues.Get00Element() + EPS_IN_INVERSE); // TODO: GPU inefficiency
inputGradientValues.AddWithScaleOf(v, inputFunctionValues);
}
virtual void /*ComputationNodeNonLooping::*/ ForwardPropNonLooping() override
{
FrameRange fr(Input(0)->GetMBLayout());
Value().VerifySize(1, 1);
Value().SetValue(Input(0)->MaskedValueFor(fr).FrobeniusNorm());
#if NANCHECK
Value().HasNan("MatrixL2Reg");
#endif
}
virtual void /*ComputationNodeBase::*/ Validate(bool isFinalValidationPass) override
{
ValidateUnaryReduce(isFinalValidationPass);
}
};
template class MatrixL2RegNode<float>;
template class MatrixL2RegNode<double>;
// -----------------------------------------------------------------------
// NoiseContrastiveEstimationNode (labels, input, inputWeights, biasWeights)
// -labels: label in dense matrix in [4 x T]
// the first row is the word index, the second row is the class index, the third row is the first word index of the class
// the last row is the first word index of the next class
// - input: hidden layer activity to the node in [hdsize x T]. for a simple rnn, this is the hidden layer activty
// - inputWeights: weight matrix in [hdsize x vocab_size], for speed-up, as per word matrix can be simply obtained as column slice
// - biasWeights: clsprob in dense matrix in [nbr_cls x T]. this is the output from logsoftmax node for the log-posterior probabilty of class given observations
// */
// BUGBUG: This node has not been converted to memshare conventions.
// -----------------------------------------------------------------------
enum NCEEvalMode
{
Softmax = 0,
Unnormalized = 1,
None = 2
};
template <class ElemType>
class NoiseContrastiveEstimationNode : public ComputationNodeNonLooping /*ComputationNode*/<ElemType>, public NumInputs<4>
{
typedef ComputationNodeNonLooping<ElemType> Base;
UsingComputationNodeMembersBoilerplate;
static const std::wstring TypeName()
{
return L"NCEBasedCrossEntropyWithSoftmax";
}
public:
DeclareConstructorFromConfigWithNumInputs(NoiseContrastiveEstimationNode);
NoiseContrastiveEstimationNode(DEVICEID_TYPE deviceId, const wstring& name)
: Base(deviceId, name),
m_logSoftmax(deviceId),
m_softMax(deviceId),
m_grdToSoftMaxInput(deviceId),
m_ncePrediction(deviceId),
m_evalMode(NCEEvalMode::None)
{
}
NoiseContrastiveEstimationNode(DEVICEID_TYPE deviceId, const wstring& name, NCEEvalMode xm_evalMode)
: Base(deviceId, name),
m_logSoftmax(deviceId),
m_softMax(deviceId),
m_grdToSoftMaxInput(deviceId),
m_ncePrediction(deviceId),
m_evalMode(xm_evalMode)
{
}
// ^^ TODO: we can merge these two
virtual void Save(File& fstream) const override
{
Base::Save(fstream);
fstream << m_evalMode;
}
virtual void Load(File& fstream, size_t modelVersion) override
{
Base::Load(fstream, modelVersion);
fstream >> m_evalMode;
if (m_evalMode > NCEEvalMode::None)
{
m_evalMode = NCEEvalMode::None;
fstream.SetPosition(fstream.GetPosition() - sizeof(m_evalMode));
}
}
void SetEvalMode(NCEEvalMode& xevMode)
{
m_evalMode = xevMode;
}
NCEEvalMode& EvalMode()
{
return m_evalMode;
} // TODO: really? Return a reference to a local? TODO: change to const? and call it GetEvalMode()
/**
compute gradients to input observations, the weights to the observations, and the class log posterior probabilities
*/
virtual void BackpropToNonLooping(size_t inputIndex) override
{
FrameRange fr(Input(0)->GetMBLayout());
m_needRecomputeGradientToSoftmaxInput = false;
// gradient computation@yinggongzhao
// inputIndex should be 2 this time
if (m_evalMode != NCEEvalMode::None)
LogicError("BackpropTo should only be called in training mode");
if (inputIndex == 0)
InvalidArgument("ComputeInput partial should not be called for label");
// samples+probs hidden embedding
// Input(inputIndex)->GradientFor(fr).AssignNCEDerivative(m_ncePrediction, Input(0)->ValueFor(fr), Input(1)->ValueFor(fr), Input(2)->Value(), inputIndex);
if (inputIndex >= 2)
Input(inputIndex)->Gradient().AssignNCEDerivative(m_ncePrediction, Input(0)->ValueFor(fr), Input(1)->ValueFor(fr), Input(2)->ValueAsMatrix(), inputIndex);
else
Input(inputIndex)->GradientFor(fr).AssignNCEDerivative(m_ncePrediction, Input(0)->ValueFor(fr), Input(1)->ValueFor(fr), Input(2)->ValueAsMatrix(), inputIndex);
}
virtual bool OutputUsedInComputingInputNodesGradients() const override
{
return false;
}
virtual void UpdateFunctionMBSize() override
{
// TODO (this does not really break it since for full matrices, class Matrix will resize by itself)
}
virtual void /*ComputationNodeNonLooping::*/ ForwardPropNonLooping() override // -sum(left_i * log(softmax_i(right)))
{
FrameRange fr(Input(0)->GetMBLayout());
if (Input(0)->HasMBLayout() && Input(0)->GetMBLayout()->HasGaps())
LogicError("%ls %ls operation does not handle multiple parallel sequences with gaps correctly. Contact [email protected] if you have a need and a test case.", NodeName().c_str(), OperationName().c_str());
int positive = 0, negative = 0;
if (Input(0)->GetSampleLayout().GetNumElements() == 1)
{
for (int i = 0; i < Input(0)->Value().GetNumCols(); i++) // BUGBUG: Loops must be over frames, not columns. Columns may contain gaps.
{
if (Input(0)->Value()(0, i) > 0)
positive++;
else if (Input(0)->Value()(0, i) < 0)
negative++;
}
assert(positive * negative == 0);
}
if (m_evalMode == NCEEvalMode::Softmax || (Input(0)->GetSampleLayout().GetNumElements() == 1 && positive > 0))
{
// evaluation uses softmax
m_logSoftmax.AssignProductOf(Input(1)->Value(), true, Input(2)->ValueAsMatrix(), false);
m_logSoftmax += Input(3)->Value();
m_logSoftmax.InplaceLogSoftmax(false);
MaskMissingColumnsToZero(m_logSoftmax, Input(1)->GetMBLayout(), fr); // TODO: is this the right way to neutralize gaps?
Value().AssignSoftmaxSum(Input(0)->Value(), m_logSoftmax);
}
else if (m_evalMode == NCEEvalMode::Unnormalized || (Input(0)->GetSampleLayout().GetNumElements() == 1 && negative > 0))
{
// TODO: are we treating gaps correctly here?
Value().AssignNceUnnormalizedEval(Input(0)->Value(), Input(1)->Value(), Input(2)->ValueAsMatrix(), Input(3)->Value());
}
else
{
// TODO: are we treating gaps correctly here?
// training criterion uses NCE
// likelihood samples+probs hidden embedding bias
Value().AssignNoiseContrastiveEstimation(Input(0)->Value(), Input(1)->Value(), Input(2)->ValueAsMatrix(), Input(3)->Value(), m_ncePrediction);
}
m_needRecomputeGradientToSoftmaxInput = true;
}
virtual void /*ComputationNodeBase::*/ Validate(bool isFinalValidationPass) override
{
Base::Validate(isFinalValidationPass);
m_pMBLayout = nullptr; // this node does not hold mini-batch data
if (isFinalValidationPass)
{
if (Input(1)->GetSampleMatrixNumRows() != Input(2)->GetAsMatrixNumRows())
LogicError("The Matrix dimension for observation and weight in the NoiseContrastiveEstimationNode operation does not match.");
if (!Input(0)->HasMBLayout() || !Input(1)->HasMBLayout() || Input(2)->HasMBLayout() || !Input(3)->HasMBLayout())
LogicError("%ls %ls operation requires inputs 0, 1, and 3 to be a minibatch, and input 2 to be a matrix.", NodeName().c_str(), OperationName().c_str());
}
SetDims(TensorShape(1), false);
}
protected:
Matrix<ElemType> m_logSoftmax;
Matrix<ElemType> m_softMax;
Matrix<ElemType> m_ncePrediction;
// gradient of cross entropy with respect to the input of softmax
// a 1 row by \sum_t m_nbrWordsInEachTime[t] vector
// one slice of size m_nbrWordsInEachTime[t] saves the input to softmax for word y_t
Matrix<ElemType> m_grdToSoftMaxInput;
bool m_needRecomputeGradientToSoftmaxInput;
size_t m_nbrNoise;
size_t m_totalNbrWords;
private:
NCEEvalMode m_evalMode;
};
template class NoiseContrastiveEstimationNode<float>;
template class NoiseContrastiveEstimationNode<double>;
// -----------------------------------------------------------------------
// ClassBasedCrossEntropyWithSoftmaxNode (labeldata(.,t), inputdata(.,t), embeddingMatrix, clsProbBeforeSoftmaxData(.,t))
// - Input(0) [4 x T] label in dense matrix in
// (0,t) the first row is the word index
// (1,t) the second row is the class index
// (2,t) the third row is the first word index of the class
// (3,t) the last row is the first word index of the next class
// - Input(1) [hdsize x T] hidden layer activation to the node in. for a simple rnn, this is the hidden layer activty
// - Input(2) [hdsize x vocab_size] weight matrix in, for speed-up, as per word matrix can be simply obtained as column slice
// - Input(3) [nbr_cls x T] clsprob in dense matrix in. This input, if applied softmax on, is the posterior probabilty of class given observations
// -----------------------------------------------------------------------
// calculates: -sum(left_i * log(softmax_i(right))) for class given history and for word given history
// need to provide class probabilty from external node
template <class ElemType>
class ClassBasedCrossEntropyWithSoftmaxNode : public ComputationNodeNonLooping /*ComputationNode*/<ElemType>, public NumInputs<4>
{
typedef ComputationNodeNonLooping<ElemType> Base;
UsingComputationNodeMembersBoilerplate;
static const std::wstring TypeName()
{
return L"ClassBasedCrossEntropyWithSoftmax";
}
// our inputs
static const size_t LABELDATA = 0;
static const size_t INPUTDATA = 1;
static const size_t EMBEDDINGMATRIX = 2;
static const size_t CLASSPROBINDATA = 3;
public:
DeclareConstructorFromConfigWithNumInputs(ClassBasedCrossEntropyWithSoftmaxNode);
ClassBasedCrossEntropyWithSoftmaxNode(DEVICEID_TYPE deviceId, const wstring& name)
: Base(deviceId, name),
m_logSoftmax(deviceId),
m_softMax(deviceId),
m_grdToSoftMaxInput(deviceId),
m_clsLogSoftmax(deviceId),
m_clsSoftmax(deviceId)
{
}
// compute gradients to input observations, the weights to the observations, and the class log posterior probabilites
virtual void BackpropToNonLooping(size_t inputIndex) override
{
// this should never be called for input[0], which is controlled through the needGradient flag
if (inputIndex != 1 && inputIndex != 2 && inputIndex != 3)
InvalidArgument("ClassCrossEntropyWithSoftmaxNode criterion only takes with respect to input, weight to the input and class log posterior probability.");
ComputeSoftMaxPartial();
Matrix<ElemType> grd_t;
Matrix<ElemType> grd_to_wgt_t;
const size_t nT = Input(LABELDATA)->GetNumTimeSteps();
const size_t nS = Input(LABELDATA)->GetNumParallelSequences();
size_t sz = 0; // iterate over the packed concatenated class-conditioned prob vectors
for (size_t s = 0; s < nS; s++)
for (size_t t = 0; t < nT; t++)
{
FrameRange fr = FrameRange(Input(LABELDATA)->GetMBLayout(), t).Sequence(s);
if (Input(LABELDATA)->GetMBLayout()->IsGap(fr)) // skip gaps
continue;
Matrix<ElemType> lbl_t = Input(LABELDATA)->ValueFor(fr);
size_t c_t = (size_t) lbl_t(1, 0);
size_t lft_bnd = (size_t) lbl_t(2, 0); // index of first word belonging to current word token's class
size_t rgt_bnd = (size_t) lbl_t(3, 0); // and end of that range
size_t nbr_wrd = (rgt_bnd - lft_bnd); // number of words in the class
// compute prb - 1 and prb
Matrix<ElemType> weightForClass = Input(EMBEDDINGMATRIX)->ValueAsMatrix().ColumnSlice(lft_bnd, nbr_wrd);
Matrix<ElemType> obs = Input(INPUTDATA)->ValueFor(fr); // hidden activation vector for current word token
Matrix<ElemType> grd_to_soft_max_input = m_grdToSoftMaxInput.ColumnSlice(sz, nbr_wrd);
Matrix<ElemType> grd_to_cls_prob = DataWithMBLayoutFor(m_clsLogSoftmax, fr, Input(CLASSPROBINDATA)->GetMBLayout());
switch (inputIndex)
{
case 1:
// gradient to input
grd_t = Input(INPUTDATA)->GradientFor(fr);
Matrix<ElemType>::MultiplyAndAdd(weightForClass, false, grd_to_soft_max_input, true, grd_t);
break;
case 2:
// gradient to input weight
grd_to_wgt_t = Input(EMBEDDINGMATRIX)->GradientAsMatrix().ColumnSlice(lft_bnd, nbr_wrd);
Matrix<ElemType>::MultiplyAndAdd(obs, false, grd_to_soft_max_input, false, grd_to_wgt_t);
break;
case 3:
grd_t = Input(CLASSPROBINDATA)->GradientFor(fr);
grd_t.SetValue(DataWithMBLayoutFor(m_clsSoftmax, fr, Input(CLASSPROBINDATA)->GetMBLayout()));
ComputeCEPartialToSoftmaxInputs(grd_t, Gradient(), c_t);
break;
}
sz += nbr_wrd;
}
}
virtual bool OutputUsedInComputingInputNodesGradients() const override
{
return false;
}
private:
void ComputeCEPartialToSoftmaxInputs(Matrix<ElemType>& inputGradientValues, Matrix<ElemType>& gradientValues, size_t y_t)
{
Matrix<ElemType>::MinusOneAt(inputGradientValues, y_t);
Matrix<ElemType>::Scale(gradientValues, inputGradientValues);
}
// gradient of cross entropy w.r.t. to input to softmax
void ComputeSoftMaxPartial()
{
if (m_needRecomputeGradientToSoftmaxInput)
{
m_grdToSoftMaxInput.Resize(1, m_totalNbrWords); // buffer that contains a concatenation of class-conditional values
const size_t nT = Input(LABELDATA)->GetNumTimeSteps();
const size_t nS = Input(LABELDATA)->GetNumParallelSequences();
size_t sz = 0; // iterate over the packed concatenated class-conditioned prob vectors
for (size_t s = 0; s < nS; s++)
for (size_t t = 0; t < nT; t++)
{
FrameRange fr = FrameRange(Input(LABELDATA)->GetMBLayout(), t).Sequence(s);
// if (Input(LABELDATA)->GetMBLayout()->IsGap(s, t)) // skip gaps
if (Input(LABELDATA)->GetMBLayout()->IsGap(fr)) // skip gaps
continue;
Matrix<ElemType> lbl_t = Input(LABELDATA)->ValueFor(fr);
size_t y_t = (size_t) lbl_t(0, 0); // word index
size_t lft_bnd = (size_t) lbl_t(2, 0); // index of first word belonging to current word token's class
size_t rgt_bnd = (size_t) lbl_t(3, 0); // and end of that range
size_t nbr_wrd = (rgt_bnd - lft_bnd); // number of words in the class
Matrix<ElemType> softMax = m_softMax.ColumnSlice(sz, nbr_wrd);
size_t idx_in_class = y_t - lft_bnd;
ComputeCEPartialToSoftmaxInputs(softMax, Gradient(), idx_in_class);
m_grdToSoftMaxInput.ColumnSlice(sz, nbr_wrd).SetValue(softMax);
sz += nbr_wrd;
}
m_needRecomputeGradientToSoftmaxInput = false;
}
}
public:
virtual void UpdateFunctionMBSize() override
{
// TODO: Resize temp matrices here (not doing so does not really fail since for full matrices, class Matrix will resize by itself)
}
// -sum(left_i * log(softmax_i(right)))
virtual void /*ComputationNodeNonLooping::*/ ForwardPropNonLooping() override
{
if (Input(LABELDATA)->Value().GetDeviceId() != CPUDEVICE)
LogicError("ClassBasedCrossEntropyWithSoftmax (ForwardPropNonLooping()): The label matrix is not using CPU device. This will make computation slow, even though the label data is probably saved on GPU. Because of the external loop over time with explicit class id retrieved from the label matrix, the computation will be very slow if the label matrix is saved on GPU. However, this is only a constraint for label matrix and other matrices such as data are suggested to reside on GPU. ");
// TODO: Get the label matrix into location=Both state.
auto& functionValues = Value();
const size_t hdSize = Input(INPUTDATA)->GetSampleMatrixNumRows(); // hdSize
assert(m_nbrCls == Input(CLASSPROBINDATA)->GetSampleMatrixNumRows());
// compute the class posteriors
m_clsLogSoftmax = Input(CLASSPROBINDATA)->Value();
m_clsLogSoftmax.InplaceLogSoftmax(true); // log
m_clsSoftmax.AssignExpOf(m_clsLogSoftmax); // non-log
// create a large workspace to contain all class-conditioned probs concatenated
// 'sz' is the offset into that vector. We will iterate over these vectors at a few places. Always use this same boilerplate code.
// TODO: should we pull this iteration into an iterator, to reduce the code dup?
const size_t nT = Input(LABELDATA)->GetNumTimeSteps();
const size_t nS = Input(LABELDATA)->GetNumParallelSequences();
size_t sz = 0;
for (size_t s = 0; s < nS; s++)
for (size_t t = 0; t < nT; t++)
{
FrameRange fr = FrameRange(Input(LABELDATA)->GetMBLayout(), t).Sequence(s);
if (Input(LABELDATA)->GetMBLayout()->IsGap(fr)) // skip gaps
continue;
const Matrix<ElemType>& lbl_t = Input(LABELDATA)->ValueFor(fr);
size_t lft_bnd = (size_t) lbl_t(2, 0);
size_t rgt_bnd = (size_t) lbl_t(3, 0);
size_t nbr_wrd = (rgt_bnd - lft_bnd); // number of words in the class
if (nbr_wrd == 0)
LogicError("ClassBasedCrossEntropyWithSoftmax (ForwardPropNonLooping()): Encountered a class of size 0. This sample seems to lack an NoInput flag.");
sz += nbr_wrd;
}
m_totalNbrWords = sz; // total size of concatenated vector
// buffer to hold the concatenated class-conditioned prob vectors
m_softMax.Resize(1, sz);
m_logSoftmax.Resize(1, sz);
// accumulate objective
functionValues.SetValue(0);
sz = 0; // iterate over the packed concatenated class-conditioned prob vectors
for (size_t s = 0; s < nS; s++)
for (size_t t = 0; t < nT; t++)
{
FrameRange fr = FrameRange(Input(LABELDATA)->GetMBLayout(), t).Sequence(s);
if (Input(LABELDATA)->GetMBLayout()->IsGap(fr)) // skip gaps
continue;
const Matrix<ElemType>& lbl_t = Input(LABELDATA)->ValueFor(fr);
size_t y_t = (size_t) lbl_t(0, 0); // current word token index
size_t c_t = (size_t) lbl_t(1, 0); // current word token's class index
size_t lft_bnd = (size_t) lbl_t(2, 0); // index of first word belonging to current word token's class
size_t rgt_bnd = (size_t) lbl_t(3, 0); // and end of that range
size_t nbr_wrd = (rgt_bnd - lft_bnd); // number of words in the class
// now get views of various arrays that correspond to the index range of words belonging to this class
// get hidden vectors for the words in this class
Matrix<ElemType> weightForClass = Input(EMBEDDINGMATRIX)->ValueAsMatrix().ColumnSlice(lft_bnd, nbr_wrd); // [hdSize x nbr_wrd]
// buffer to hold the class-conditional distribution
Matrix<ElemType> softMax_t = m_softMax.ColumnSlice(sz, nbr_wrd); // TODO: declare these outside of the loop to avoid the malloc
Matrix<ElemType> logSoftMax_t = m_logSoftmax.ColumnSlice(sz, nbr_wrd);
Matrix<ElemType> obs = Input(INPUTDATA)->ValueFor(fr); // hidden activation vector for current word token
// multiply hidden activation with weight matrix (the slice of the weight matrix for the range of class members)
// TODO: can we use 'true' here instead? Above transposition hack won't work with row slices. 'obs' not used elsewhere
obs.Reshape(1, hdSize); // transpose it (make it a column vector)
logSoftMax_t.AssignProductOf(obs /*(1 x hdSize)*/, false, weightForClass /*hdSize x nbr_wrd*/, false); // -> 1 x nbr_word
// log softmax(W x_t)
logSoftMax_t.InplaceLogSoftmax(false);
// and non-log version
softMax_t.SetValue(logSoftMax_t);
softMax_t.InplaceExp();
// we now have a column vector of class-conditional probabilities over the class members
// add the word's class-conditional log posterior
if (y_t < lft_bnd || y_t >= rgt_bnd)
LogicError("ClassBasedCrossEntropyWithSoftmax (ForwardPropNonLooping()): Word index out of bounds of class-member index range (word not a class member).");
size_t idx_in_class = y_t - lft_bnd;
Matrix<ElemType>::AddElementToElement(logSoftMax_t, 0, idx_in_class, functionValues, 0, 0); // (1x1)
// add the class log posterior probability
Matrix<ElemType>::AddElementToElement(m_clsLogSoftmax, c_t, t, functionValues, 0, 0); // (1x1)
sz += nbr_wrd;
}
functionValues *= (-1);
#if NANCHECK
functionValues.HasNan("ClassBasedCrossEntropyWithSoftmax");
#endif
m_needRecomputeGradientToSoftmaxInput = true;
}
virtual void /*ComputationNodeBase::*/ Validate(bool isFinalValidationPass) override
{
Base::Validate(isFinalValidationPass);
m_pMBLayout = nullptr; // this node does not hold mini-batch data
if (isFinalValidationPass)
{
if (Input(LABELDATA)->GetSampleMatrixNumRows() != 4) // label data needs to have 4 rows
LogicError("The label data in the ClassBasedCrossEntropyWithSoftmax operation must have 4 rows.");
if (Input(INPUTDATA)->GetSampleMatrixNumRows() != Input(EMBEDDINGMATRIX)->GetAsMatrixNumRows()) // input and matrix can be timed
LogicError("The matrix dimension for observation and weight in the ClassBasedCrossEntropyWithSoftmax operation does not match.");
if (Input(LABELDATA)->GetMBLayout() != Input(INPUTDATA)->GetMBLayout() || Input(LABELDATA)->GetMBLayout() != Input(CLASSPROBINDATA)->GetMBLayout())
InvalidArgument("%ls %ls operation requires that the layouts of inputs 0 (label), 1 (hidden activation), and 3 (log softmax) match.", NodeName().c_str(), OperationName().c_str());
}
SetDims(TensorShape(1), false);
m_nbrCls = Input(CLASSPROBINDATA)->GetSampleMatrixNumRows();
}
protected:
Matrix<ElemType> m_logSoftmax;
Matrix<ElemType> m_softMax;
Matrix<ElemType> m_clsLogSoftmax;
Matrix<ElemType> m_clsSoftmax;
// gradient of cross entropy with respect to the input of softmax
// a 1 row by \sum_t m_nbrWordsInEachTime[t] vector
// one slice of size m_nbrWordsInEachTime[t] saves the input to softmax for word y_t
Matrix<ElemType> m_grdToSoftMaxInput;
bool m_needRecomputeGradientToSoftmaxInput;
size_t m_nbrCls;
size_t m_totalNbrWords;
};
template class ClassBasedCrossEntropyWithSoftmaxNode<float>;
template class ClassBasedCrossEntropyWithSoftmaxNode<double>;