/
memory_tree.cc
1309 lines (1169 loc) · 39.9 KB
/
memory_tree.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
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <float.h>
#include <time.h>
#include <sstream>
#include <ctime>
#include "reductions.h"
#include "rand48.h"
#include "vw.h"
#include "v_array.h"
using namespace std;
using namespace LEARNER;
using namespace VW::config;
namespace memory_tree_ns
{
///////////////////////Helper//////////////////////////////
//////////////////////////////////////////////////////////
template <typename T>
void remove_at_index(v_array<T>& array, uint32_t index)
{
if (index >= array.size())
{
cout << "ERROR: index is larger than the size" << endl;
return;
}
if (index == array.size() - 1)
{
array.pop();
return;
}
for (size_t i = index + 1; i < array.size(); i++)
{
array[i - 1] = array[i];
}
array.pop();
return;
}
void copy_example_data(example* dst, example* src, bool oas = false) // copy example data.
{
if (oas == false)
{
dst->l = src->l;
dst->l.multi.label = src->l.multi.label;
}
else
{
dst->l.multilabels.label_v.delete_v();
copy_array(dst->l.multilabels.label_v, src->l.multilabels.label_v);
}
VW::copy_example_data(false, dst, src);
}
inline void free_example(example* ec)
{
VW::dealloc_example(nullptr, *ec);
free(ec);
}
////Implement kronecker_product between two examples:
// kronecker_prod at feature level:
void diag_kronecker_prod_fs_test(
features& f1, features& f2, features& prod_f, float& total_sum_feat_sq, float norm_sq1, float norm_sq2)
{
prod_f.delete_v();
if (f2.indicies.size() == 0)
return;
float denominator = pow(norm_sq1 * norm_sq2, 0.5f);
size_t idx1 = 0;
size_t idx2 = 0;
while (idx1 < f1.size() && idx2 < f2.size())
{
uint64_t ec1pos = f1.indicies[idx1];
uint64_t ec2pos = f2.indicies[idx2];
if (ec1pos < ec2pos)
idx1++;
else if (ec1pos > ec2pos)
idx2++;
else
{
prod_f.push_back(f1.values[idx1] * f2.values[idx2] / denominator, ec1pos);
total_sum_feat_sq += f1.values[idx1] * f2.values[idx2] / denominator; // make this out of loop
idx1++;
idx2++;
}
}
}
int cmpfunc(const void* a, const void* b) { return *(char*)a - *(char*)b; }
void diag_kronecker_product_test(example& ec1, example& ec2, example& ec, bool oas = false)
{
// copy_example_data(&ec, &ec1, oas); //no_feat false, oas: true
VW::dealloc_example(nullptr, ec, nullptr); // clear ec
copy_example_data(&ec, &ec1, oas);
ec.total_sum_feat_sq = 0.0; // sort namespaces. pass indices array into sort...template (leave this to the end)
qsort(ec1.indices.begin(), ec1.indices.size(), sizeof(namespace_index), cmpfunc);
qsort(ec2.indices.begin(), ec2.indices.size(), sizeof(namespace_index), cmpfunc);
size_t idx1 = 0;
size_t idx2 = 0;
while (idx1 < ec1.indices.size() && idx2 < ec2.indices.size())
// for (size_t idx1 = 0, idx2 = 0; idx1 < ec1.indices.size() && idx2 < ec2.indices.size(); idx1++)
{
namespace_index c1 = ec1.indices[idx1];
namespace_index c2 = ec2.indices[idx2];
if (c1 < c2)
idx1++;
else if (c1 > c2)
idx2++;
else
{
diag_kronecker_prod_fs_test(ec1.feature_space[c1], ec2.feature_space[c2], ec.feature_space[c1],
ec.total_sum_feat_sq, ec1.total_sum_feat_sq, ec2.total_sum_feat_sq);
idx1++;
idx2++;
}
}
}
////////////////////////////end of helper/////////////////////////
//////////////////////////////////////////////////////////////////
////////////////////////Implementation of memory_tree///////////////////
///////////////////////////////////////////////////////////////////////
// construct node for tree.
struct node
{
uint64_t parent; // parent index
int internal;
// bool internal; //an internal or leaf
uint32_t depth; // depth.
uint64_t base_router; // use to index router.
uint64_t left; // left child.
uint64_t right; // right child.
double nl; // number of examples routed to left.
double nr; // number of examples routed to right.
v_array<uint32_t> examples_index;
node() // construct:
{
parent = 0;
internal = 0; // 0:not used, 1:internal, -1:leaf
// internal = false;
depth = 0;
base_router = 0;
left = 0;
right = 0;
nl = 0.001; // initilze to 1, as we need to do nl/nr.
nr = 0.001;
examples_index = v_init<uint32_t>();
}
};
// memory_tree
struct memory_tree
{
vw* all;
v_array<node> nodes; // array of nodes.
v_array<example*> examples; // array of example points
size_t max_leaf_examples;
size_t max_nodes;
size_t leaf_example_multiplier;
size_t max_routers;
size_t max_num_labels;
float alpha; // for cpt type of update.
uint64_t routers_used;
int iter;
uint32_t dream_repeats; // number of dream operations per example.
uint32_t total_num_queries;
size_t max_depth;
size_t max_ex_in_leaf;
float construct_time; // recording the time for constructing the memory tree
float test_time; // recording the test time
uint32_t num_mistakes;
bool learn_at_leaf; // indicator for turning on learning the scorer function at the leaf level
bool test_mode;
size_t current_pass; // for tracking # of passes over the dataset
size_t final_pass;
int top_K; // commands:
bool oas; // indicator for multi-label classification (oas = 1)
int dream_at_update;
bool online; // indicator for running CMT in online fashion
float F1_score;
float hamming_loss;
example* kprod_ec;
memory_tree()
{
nodes = v_init<node>();
examples = v_init<example*>();
alpha = 0.5;
routers_used = 0;
iter = 0;
num_mistakes = 0;
test_mode = false;
max_depth = 0;
max_ex_in_leaf = 0;
construct_time = 0;
test_time = 0;
top_K = 1;
}
};
float linear_kernel(const flat_example* fec1, const flat_example* fec2)
{
float dotprod = 0;
features& fs_1 = (features&)fec1->fs;
features& fs_2 = (features&)fec2->fs;
if (fs_2.indicies.size() == 0)
return 0.f;
for (size_t idx1 = 0, idx2 = 0; idx1 < fs_1.size() && idx2 < fs_2.size(); idx1++)
{
uint64_t ec1pos = fs_1.indicies[idx1];
uint64_t ec2pos = fs_2.indicies[idx2];
if (ec1pos < ec2pos)
continue;
while (ec1pos > ec2pos && ++idx2 < fs_2.size()) ec2pos = fs_2.indicies[idx2];
if (ec1pos == ec2pos)
{
dotprod += fs_1.values[idx1] * fs_2.values[idx2];
++idx2;
}
}
return dotprod;
}
float normalized_linear_prod(memory_tree& b, example* ec1, example* ec2)
{
flat_example* fec1 = flatten_sort_example(*b.all, ec1);
flat_example* fec2 = flatten_sort_example(*b.all, ec2);
float norm_sqrt = pow(fec1->total_sum_feat_sq * fec2->total_sum_feat_sq, 0.5f);
float linear_prod = linear_kernel(fec1, fec2);
// fec1->fs.delete_v();
// fec2->fs.delete_v();
free_flatten_example(fec1);
free_flatten_example(fec2);
return linear_prod / norm_sqrt;
}
void init_tree(memory_tree& b)
{
// srand48(4000);
// simple initilization: initilize the root only
b.iter = 0;
b.num_mistakes = 0;
b.routers_used = 0;
b.test_mode = false;
b.max_depth = 0;
b.max_ex_in_leaf = 0;
b.construct_time = 0;
b.test_time = 0;
b.top_K = 1;
b.hamming_loss = 0.f;
b.F1_score = 0.f;
b.nodes.push_back(node());
b.nodes[0].internal = -1; // mark the root as leaf
b.nodes[0].base_router = (b.routers_used++);
b.kprod_ec = &calloc_or_throw<example>(); // allocate space for kronecker product example
b.total_num_queries = 0;
b.max_routers = b.max_nodes;
cout << "tree initiazliation is done...." << endl
<< "max nodes " << b.max_nodes << endl
<< "tree size: " << b.nodes.size() << endl
<< "max number of unique labels: " << b.max_num_labels << endl
<< "learn at leaf: " << b.learn_at_leaf << endl
<< "num of dream operations per example: " << b.dream_repeats << endl
<< "current_pass: " << b.current_pass << endl
<< "oas: " << b.oas << endl;
}
// rout based on the prediction
inline uint64_t insert_descent(node& n, const float prediction)
{
// prediction <0 go left, otherwise go right
if (prediction < 0)
{
n.nl++; // increment the number of examples routed to the left.
return n.left;
}
else
{ // otherwise go right.
n.nr++; // increment the number of examples routed to the right.
return n.right;
}
}
// return the id of the example and the leaf id (stored in cn)
inline int random_sample_example_pop(memory_tree& b, uint64_t& cn)
{
cn = 0; // always start from the root:
while (b.nodes[cn].internal == 1)
{
float pred = 0.; // deal with some edge cases:
if (b.nodes[cn].nl < 1) // no examples routed to left ever:
pred = 1.f; // go right.
else if (b.nodes[cn].nr < 1) // no examples routed to right ever:
pred = -1.f; // go left.
else if ((b.nodes[cn].nl >= 1) && (b.nodes[cn].nr >= 1))
pred = merand48(b.all->random_state) < (b.nodes[cn].nl * 1. / (b.nodes[cn].nr + b.nodes[cn].nl)) ? -1.f : 1.f;
else
{
cout << cn << " " << b.nodes[cn].nl << " " << b.nodes[cn].nr << endl;
cout << "Error: nl = 0, and nr = 0, exit...";
exit(0);
}
if (pred < 0)
{
b.nodes[cn].nl--;
cn = b.nodes[cn].left;
}
else
{
b.nodes[cn].nr--;
cn = b.nodes[cn].right;
}
}
if (b.nodes[cn].examples_index.size() >= 1)
{
int loc_at_leaf = int(merand48(b.all->random_state) * b.nodes[cn].examples_index.size());
uint32_t ec_id = b.nodes[cn].examples_index[loc_at_leaf];
remove_at_index(b.nodes[cn].examples_index, loc_at_leaf);
return ec_id;
}
else
return -1;
}
// train the node with id cn, using the statistics stored in the node to
// formulate a binary classificaiton example.
float train_node(memory_tree& b, single_learner& base, example& ec, const uint64_t cn)
{
// predict, learn and predict
// note: here we first train the router and then predict.
MULTICLASS::label_t mc;
uint32_t save_multi_pred = 0;
MULTILABEL::labels multilabels;
MULTILABEL::labels preds;
if (b.oas == false)
{
mc = ec.l.multi;
save_multi_pred = ec.pred.multiclass;
}
else
{
multilabels = ec.l.multilabels;
preds = ec.pred.multilabels;
}
ec.l.simple = {1.f, 1.f, 0.};
base.predict(ec, b.nodes[cn].base_router);
float prediction = ec.pred.scalar;
// float imp_weight = 1.f; //no importance weight.
float weighted_value =
(float)((1. - b.alpha) * log(b.nodes[cn].nl / (b.nodes[cn].nr + 1e-1)) / log(2.) + b.alpha * prediction);
float route_label = weighted_value < 0.f ? -1.f : 1.f;
// ec.l.simple = {route_label, imp_weight, 0.f};
float ec_input_weight = ec.weight;
ec.weight = 1.f;
ec.l.simple = {route_label, 1., 0.f};
base.learn(ec, b.nodes[cn].base_router); // update the router according to the new example.
base.predict(ec, b.nodes[cn].base_router);
float save_binary_scalar = ec.pred.scalar;
if (b.oas == false)
{
ec.l.multi = mc;
ec.pred.multiclass = save_multi_pred;
}
else
{
ec.pred.multilabels = preds;
ec.l.multilabels = multilabels;
}
ec.weight = ec_input_weight;
return save_binary_scalar;
}
// turn a leaf into an internal node, and create two children
// when the number of examples is too big
void split_leaf(memory_tree& b, single_learner& base, const uint64_t cn)
{
// create two children
b.nodes[cn].internal = 1; // swith to internal node.
uint32_t left_child = (uint32_t)b.nodes.size();
b.nodes.push_back(node());
b.nodes[left_child].internal = -1; // left leaf
b.nodes[left_child].base_router = (b.routers_used++);
uint32_t right_child = (uint32_t)b.nodes.size();
b.nodes.push_back(node());
b.nodes[right_child].internal = -1; // right leaf
b.nodes[right_child].base_router = (b.routers_used++);
if (b.nodes[cn].depth + 1 > b.max_depth)
{
b.max_depth = b.nodes[cn].depth + 1;
cout << "depth " << b.max_depth << endl;
}
b.nodes[cn].left = left_child;
b.nodes[cn].right = right_child;
b.nodes[left_child].parent = cn;
b.nodes[right_child].parent = cn;
b.nodes[left_child].depth = b.nodes[cn].depth + 1;
b.nodes[right_child].depth = b.nodes[cn].depth + 1;
if (b.nodes[left_child].depth > b.max_depth)
b.max_depth = b.nodes[left_child].depth;
// rout the examples stored in the node to the left and right
for (size_t ec_id = 0; ec_id < b.nodes[cn].examples_index.size(); ec_id++) // scan all examples stored in the cn
{
uint32_t ec_pos = b.nodes[cn].examples_index[ec_id];
MULTICLASS::label_t mc;
uint32_t save_multi_pred = 0;
MULTILABEL::labels multilabels;
MULTILABEL::labels preds;
if (b.oas == false)
{
mc = b.examples[ec_pos]->l.multi;
save_multi_pred = b.examples[ec_pos]->pred.multiclass;
}
else
{
multilabels = b.examples[ec_pos]->l.multilabels;
preds = b.examples[ec_pos]->pred.multilabels;
}
b.examples[ec_pos]->l.simple = {1.f, 1.f, 0.f};
base.predict(*b.examples[ec_pos], b.nodes[cn].base_router); // re-predict
float scalar = b.examples[ec_pos]->pred.scalar; // this is spliting the leaf.
if (scalar < 0)
{
b.nodes[left_child].examples_index.push_back(ec_pos);
float leaf_pred = train_node(b, base, *b.examples[ec_pos], left_child);
insert_descent(b.nodes[left_child], leaf_pred); // fake descent, only for update nl and nr
}
else
{
b.nodes[right_child].examples_index.push_back(ec_pos);
float leaf_pred = train_node(b, base, *b.examples[ec_pos], right_child);
insert_descent(b.nodes[right_child], leaf_pred); // fake descent. for update nr and nl
}
if (b.oas == false)
{
b.examples[ec_pos]->l.multi = mc;
b.examples[ec_pos]->pred.multiclass = save_multi_pred;
}
else
{
b.examples[ec_pos]->pred.multilabels = preds;
b.examples[ec_pos]->l.multilabels = multilabels;
}
}
b.nodes[cn].examples_index.delete_v(); // empty the cn's example list
b.nodes[cn].nl = (std::max)(double(b.nodes[left_child].examples_index.size()), 0.001); // avoid to set nl to zero
b.nodes[cn].nr = (std::max)(double(b.nodes[right_child].examples_index.size()), 0.001); // avoid to set nr to zero
if ((std::max)(b.nodes[cn].nl, b.nodes[cn].nr) > b.max_ex_in_leaf)
{
b.max_ex_in_leaf = (size_t)(std::max)(b.nodes[cn].nl, b.nodes[cn].nr);
// cout<<b.max_ex_in_leaf<<endl;
}
}
int compare_label(const void* a, const void* b) { return *(uint32_t*)a - *(uint32_t*)b; }
inline uint32_t over_lap(v_array<uint32_t>& array_1, v_array<uint32_t>& array_2)
{
uint32_t num_overlap = 0;
qsort(array_1.begin(), array_1.size(), sizeof(uint32_t), compare_label);
qsort(array_2.begin(), array_2.size(), sizeof(uint32_t), compare_label);
uint32_t idx1 = 0;
uint32_t idx2 = 0;
while (idx1 < array_1.size() && idx2 < array_2.size())
{
uint32_t c1 = array_1[idx1];
uint32_t c2 = array_2[idx2];
if (c1 < c2)
idx1++;
else if (c1 > c2)
idx2++;
else
{
num_overlap++;
idx1++;
idx2++;
}
}
return num_overlap;
}
// template<typename T>
inline uint32_t hamming_loss(v_array<uint32_t>& array_1, v_array<uint32_t>& array_2)
{
uint32_t overlap = over_lap(array_1, array_2);
return (uint32_t)(array_1.size() + array_2.size() - 2 * overlap);
}
void collect_labels_from_leaf(memory_tree& b, const uint64_t cn, v_array<uint32_t>& leaf_labs)
{
if (b.nodes[cn].internal != -1)
cout << "something is wrong, it should be a leaf node" << endl;
leaf_labs.clear();
for (size_t i = 0; i < b.nodes[cn].examples_index.size(); i++)
{ // scan through each memory in the leaf
uint32_t loc = b.nodes[cn].examples_index[i];
for (uint32_t lab : b.examples[loc]->l.multilabels.label_v)
{ // scan through each label:
if (v_array_contains(leaf_labs, lab) == false)
leaf_labs.push_back(lab);
}
}
}
inline void train_one_against_some_at_leaf(memory_tree& b, single_learner& base, const uint64_t cn, example& ec)
{
v_array<uint32_t> leaf_labs = v_init<uint32_t>();
collect_labels_from_leaf(b, cn, leaf_labs); // unique labels from the leaf.
MULTILABEL::labels multilabels = ec.l.multilabels;
MULTILABEL::labels preds = ec.pred.multilabels;
ec.l.simple = {FLT_MAX, 1.f, 0.f};
for (size_t i = 0; i < leaf_labs.size(); i++)
{
ec.l.simple.label = -1.f;
if (v_array_contains(multilabels.label_v, leaf_labs[i]))
ec.l.simple.label = 1.f;
base.learn(ec, b.max_routers + 1 + leaf_labs[i]);
}
ec.pred.multilabels = preds;
ec.l.multilabels = multilabels;
}
inline uint32_t compute_hamming_loss_via_oas(
memory_tree& b, single_learner& base, const uint64_t cn, example& ec, v_array<uint32_t>& selected_labs)
{
selected_labs.delete_v();
v_array<uint32_t> leaf_labs = v_init<uint32_t>();
collect_labels_from_leaf(b, cn, leaf_labs); // unique labels stored in the leaf.
MULTILABEL::labels multilabels = ec.l.multilabels;
MULTILABEL::labels preds = ec.pred.multilabels;
ec.l.simple = {FLT_MAX, 1.f, 0.f};
for (size_t i = 0; i < leaf_labs.size(); i++)
{
base.predict(ec, b.max_routers + 1 + leaf_labs[i]);
float score = ec.pred.scalar;
if (score > 0)
selected_labs.push_back(leaf_labs[i]);
}
ec.pred.multilabels = preds;
ec.l.multilabels = multilabels;
return hamming_loss(ec.l.multilabels.label_v, selected_labs);
}
// pick up the "closest" example in the leaf using the score function.
int64_t pick_nearest(memory_tree& b, single_learner& base, const uint64_t cn, example& ec)
{
if (b.nodes[cn].examples_index.size() > 0)
{
float max_score = -FLT_MAX;
int64_t max_pos = -1;
for (size_t i = 0; i < b.nodes[cn].examples_index.size(); i++)
{
float score = 0.f;
uint32_t loc = b.nodes[cn].examples_index[i];
// do not use reward to update memory tree during the very first pass
//(which is for unsupervised training for memory tree)
if (b.learn_at_leaf == true && b.current_pass >= 1)
{
float tmp_s = normalized_linear_prod(b, &ec, b.examples[loc]);
diag_kronecker_product_test(ec, *b.examples[loc], *b.kprod_ec, b.oas);
b.kprod_ec->l.simple = {FLT_MAX, 0., tmp_s};
base.predict(*b.kprod_ec, b.max_routers);
score = b.kprod_ec->partial_prediction;
}
else
score = normalized_linear_prod(b, &ec, b.examples[loc]);
if (score > max_score)
{
max_score = score;
max_pos = (int64_t)loc;
}
}
return max_pos;
}
else
return -1;
}
// for any two examples, use number of overlap labels to indicate the similarity between these two examples.
float get_overlap_from_two_examples(example& ec1, example& ec2)
{
return (float)over_lap(ec1.l.multilabels.label_v, ec2.l.multilabels.label_v);
}
// we use F1 score as the reward signal
float F1_score_for_two_examples(example& ec1, example& ec2)
{
float num_overlaps = get_overlap_from_two_examples(ec1, ec2);
float v1 = (float)(num_overlaps / (1e-7 + ec1.l.multilabels.label_v.size() * 1.));
float v2 = (float)(num_overlaps / (1e-7 + ec2.l.multilabels.label_v.size() * 1.));
if (num_overlaps == 0.f)
return 0.f;
else
// return v2; //only precision
return 2.f * (v1 * v2 / (v1 + v2));
}
void predict(memory_tree& b, single_learner& base, example& ec)
{
MULTICLASS::label_t mc;
uint32_t save_multi_pred = 0;
MULTILABEL::labels multilabels;
MULTILABEL::labels preds;
if (b.oas == false)
{
mc = ec.l.multi;
save_multi_pred = ec.pred.multiclass;
}
else
{
multilabels = ec.l.multilabels;
preds = ec.pred.multilabels;
}
uint64_t cn = 0;
ec.l.simple = {-1.f, 1.f, 0.};
while (b.nodes[cn].internal == 1)
{ // if it's internal{
base.predict(ec, b.nodes[cn].base_router);
uint64_t newcn = ec.pred.scalar < 0 ? b.nodes[cn].left : b.nodes[cn].right; // do not need to increment nl and nr.
cn = newcn;
}
if (b.oas == false)
{
ec.l.multi = mc;
ec.pred.multiclass = save_multi_pred;
}
else
{
ec.pred.multilabels = preds;
ec.l.multilabels = multilabels;
}
int64_t closest_ec = 0;
if (b.oas == false)
{
closest_ec = pick_nearest(b, base, cn, ec);
if (closest_ec != -1)
ec.pred.multiclass = b.examples[closest_ec]->l.multi.label;
else
ec.pred.multiclass = 0;
if (ec.l.multi.label != ec.pred.multiclass)
{
ec.loss = ec.weight;
b.num_mistakes++;
}
}
else
{
float reward = 0.f;
closest_ec = pick_nearest(b, base, cn, ec);
if (closest_ec != -1)
{
reward = F1_score_for_two_examples(ec, *b.examples[closest_ec]);
b.F1_score += reward;
}
v_array<uint32_t> selected_labs = v_init<uint32_t>();
ec.loss = (float)compute_hamming_loss_via_oas(b, base, cn, ec, selected_labs);
b.hamming_loss += ec.loss;
}
}
float return_reward_from_node(memory_tree& b, single_learner& base, uint64_t cn, example& ec, float weight = 1.f)
{
// example& ec = *b.examples[ec_array_index];
MULTICLASS::label_t mc;
uint32_t save_multi_pred = 0;
MULTILABEL::labels multilabels;
MULTILABEL::labels preds;
if (b.oas == false)
{
mc = ec.l.multi;
save_multi_pred = ec.pred.multiclass;
}
else
{
multilabels = ec.l.multilabels;
preds = ec.pred.multilabels;
}
ec.l.simple = {FLT_MAX, 1., 0.0};
while (b.nodes[cn].internal != -1)
{
base.predict(ec, b.nodes[cn].base_router);
float prediction = ec.pred.scalar;
cn = prediction < 0 ? b.nodes[cn].left : b.nodes[cn].right;
}
if (b.oas == false)
{
ec.l.multi = mc;
ec.pred.multiclass = save_multi_pred;
}
else
{
ec.pred.multilabels = preds;
ec.l.multilabels = multilabels;
}
// get to leaf now:
int64_t closest_ec = 0;
float reward = 0.f;
closest_ec = pick_nearest(b, base, cn, ec); // no randomness for picking example.
if (b.oas == false)
{
if ((closest_ec != -1) && (b.examples[closest_ec]->l.multi.label == ec.l.multi.label))
reward = 1.f;
}
else
{
if (closest_ec != -1)
reward = F1_score_for_two_examples(ec, *b.examples[closest_ec]);
}
b.total_num_queries++;
if (b.learn_at_leaf == true && closest_ec != -1)
{
float score = normalized_linear_prod(b, &ec, b.examples[closest_ec]);
diag_kronecker_product_test(ec, *b.examples[closest_ec], *b.kprod_ec, b.oas);
b.kprod_ec->l.simple = {reward, 1.f, -score};
b.kprod_ec->weight = weight;
base.learn(*b.kprod_ec, b.max_routers);
}
if (b.oas == true)
train_one_against_some_at_leaf(b, base, cn, ec); /// learn the inference procedure anyway
return reward;
}
void learn_at_leaf_random(
memory_tree& b, single_learner& base, const uint64_t& leaf_id, example& ec, const float& weight)
{
b.total_num_queries++;
int32_t ec_id = -1;
float reward = 0.f;
if (b.nodes[leaf_id].examples_index.size() > 0)
{
uint32_t pos = uint32_t(merand48(b.all->random_state) * b.nodes[leaf_id].examples_index.size());
ec_id = b.nodes[leaf_id].examples_index[pos];
}
if (ec_id != -1)
{
if (b.examples[ec_id]->l.multi.label == ec.l.multi.label)
reward = 1.f;
float score = normalized_linear_prod(b, &ec, b.examples[ec_id]);
diag_kronecker_product_test(ec, *b.examples[ec_id], *b.kprod_ec, b.oas);
b.kprod_ec->l.simple = {reward, 1.f, -score};
b.kprod_ec->weight = weight; //* b.nodes[leaf_id].examples_index.size();
base.learn(*b.kprod_ec, b.max_routers);
}
return;
}
void route_to_leaf(memory_tree& b, single_learner& base, const uint32_t& ec_array_index, uint64_t cn,
v_array<uint64_t>& path, bool insertion)
{
example& ec = *b.examples[ec_array_index];
MULTICLASS::label_t mc;
uint32_t save_multi_pred = 0;
MULTILABEL::labels multilabels;
MULTILABEL::labels preds;
if (b.oas == false)
{
mc = ec.l.multi;
save_multi_pred = ec.pred.multiclass;
}
else
{
multilabels = ec.l.multilabels;
preds = ec.pred.multilabels;
}
path.clear();
ec.l.simple = {FLT_MAX, 1.0, 0.0};
while (b.nodes[cn].internal != -1)
{
path.push_back(cn); // path stores node id from the root to the leaf
base.predict(ec, b.nodes[cn].base_router);
float prediction = ec.pred.scalar;
if (insertion == false)
cn = prediction < 0 ? b.nodes[cn].left : b.nodes[cn].right;
else
cn = insert_descent(b.nodes[cn], prediction);
}
path.push_back(cn); // push back the leaf
if (b.oas == false)
{
ec.l.multi = mc;
ec.pred.multiclass = save_multi_pred;
}
else
{
ec.pred.multilabels = preds;
ec.l.multilabels = multilabels;
}
// cout<<"at route to leaf: "<<path.size()<<endl;
if (insertion == true)
{
b.nodes[cn].examples_index.push_back(ec_array_index);
if ((b.nodes[cn].examples_index.size() >= b.max_leaf_examples) && (b.nodes.size() + 2 < b.max_nodes))
split_leaf(b, base, cn);
}
}
// we roll in, then stop at a random step, do exploration. //no real insertion happens in the function.
void single_query_and_learn(memory_tree& b, single_learner& base, const uint32_t& ec_array_index, example& ec)
{
v_array<uint64_t> path_to_leaf = v_init<uint64_t>();
route_to_leaf(b, base, ec_array_index, 0, path_to_leaf, false); // no insertion happens here.
if (path_to_leaf.size() > 1)
{
// uint32_t random_pos = merand48(b.all->random_state)*(path_to_leaf.size()-1);
uint32_t random_pos = (uint32_t)(merand48(b.all->random_state) * (path_to_leaf.size())); // include leaf
uint64_t cn = path_to_leaf[random_pos];
if (b.nodes[cn].internal != -1)
{ // if it's an internal node:'
float objective = 0.f;
float prob_right = 0.5;
float coin = merand48(b.all->random_state) < prob_right ? 1.f : -1.f;
float weight = path_to_leaf.size() * 1.f / (path_to_leaf.size() - 1.f);
if (coin == -1.f)
{ // go left
float reward_left_subtree = return_reward_from_node(b, base, b.nodes[cn].left, ec, weight);
objective = (float)((1. - b.alpha) * log(b.nodes[cn].nl / b.nodes[cn].nr) +
b.alpha * (-reward_left_subtree / (1. - prob_right)) / 2.);
}
else
{ // go right:
float reward_right_subtree = return_reward_from_node(b, base, b.nodes[cn].right, ec, weight);
objective = (float)((1. - b.alpha) * log(b.nodes[cn].nl / b.nodes[cn].nr) +
b.alpha * (reward_right_subtree / prob_right) / 2.);
}
float ec_input_weight = ec.weight;
MULTICLASS::label_t mc;
MULTILABEL::labels multilabels;
MULTILABEL::labels preds;
if (b.oas == false)
mc = ec.l.multi;
else
{
multilabels = ec.l.multilabels;
preds = ec.pred.multilabels;
}
ec.weight = fabs(objective);
if (ec.weight >= 100.f) // crop the weight, otherwise sometimes cause NAN outputs.
ec.weight = 100.f;
else if (ec.weight < .01f)
ec.weight = 0.01f;
ec.l.simple = {objective < 0. ? -1.f : 1.f, 1.f, 0.};
base.learn(ec, b.nodes[cn].base_router);
if (b.oas == false)
ec.l.multi = mc;
else
{
ec.pred.multilabels = preds;
ec.l.multilabels = multilabels;
}
ec.weight = ec_input_weight; // restore the original weight
}
else
{ // if it's a leaf node:
float weight = 1.f; // float(path_to_leaf.size());
if (b.learn_at_leaf == true)
learn_at_leaf_random(
b, base, cn, ec, weight); // randomly sample one example, query reward, and update leaf learner
if (b.oas == true)
train_one_against_some_at_leaf(b, base, cn, ec);
}
}
path_to_leaf.delete_v();
}
// using reward signals
void update_rew(memory_tree& b, single_learner& base, const uint32_t& ec_array_index, example& ec)
{
single_query_and_learn(b, base, ec_array_index, ec);
}
// node here the ec is already stored in the b.examples, the task here is to rout it to the leaf,
// and insert the ec_array_index to the leaf.
void insert_example(memory_tree& b, single_learner& base, const uint32_t& ec_array_index, bool fake_insert = false)
{
uint64_t cn = 0; // start from the root.
while (b.nodes[cn].internal == 1) // if it's internal node:
{
// predict and train the node at cn.
float router_pred = train_node(b, base, *b.examples[ec_array_index], cn);
uint64_t newcn = insert_descent(b.nodes[cn], router_pred); // updated nr or nl
cn = newcn;
}
if (b.oas == true) // if useing oas as inference procedure, we just train oas here, as it's independent of the memory
// unit anyway'
train_one_against_some_at_leaf(b, base, cn, *b.examples[ec_array_index]);
if ((b.nodes[cn].internal == -1) && (fake_insert == false)) // get to leaf:
{
b.nodes[cn].examples_index.push_back(ec_array_index);
if (b.nodes[cn].examples_index.size() > b.max_ex_in_leaf)
{
b.max_ex_in_leaf = b.nodes[cn].examples_index.size();
}
float leaf_pred = train_node(b, base, *b.examples[ec_array_index], cn); // tain the leaf as well.
insert_descent(b.nodes[cn], leaf_pred); // this is a faked descent, the purpose is only to update nl and nr of cn
// if the number of examples exceeds the max_leaf_examples, and not reach the max_nodes - 2 yet, we split:
if ((b.nodes[cn].examples_index.size() >= b.max_leaf_examples) && (b.nodes.size() + 2 <= b.max_nodes))
{
split_leaf(b, base, cn);
}
}
}
void experience_replay(memory_tree& b, single_learner& base)
{
uint64_t cn = 0; // start from root, randomly descent down!
int ec_id = random_sample_example_pop(b, cn);
if (ec_id >= 0)
{
if (b.current_pass < 1)
insert_example(b, base, ec_id); // unsupervised learning
else
{
if (b.dream_at_update == false)
{
v_array<uint64_t> tmp_path = v_init<uint64_t>();
route_to_leaf(b, base, ec_id, 0, tmp_path, true);
tmp_path.delete_v();
}
else
{
insert_example(b, base, ec_id);