-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLoss.cs
More file actions
486 lines (418 loc) · 13.1 KB
/
Copy pathLoss.cs
File metadata and controls
486 lines (418 loc) · 13.1 KB
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Wintellect.PowerCollections;
using Predictions = System.Collections.Generic.List<System.Tuple<float, int>>;
namespace FastText
{
public abstract class Loss
{
private const long LOG_TABLE_SIZE = 512;
private const long MAX_SIGMOID = 8;
private const long SIGMOID_TABLE_SIZE = 512;
protected List<float> t_sigmoid_;
protected List<float> t_log_;
protected Matrix wo_;
protected float Log(float x)
{
if (x > 1.0)
{
return 0f;
}
var i = (int)(x * LOG_TABLE_SIZE);
return t_log_[i];
}
protected float Sigmoid(float x)
{
if (x < -MAX_SIGMOID)
{
return 0f;
}
else if (x > MAX_SIGMOID)
{
return 1f;
}
else
{
var i =
(int)((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2);
return t_sigmoid_[i];
}
}
protected float StdLog(float x)
{
return (float)Math.Log(x + 1E-5);
}
private void FindKBest(
int k,
float threshold,
Predictions predictions,
float[] output)
{
var heap = new OrderedBag<Tuple<float, int>>(
predictions,
new Comparison<Tuple<float, int>>((l, r) =>
{
var b = l.Item1 > r.Item1;
return b ? 1 : 0;
}));
for (int i = 0; i < output.Length; i++)
{
if (output[i] < threshold)
{
continue;
}
if (heap.Count == k && StdLog(output[i]) < heap.First().Item1)
{
continue;
}
heap.Add(Tuple.Create(StdLog(output[i]), i));
if (heap.Count > k)
{
heap.RemoveFirst();
}
}
}
public Loss(Matrix wo)
{
wo_ = wo;
t_sigmoid_ = new List<float>((int)SIGMOID_TABLE_SIZE + 1);
for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++)
{
var x = (float)(i * 2 * MAX_SIGMOID) / SIGMOID_TABLE_SIZE - MAX_SIGMOID;
t_sigmoid_.Add(1f / (1f + (float)Math.Exp(-x)));
}
t_log_ = new List<float>((int)LOG_TABLE_SIZE + 1);
for (int i = 0; i < LOG_TABLE_SIZE + 1; i++)
{
var x = (i + 1E-5f) / LOG_TABLE_SIZE;
t_log_.Add((float)Math.Log(x));
}
}
public virtual void Predict(
int k,
float threshold,
Predictions heap,
Model.State state)
{
ComputeOutput(state);
FindKBest(k, threshold, heap, state.output.Data);
}
public abstract float Forward(
int[] targets,
int targetIndex,
Model.State state,
float lr,
bool backprop);
public abstract void ComputeOutput(Model.State state);
}
public abstract class BinaryLogisticLoss : Loss
{
public BinaryLogisticLoss(Matrix wo) : base(wo)
{
}
public float BinaryLogistic(
int target,
Model.State state,
bool labelIsPositive,
float lr,
bool backprop)
{
var score = Sigmoid(wo_.DotRow(state.hidden.Data, target));
if (backprop)
{
var flabelIsPositive = (float)Convert.ToDouble(labelIsPositive);
var alpha = lr * (flabelIsPositive - score);
state.grad.AddRow(wo_, target, alpha);
wo_.AddVectorToRow(state.hidden.Data, target, alpha);
}
if (labelIsPositive)
{
return -Log(score);
}
else
{
return -Log(1f - score);
}
}
public override void ComputeOutput(Model.State state)
{
Vector output = state.output;
output.Mul(wo_, state.hidden);
var osz = output.Size();
for (int i = 0; i < osz; i++)
{
output[i] = Sigmoid(output[i]);
}
}
}
public class OneVsAllLoss : BinaryLogisticLoss
{
public OneVsAllLoss(Matrix wo) : base(wo)
{
}
public override float Forward(
int[] targets,
int targetIndex,
Model.State state,
float lr,
bool backprop)
{
var loss = 0f;
var osz = state.output.Size();
for (int i = 0; i < osz; i++)
{
bool isMatch = Utils.Contains(targets, i);
loss += BinaryLogistic(i, state, isMatch, lr, backprop);
}
return loss;
}
}
public class NegativeSamplingLoss : BinaryLogisticLoss
{
protected const int NEGATIVE_TABLE_SIZE = 10000000;
protected int neg_;
protected List<int> negatives_;
protected int getNegative(int target, Random rng)
{
int negative;
do
{
var uniform = rng.Next(0, negatives_.Count);
negative = negatives_[uniform];
} while (target == negative);
return negative;
}
public NegativeSamplingLoss(
Matrix wo,
int neg,
long[] targetCounts) : base(wo)
{
neg_ = neg;
negatives_ = new List<int>();
var z = 0f;
for (int i = 0; i < targetCounts.Length; i++)
{
z += (float)Math.Pow(targetCounts[i], 0.5);
}
for (int i = 0; i < targetCounts.Length; i++)
{
var c = (float)Math.Pow(targetCounts[i], 0.5);
for (int j = 0; j < c * NEGATIVE_TABLE_SIZE / z;
j++)
{
negatives_.Add(i);
}
}
}
public override float Forward(
int[] targets,
int targetIndex,
Model.State state,
float lr,
bool backprop)
{
Debug.Assert(targetIndex >= 0);
Debug.Assert(targetIndex < targets.Length);
var target = targets[targetIndex];
var loss = BinaryLogistic(target, state, true, lr, backprop);
for (int n = 0; n < neg_; n++)
{
var negativeTarget = getNegative(target, state.rng);
loss += BinaryLogistic(negativeTarget, state, false, lr, backprop);
}
return loss;
}
}
public class HierarchicalSoftmaxLoss : BinaryLogisticLoss
{
protected class Node
{
public int parent;
public int left;
public int right;
public long count;
public bool binary;
}
protected List<int[]> paths_;
protected List<bool[]> codes_;
protected List<Node> tree_;
protected int osz_;
protected void BuildTree(long[] counts)
{
tree_.Capacity = 2 * osz_ - 1;
for (int i = 0; i < 2 * osz_ - 1; i++)
{
tree_[i].parent = -1;
tree_[i].left = -1;
tree_[i].right = -1;
tree_[i].count = (long)1e15;
tree_[i].binary = false;
}
for (int i = 0; i < osz_; i++)
{
tree_[i].count = counts[i];
}
var leaf = osz_ - 1;
var node = osz_;
for (int i = osz_; i < 2 * osz_ - 1; i++)
{
var mini = new int[2];
for (int j = 0; j < 2; j++)
{
if (leaf >= 0 && tree_[leaf].count < tree_[node].count)
{
mini[j] = leaf--;
}
else
{
mini[j] = node++;
}
}
tree_[i].left = mini[0];
tree_[i].right = mini[1];
tree_[i].count = tree_[mini[0]].count + tree_[mini[1]].count;
tree_[mini[0]].parent = i;
tree_[mini[1]].parent = i;
tree_[mini[1]].binary = true;
}
for (int i = 0; i < osz_; i++)
{
List<int> path = new List<int>();
List<bool> code = new List<bool>();
var j = i;
while (tree_[j].parent != -1)
{
path.Add(tree_[j].parent - osz_);
code.Add(tree_[j].binary);
j = tree_[j].parent;
}
paths_.Add(path.ToArray());
codes_.Add(code.ToArray());
}
}
protected void DFS(
int k,
float threshold,
int node,
float score,
Predictions predictions,
float[] hidden)
{
var heap = new OrderedBag<Tuple<float, int>>(
predictions,
new Comparison<Tuple<float, int>>((l, r) =>
{
var b = l.Item1 > r.Item1;
return b ? 1 : 0;
}));
if (score < StdLog(threshold))
{
return;
}
if (heap.Count == k && score < heap.GetFirst().Item1)
{
return;
}
if (tree_[node].left == -1 && tree_[node].right == -1)
{
heap.Add(Tuple.Create(score, node));
if (heap.Count > k)
{
heap.RemoveFirst();
}
return;
}
var f = wo_.DotRow(hidden, node - osz_);
f = 1f / (1 + (float)Math.Exp(-f));
predictions = heap.ToList();
DFS(k, threshold, tree_[node].left, score + StdLog(1f - f), predictions, hidden);
DFS(k, threshold, tree_[node].right, score + StdLog(f), predictions, hidden);
}
public HierarchicalSoftmaxLoss(Matrix wo, long[] targetCounts) : base(wo)
{
paths_ = new List<int[]>();
codes_ = new List<bool[]>();
tree_ = new List<Node>();
osz_ = targetCounts.Length;
BuildTree(targetCounts);
}
public override float Forward(
int[] targets,
int targetIndex,
Model.State state,
float lr,
bool backprop)
{
var loss = 0f;
var target = targets[targetIndex];
var binaryCode = codes_[target];
var pathToRoot = paths_[target];
for (int i = 0; i < pathToRoot.Length; i++)
{
loss += BinaryLogistic(pathToRoot[i], state, binaryCode[i], lr, backprop);
}
return loss;
}
public override void Predict(
int k,
float threshold,
Predictions heap,
Model.State state)
{
DFS(k, threshold, 2 * osz_ - 2, 0f, heap, state.hidden.Data);
}
}
public class SoftmaxLoss : Loss
{
public SoftmaxLoss(Matrix wo) : base(wo)
{
}
public override void ComputeOutput(Model.State state)
{
Vector output = state.output;
output.Mul(wo_, state.hidden);
var max = output[0];
var z = 0f;
var osz = output.Size();
for (int i = 0; i < osz; i++)
{
max = Math.Max(output[i], max);
}
for (int i = 0; i < osz; i++)
{
output[i] = (float)Math.Exp(output[i] - max);
z += output[i];
}
for (int i = 0; i < osz; i++)
{
output[i] /= z;
}
}
public override float Forward(
int[] targets,
int targetIndex,
Model.State state,
float lr,
bool backprop)
{
Debug.Assert(targetIndex >= 0);
Debug.Assert(targetIndex < targets.Length);
ComputeOutput(state);
var target = targets[targetIndex];
if (backprop)
{
var osz = wo_.Size(0);
for (int i = 0; i < osz; i++)
{
var label = (i == target) ? 1f : 0f;
var alpha = lr * (label - state.output[i]);
state.grad.AddRow(wo_, i, alpha);
wo_.AddVectorToRow(state.hidden.Data, i, alpha);
}
}
return -Log(state.output[target]);
}
}
}