-
Notifications
You must be signed in to change notification settings - Fork 8
/
knowledge_graph_embeddings.cc
1338 lines (1084 loc) · 44.4 KB
/
knowledge_graph_embeddings.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 "utils.h"
#include "ps/ps.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <thread>
#include <numeric>
#include <boost/program_options.hpp>
#include <limits>
#include <sstream>
#include <string>
#include <iostream>
#include <unistd.h>
#include <bitset>
#include <random>
#include <iomanip>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <cassert>
#include <cstring>
#include <regex>
using namespace ps;
using namespace std;
typedef double ValT;
typedef DefaultColoServerHandle<ValT> HandleT;
typedef ColoKVServer<ValT, HandleT> ServerT;
typedef ColoKVWorker<ValT, HandleT> WorkerT;
enum class Alg { ComplEx, RESCAL };
// Model and algorithm parameters
string alg;
Alg algorithm;
string dataset;
uint embed_dim;
uint rel_dim;
double eta;
double gamma_entity;
double gamma_relation;
double dropout_entity;
double dropout_relation;
int neg_ratio;
uint num_epochs;
uint num_threads;
int eval_freq;
long ne; // number of entities
long nr; // number of relations
string model_path;
int save_every_nth_epoch;
bool write_end_checkpoint;
// Evaluation
size_t eval_truncate_va;
size_t eval_truncate_tr;
bool run_initial_evaluation;
unsigned model_seed;
// System parameters
bool async_push;
bool signal_initial_relations_intent;
uint signal_intent_ahead;
bool read_partitioned_dataset;
std::string init_parameters;
bool enforce_random_keys;
bool enforce_full_replication;
long max_N_per_thread;
long max_runtime;
uint num_workers = -1;
uint num_keys = -1;
uint entity_vector_length;
uint relation_vector_length;
string tr_file;
int num_serv; // number of servers
// random assignment of keys (if enabled)
std::vector<Key> key_assignment;
Key loss_key;
Key eval_key;
// positions in eval vector (for distributed evaluation)
const int _MRR_S = 0;
const int _MRR_R = 1;
const int _MRR_O = 2;
const int _MRR_S_RAW = 3;
const int _MRR_O_RAW = 4;
const int _MR_S = 5;
const int _MR_R = 6;
const int _MR_O = 7;
const int _MR_S_RAW = 8;
const int _MR_O_RAW = 9;
const int _HITS01_S = 10;
const int _HITS01_R = 11;
const int _HITS01_O = 12;
const int _HITS03_S = 13;
const int _HITS03_R = 14;
const int _HITS03_O = 15;
const int _HITS10_S = 16;
const int _HITS10_R = 17;
const int _HITS10_O = 18;
static default_random_engine GLOBAL_GENERATOR;
static uniform_real_distribution<double> UNIFORM(0, 1);
typedef tuple<int, int, int> triplet;
inline Key entity_key (const int e) {
return enforce_random_keys ? key_assignment[e] : e;
}
inline Key relation_key (const int r) {
return enforce_random_keys ? key_assignment[ne+r] : ne+r;
}
// Negative sampling distribution
std::mt19937 negs_gen;
std::uniform_int_distribution<int> negs_dist;
// Draw a negative sample
inline Key DrawEntity() {
return entity_key(negs_dist(negs_gen));
}
std::ostream& operator<<(std::ostream& os, const triplet t) {
std::stringstream ss;
ss << "<" << get<0>(t) << "," << get<1>(t) << "," << get<2>(t) << ">";
os << ss.str();
return os;
}
// Process-level data structures
vector<triplet> sros_tr;
vector<triplet> sros_va;
vector<triplet> sros_te;
vector<triplet> sros_al;
vector<triplet> create_sros(const string& fname) {
ifstream ifs(fname, ios::in);
string line;
int s, r, o;
vector<triplet> sros;
assert(!ifs.fail());
while (getline(ifs, line)) {
stringstream ss(line);
ss >> s >> r >> o;
sros.push_back( make_tuple(s, r, o) );
}
ifs.close();
return sros;
}
vector<vector<double>> uniform_matrix(int m, int n, double l, double h) {
vector<vector<double>> matrix;
matrix.resize(m);
for (int i = 0; i < m; i++)
matrix[i].resize(n);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
matrix[i][j] = (h-l)*UNIFORM(GLOBAL_GENERATOR) + l;
return matrix;
}
vector<vector<double>> const_matrix(int m, int n, double c) {
vector<vector<double>> matrix;
matrix.resize(m);
for (int i = 0; i < m; i++)
matrix[i].resize(n);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
matrix[i][j] = c;
return matrix;
}
vector<int> range(int n, int start=0) { // 0 ... n-1
vector<int> v;
v.reserve(n);
for (int i = start; i < n+start; i++)
v.push_back(i);
return v;
}
// pull the entire model from the PS to local vectors
void pull_full_model(std::vector<ValT>& E, std::vector<ValT>& R, WorkerT& kv) {
util::Stopwatch sw_pull;
sw_pull.start();
// construct data structures for pull
vector<Key> R_keys (nr);
for(unsigned int r=0; r!=nr; ++r) {
R_keys[r] = relation_key(r);
}
R.resize(nr * relation_vector_length);
vector<Key> E_keys (ne);
for(unsigned int e=0; e!=ne; ++e) {
E_keys[e] = entity_key(e);
}
E.resize (ne * entity_vector_length);
// pull
kv.WaitSync();
kv.Wait(kv.Pull(E_keys, &E), kv.Pull(R_keys, &R));
sw_pull.stop();
ALOG("Model pulled (" << sw_pull << ")");
}
double sigmoid(double x, double cutoff=30) {
if (x > +cutoff) return 1.;
if (x < -cutoff) return 0.;
return 1./(1.+exp(-x));
}
class SROBucket {
unordered_set<int64_t> __sros;
unordered_map<int64_t, vector<int>> __sr2o;
unordered_map<int64_t, vector<int>> __or2s;
size_t ne_bits;
size_t nr_bits;
long duplicates = 0;
int64_t hash(int a, int b, int c) const {
int64_t x = a;
x = (x << nr_bits) + b;
return (x << ne_bits) + c;
}
int64_t hash(int a, int b) const {
int64_t x = a;
return (x << 32) + b;
}
public:
SROBucket(const vector<triplet>& sros) {
ne_bits = ceil(log2(ne*2));
nr_bits = ceil(log2(nr*2));
assert(2*ne_bits + nr_bits < sizeof(int64_t)*8); // make sure hash(int,int,int) does not overflow despite int64
for (auto sro : sros) {
int s = get<0>(sro);
int r = get<1>(sro);
int o = get<2>(sro);
// add identical data points to indexes only once
if (contains(s,r,o)) {
++duplicates;
continue;
}
int64_t __sro = hash(s, r, o);
__sros.insert(__sro);
int64_t __sr = hash(s, r);
if (__sr2o.find(__sr) == __sr2o.end())
__sr2o[__sr] = vector<int>();
__sr2o[__sr].push_back(o);
int64_t __or = hash(o, r);
if (__or2s.find(__or) == __or2s.end())
__or2s[__or] = vector<int>();
__or2s[__or].push_back(s);
}
ALOG("SROBucket: skipped " << duplicates << " duplicate data points");
}
bool contains(int a, int b, int c) const {
return __sros.find( hash(a, b, c) ) != __sros.end();
}
vector<int> sr2o(int s, int r) const {
return __sr2o.at(hash(s,r));
}
vector<int> or2s(int o, int r) const {
return __or2s.at(hash(o,r));
}
};
class Model {
protected:
double eta;
const double init_e = 1e-6;
vector<vector<double>> E;
vector<vector<double>> R;
vector<vector<double>> E_g;
vector<vector<double>> R_g;
public:
Model(double eta) {
this->eta = eta;
}
// saves a given model to disk
void save(const uint epoch, const string& fname, WorkerT& kv, const bool export_for_eval=true, const bool write_checkpoint=false) {
ALOG("Save model (" << (export_for_eval ? "eval export" : "") << (write_checkpoint ? ", checkpoint" : "") <<
") for epoch " << epoch << " to " << fname << "*.epoch." << std::to_string(epoch) << ".*.bin");
// pull the model
std::vector<ValT> E {};
std::vector<ValT> R {};
pull_full_model(E, R, kv);
// prepare output files
std::ofstream file_E_eval;
std::ofstream file_E_checkpoint;
std::ofstream file_E_adagrad;
std::ofstream file_R_eval;
std::ofstream file_R_checkpoint;
std::ofstream file_R_adagrad;
if (export_for_eval) {
file_E_eval.open(fname+"export.epoch." + std::to_string(epoch) + ".entities.bin", std::ios::binary);
file_R_eval.open(fname+"export.epoch." + std::to_string(epoch) + ".relations.bin", std::ios::binary);
if (!file_E_eval.is_open() || !file_R_eval.is_open()) {
ALOG("Error opening files for eval export");
abort();
}
}
if (write_checkpoint) {
file_E_checkpoint.open(fname+"checkpoint.epoch." + std::to_string(epoch) + ".entities.bin", std::ios::binary);
file_R_checkpoint.open(fname+"checkpoint.epoch." + std::to_string(epoch) + ".relations.bin", std::ios::binary);
file_E_adagrad.open(fname+"checkpoint.epoch." + std::to_string(epoch) + ".entities.adagrad.bin", std::ios::binary);
file_R_adagrad.open(fname+"checkpoint.epoch." + std::to_string(epoch) + ".relations.adagrad.bin", std::ios::binary);
if (!file_E_checkpoint.is_open() || !file_R_checkpoint.is_open() || !file_E_adagrad.is_open() || !file_R_adagrad.is_open()) {
ALOG("Error opening files for writing checkpoint");
abort();
}
}
// write entity embeddings
for (long e = 0; e != ne; e++) {
if (export_for_eval) {
for(size_t i = 0; i!=embed_dim; ++i) {
float as_float = static_cast<float>(E[e * entity_vector_length + i]);
file_E_eval.write((char*) &as_float, sizeof(float)); // embedding
}
}
if (write_checkpoint) {
ValT* pos = &(E[e * entity_vector_length]);
file_E_checkpoint.write((char*) pos, sizeof(ValT) * embed_dim); // embedding
file_E_adagrad.write((char*) pos+embed_dim, sizeof(ValT) * embed_dim); // adagrad
}
}
// write relation embeddings
for (long r = 0; r != nr; r++) {
if (export_for_eval) {
for(size_t i = 0; i!=rel_dim; ++i) {
float as_float = static_cast<float>(R[r * relation_vector_length + i]);
file_R_eval.write((char*) &as_float, sizeof(float)); // embedding
}
}
if (write_checkpoint) {
ValT* pos = &(R[r * relation_vector_length]);
file_R_checkpoint.write((char*) pos, sizeof(ValT) * rel_dim); // embedding
file_R_adagrad.write((char*) pos+rel_dim, sizeof(ValT) * rel_dim); // adagrad
}
}
if (export_for_eval) {
file_E_eval.close();
file_R_eval.close();
}
if (write_checkpoint) {
file_E_checkpoint.close();
file_R_checkpoint.close();
file_E_adagrad.close();
file_R_adagrad.close();
}
}
// randomly zeroes some elements of the given vector and scales
// other elements by 1 / (1-p)
void do_dropout(double* v, const size_t len, const double p) {
for (unsigned i = 0; i != len; i++) {
if (UNIFORM(GLOBAL_GENERATOR) < p) {
v[i] = 0;
} else {
v[i] *= 1 / (1-p);
}
}
}
void adagrad_update(double* E_s, double* R_r, double* E_o,
double* d_s, double* d_r, double* d_o) {
double* Eg_s = E_s + embed_dim;
double* Rg_r = R_r + rel_dim;
double* Eg_o = E_o + embed_dim;
double* dg_s = d_s + embed_dim;
double* dg_r = d_r + rel_dim;
double* dg_o = d_o + embed_dim;
for (unsigned i = 0; i < embed_dim; i++) dg_s[i] = d_s[i] * d_s[i];
for (unsigned i = 0; i < rel_dim; i++) dg_r[i] = d_r[i] * d_r[i];
for (unsigned i = 0; i < embed_dim; i++) dg_o[i] = d_o[i] * d_o[i];
for (unsigned i = 0; i < embed_dim; i++) d_s[i] = - eta * d_s[i] / sqrt(Eg_s[i] + dg_s[i]);
for (unsigned i = 0; i < rel_dim; i++) d_r[i] = - eta * d_r[i] / sqrt(Rg_r[i] + dg_r[i]);
for (unsigned i = 0; i < embed_dim; i++) d_o[i] = - eta * d_o[i] / sqrt(Eg_o[i] + dg_o[i]);
}
void train(int s, int r, int o, bool is_positive, WorkerT& kv, double& bce_loss, double& reg_loss) {
// Allocate memory and get embeddings from the server
vector<double> embed_s (entity_vector_length);
vector<double> embed_r (relation_vector_length);
vector<double> embed_o (entity_vector_length);
vector<double> update_s (embed_s.size());
vector<double> update_r (embed_r.size());
vector<double> update_o (embed_o.size());
vector<Key> key_s (1);
vector<Key> key_r {relation_key(r)};
vector<Key> key_o (1);
int ts_s, ts_r, ts_o;
// negative sample for the subject?
if (s < 0) { // negative sample
ts_s = kv.PullSample(-s, key_s, embed_s);
} else { // true subject
key_s[0] = entity_key(s);
ts_s = kv.Pull(key_s, &embed_s);
}
// negative sample for the object?
if (o < 0) { // negative sample
ts_o = kv.PullSample(-o, key_o, embed_o);
} else { // true object
key_o[0] = entity_key(o);
ts_o = kv.Pull(key_o, &embed_o);
}
ts_r = kv.Pull(key_r, &embed_r);
kv.Wait(ts_s, ts_r, ts_o);
double* E_s = embed_s.data();
double* R_r = embed_r.data();
double* E_o = embed_o.data();
double* d_s = update_s.data();
double* d_r = update_r.data();
double* d_o = update_o.data();
// dropout
if (dropout_entity != 0) {
do_dropout(E_s, embed_dim, dropout_entity);
do_dropout(E_o, embed_dim, dropout_entity);
}
if (dropout_relation != 0) {
do_dropout(R_r, rel_dim, dropout_relation);
}
double offset = is_positive ? 1 : 0;
double triple_score = score(E_s, R_r, E_o);
double d_loss = sigmoid(triple_score) - offset;
// record training loss
double y = is_positive ? 1 : -1;
double loss = -log(sigmoid(y*triple_score, 1e9));
bce_loss += loss;
// score_grad(s, r, o, d_s, d_r, d_o);
score_grad(E_s, R_r, E_o, d_s, d_r, d_o);
for (unsigned i = 0; i < embed_dim; i++) d_s[i] *= d_loss;
for (unsigned i = 0; i < rel_dim; i++) d_r[i] *= d_loss;
for (unsigned i = 0; i < embed_dim; i++) d_o[i] *= d_loss;
// regularization (only on positives)
if (is_positive) {
double reg_loss_s = 0;
double reg_loss_r = 0;
double reg_loss_o = 0;
for (unsigned i = 0; i < embed_dim; i++) {
d_s[i] += gamma_entity * E_s[i];
reg_loss_s += E_s[i]*E_s[i];
}
for (unsigned i = 0; i < rel_dim; i++) {
d_r[i] += gamma_relation * R_r[i];
reg_loss_r += R_r[i]*R_r[i];
}
for (unsigned i = 0; i < embed_dim; i++) {
d_o[i] += gamma_entity * E_o[i];
reg_loss_o += E_o[i]*E_o[i];
}
reg_loss += gamma_entity * reg_loss_s + gamma_relation * reg_loss_r + gamma_entity * reg_loss_o;
}
adagrad_update(E_s, R_r, E_o, d_s, d_r, d_o);
if (async_push) {
kv.Push(key_s, update_s); kv.Push(key_r, update_r); kv.Push(key_o, update_o);
} else {
kv.Wait(kv.Push(key_s, update_s), kv.Push(key_r, update_r), kv.Push(key_o, update_o));
}
}
virtual double score(double* E_s, double* R_r, double* E_o) const = 0;
virtual void score_grad(double* E_s, double* R_r, double* E_o,
double* d_s, double* d_r, double* d_o) {};
virtual vector<double> init_ps(std::function<double()> init_rand) = 0;
};// end Model
class Evaluator {
long ne;
long nr;
const vector<triplet>& sros;
const SROBucket& sro_bucket;
public:
Evaluator(long ne, long nr, const vector<triplet>& sros, const SROBucket& sro_bucket) :
ne(ne), nr(nr), sros(sros), sro_bucket(sro_bucket) {}
// distributed evaluation: each node processes a part of the data points. The results are then aggregated via the PS
unordered_map<string, double> evaluate(const Model *model, int truncate, vector<double>& E, vector<double>& R, const int worker_id, WorkerT& kv) {
double mrr_s = 0.;
double mrr_r = 0.;
double mrr_o = 0.;
double mrr_s_raw = 0.;
double mrr_o_raw = 0.;
double mr_s = 0.;
double mr_r = 0.;
double mr_o = 0.;
double mr_s_raw = 0.;
double mr_o_raw = 0.;
double hits01_s = 0.;
double hits01_r = 0.;
double hits01_o = 0.;
double hits03_s = 0.;
double hits03_r = 0.;
double hits03_o = 0.;
double hits10_s = 0.;
double hits10_r = 0.;
double hits10_o = 0.;
// calculate total number of data points and number of data points per node
int N = this->sros.size();
if (truncate > 0) {
N = min(N, truncate);
}
int N_per_node = ceil(1.0 * N / num_serv);
// allocate evaluation vector (used to aggregated partial evaluation results on PS)
std::vector<Key> eval_key_vec { eval_key };
std::vector<ValT> eval (entity_vector_length);
// reset the evaluation vector (might contain old values from last eval)
if (worker_id == 0) {
kv.Wait(kv.Pull(eval_key_vec, &eval));
for(size_t i=0; i!=eval.size(); ++i) {
eval[i] = -eval[i];
}
kv.Wait(kv.Push(eval_key_vec, eval));
}
// wait for reset to finish
Postoffice::Get()->Barrier(1, kServerGroup);
// use all threads to evaluate
#pragma omp parallel for reduction(+: mrr_s, mrr_r, mrr_o, mr_s, mr_r, mr_o, \
hits01_s, hits01_r, hits01_o, hits03_s, hits03_r, hits03_o, hits10_s, hits10_r, hits10_o)
for (int z = 0; z < N_per_node; z++) {
auto i = ps::MyRank() * N_per_node + z;
// last worker might have less data points
if(i >= N) continue;
auto ranks = this->rank(model, sros[i], E, R);
double rank_s = get<0>(ranks);
double rank_r = get<1>(ranks);
double rank_o = get<2>(ranks);
double rank_s_raw = get<3>(ranks);
double rank_o_raw = get<4>(ranks);
mrr_s += 1./rank_s;
mrr_r += 1./rank_r;
mrr_o += 1./rank_o;
mrr_s_raw += 1./rank_s_raw;
mrr_o_raw += 1./rank_o_raw;
mr_s += rank_s;
mr_r += rank_r;
mr_o += rank_o;
mr_s_raw += rank_s_raw;
mr_o_raw += rank_o_raw;
hits01_s += rank_s <= 01;
hits01_r += rank_r <= 01;
hits01_o += rank_o <= 01;
hits03_s += rank_s <= 03;
hits03_r += rank_r <= 03;
hits03_o += rank_o <= 03;
hits10_s += rank_s <= 10;
hits10_r += rank_r <= 10;
hits10_o += rank_o <= 10;
}
// aggregate partial evaluation results on the PS
eval[_MRR_S] = mrr_s;
eval[_MRR_R] = mrr_r;
eval[_MRR_O] = mrr_o;
eval[_MRR_S_RAW] = mrr_s_raw;
eval[_MRR_O_RAW] = mrr_o_raw;
eval[_MR_S] = mr_s;
eval[_MR_R] = mr_r;
eval[_MR_O] = mr_o;
eval[_MR_S_RAW] = mr_s_raw;
eval[_MR_O_RAW] = mr_o_raw;
eval[_HITS01_S] = hits01_s;
eval[_HITS01_R] = hits01_r;
eval[_HITS01_O] = hits01_o;
eval[_HITS03_S] = hits03_s;
eval[_HITS03_R] = hits03_r;
eval[_HITS03_O] = hits03_o;
eval[_HITS10_S] = hits10_s;
eval[_HITS10_R] = hits10_r;
eval[_HITS10_O] = hits10_o;
kv.Wait(kv.Push(eval_key_vec, eval)); // push partial evaluation results
// wait for all nodes to finish evaluation
Postoffice::Get()->Barrier(1, kServerGroup);
// calculate final results
unordered_map<string, double> info;
if (worker_id == 0) {
// pull aggregated results form PS
kv.Wait(kv.Pull(eval_key_vec, &eval));
info["mrr_s"] = eval[_MRR_S] / N;
info["mrr_r"] = eval[_MRR_R] / N;
info["mrr_o"] = eval[_MRR_O] / N;
info["mrr_s_raw"] = eval[_MRR_S_RAW] / N;
info["mrr_o_raw"] = eval[_MRR_O_RAW] / N;
info["mr_s"] = eval[_MR_S] / N;
info["mr_r"] = eval[_MR_R] / N;
info["mr_o"] = eval[_MR_O] / N;
info["mr_s_raw"] = eval[_MR_S_RAW] / N;
info["mr_o_raw"] = eval[_MR_O_RAW] / N;
info["hits01_s"] = eval[_HITS01_S] / N;
info["hits01_r"] = eval[_HITS01_R] / N;
info["hits01_o"] = eval[_HITS01_O] / N;
info["hits03_s"] = eval[_HITS03_S] / N;
info["hits03_r"] = eval[_HITS03_R] / N;
info["hits03_o"] = eval[_HITS03_O] / N;
info["hits10_s"] = eval[_HITS10_S] / N;
info["hits10_r"] = eval[_HITS10_R] / N;
info["hits10_o"] = eval[_HITS10_O] / N;
}
return info;
}
private:
tuple<double, double, double, double, double> rank(const Model *model, const triplet& sro, vector<double>& E, vector<double>& R) {
int rank_s = 1;
int rank_r = 1;
int rank_o = 1;
long s = get<0>(sro);
long r = get<1>(sro);
long o = get<2>(sro);
double* E_s = E.data() + s*entity_vector_length;
double* R_r = R.data() + r*relation_vector_length;
double* E_o = E.data() + o*entity_vector_length;
// XXX:
// There might be degenerated cases when all output scores == 0, leading to perfect but meaningless results.
// A quick fix is to add a small offset to the base_score.
double base_score = model->score(E_s, R_r, E_o) - 1e-32;
// report nans if score produces nans
if(std::isnan(base_score)) {
return make_tuple(NAN, NAN, NAN, NAN, NAN);
}
for (long ss = 0; ss < ne; ss++) {
double* E_ss = E.data() + ss*entity_vector_length;
auto score = model->score(E_ss, R_r, E_o);
if (score > base_score || std::isnan(score)) rank_s++;
}
for (long rr = 0; rr < nr; rr++) {
double *R_rr = R.data() + rr*relation_vector_length;
auto score = model->score(E_s, R_rr, E_o);
if (score > base_score || std::isnan(score)) rank_r++;
}
for (long oo = 0; oo < ne; oo++) {
double* E_oo = E.data() + oo*entity_vector_length;
auto score = model->score(E_s, R_r, E_oo);
if (score > base_score || std::isnan(score)) rank_o++;
}
int rank_s_raw = rank_s;
int rank_o_raw = rank_o;
for (long ss : sro_bucket.or2s(o, r)) {
double* E_ss = E.data() + ss*entity_vector_length;
if (model->score(E_ss, R_r, E_o) > base_score) rank_s--;
}
for (long oo : sro_bucket.sr2o(s, r)) {
double* E_oo = E.data() + oo*entity_vector_length;
if (model->score(E_s, R_r, E_oo) > base_score) rank_o--;
}
return make_tuple(rank_s, rank_r, rank_o, rank_s_raw, rank_o_raw);
}
};
void pretty_print(std::string prefix_str, const unordered_map<string, double>& info) {
const char* prefix = prefix_str.c_str();
printf("%s MRR \t%.2f\t%.2f\t%.2f\n", prefix, 100*info.at("mrr_s"), 100*info.at("mrr_r"), 100*info.at("mrr_o"));
printf("%s MRR_RAW\t%.2f\t%.2f\n", prefix, 100*info.at("mrr_s_raw"), 100*info.at("mrr_o_raw"));
printf("%s MR \t%.2f\t%.2f\t%.2f\n", prefix, info.at("mr_s"), info.at("mr_r"), info.at("mr_o"));
printf("%s MR_RAW \t%.2f\t%.2f\n", prefix, info.at("mr_s_raw"), info.at("mr_o_raw"));
printf("%s Hits@01\t%.2f\t%.2f\t%.2f\n", prefix, 100*info.at("hits01_s"), 100*info.at("hits01_r"), 100*info.at("hits01_o"));
printf("%s Hits@03\t%.2f\t%.2f\t%.2f\n", prefix, 100*info.at("hits03_s"), 100*info.at("hits03_r"), 100*info.at("hits03_o"));
printf("%s Hits@10\t%.2f\t%.2f\t%.2f\n", prefix, 100*info.at("hits10_s"), 100*info.at("hits10_r"), 100*info.at("hits10_o"));
}
Evaluator* evaluator_va;
Evaluator* evaluator_tr;
Model* model;
// based on Google's word2vec
int ArgPos(char *str, int argc, char **argv) {
int a;
for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) {
if (a == argc - 1) {
printf("Argument missing for %s\n", str);
exit(1);
}
return a;
}
return -1;
}
class Complex : public Model {
int nh;
public:
Complex(long ne, long nr, int nh, double eta) : Model(eta) {
assert( nh % 2 == 0 );
this->nh = nh;
}
vector<double> init_ps(std::function<double()> init_rand) {
auto c = init_e;
vector<double> matrix ((ne+nr) * embed_dim * 2);
for (long i = 0; i!=ne+nr; ++i) {
double* mpos = matrix.data() + i*nh*2;
for (long j = 0; j!=nh; ++j) {
mpos[j] = init_rand();
}
for (long j = nh; j != nh*2; ++j) {
mpos[j] = c;
}
}
return matrix;
}
double score(double* E_s, double* R_r, double* E_o) const {
double dot = 0;
int nh_2 = nh/2;
for (int i = 0; i < nh_2; i++) {
dot += R_r[i] * E_s[i] * E_o[i];
dot += R_r[i] * E_s[nh_2+i] * E_o[nh_2+i];
dot += R_r[nh_2+i] * E_s[i] * E_o[nh_2+i];
dot -= R_r[nh_2+i] * E_s[nh_2+i] * E_o[i];
}
return dot;
}
void score_grad(double* E_s, double* R_r, double* E_o,
double* d_s, double* d_r, double* d_o) {
int nh_2 = nh/2;
for (int i = 0; i < nh_2; i++) {
// re
d_s[i] = R_r[i] * E_o[i] + R_r[nh_2+i] * E_o[nh_2+i];
d_r[i] = E_s[i] * E_o[i] + E_s[nh_2+i] * E_o[nh_2+i];
d_o[i] = R_r[i] * E_s[i] - R_r[nh_2+i] * E_s[nh_2+i];
// im
d_s[nh_2+i] = R_r[i] * E_o[nh_2+i] - R_r[nh_2+i] * E_o[i];
d_r[nh_2+i] = E_s[i] * E_o[nh_2+i] - E_s[nh_2+i] * E_o[i];
d_o[nh_2+i] = R_r[i] * E_s[nh_2+i] + R_r[nh_2+i] * E_s[i];
}
}
};
class Rescal : public Model {
int nh;
public:
Rescal(long ne, long nr, int nh, double eta) : Model(eta) {
this->nh = nh;
}
vector<double> init_ps(std::function<double()> init_rand) {
auto c = init_e;
vector<double> matrix ((ne+nr*embed_dim) * embed_dim * 2);
for (long i = 0; i!=ne; ++i) {
double* mpos = matrix.data() + i*nh*2;
for (long j = 0; j!=nh; ++j) {
mpos[j] = init_rand();
}
for (long j = nh; j != nh*2; ++j) {
mpos[j] = c;
}
}
for (long i = 0; i!=nr; ++i) {
double* mpos = matrix.data() + ne*nh*2 + i*nh*nh*2;
for (long j = 0; j!=nh*nh; ++j) {
mpos[j] = init_rand();
}
for (long j = nh*nh; j != nh*nh*2; ++j) {
mpos[j] = c;
}
}
return matrix;
}
// sizes: h h^2 h
double score(double* E_s, double* R_r, double* E_o) const {
double dot = 0;
// assume R is row-major [row1col1, row1col2, ..., row2col1, row2col2, ...]
for (int a = 0; a != nh; ++a) {
auto anh = a*nh;
for (int b = 0; b != nh; ++b) {
dot += R_r[anh+b] * E_s[a] * E_o[b];
}
}
return dot;
}
void score_grad(double* E_s, double* R_r, double* E_o,
double* d_s, double* d_r, double* d_o) {
for (int a = 0; a != nh; ++a) {
auto anh = a*nh;
d_s[a] = 0;
d_o[a] = 0;
for (int b = 0; b != nh; ++b) {
d_s[a] += R_r[anh+b] * E_o[b]; // gradient for subject
d_o[a] += R_r[b*nh+a] * E_s[b]; // gradient for object
d_r[anh+b] = E_s[a] * E_o[b]; // gradient for relation
}
}
}
};
// evaluate the current model (on train and validation set)
void run_eval(const uint epoch, double& best_mrr, const int worker_id, WorkerT& kv) {
std::vector<ValT> E {};
std::vector<ValT> R {};
pull_full_model(E, R, kv);
// evaluate
util::Stopwatch sw_eval;
sw_eval.start();
ALOG("Evaluation (TR truncate " << eval_truncate_tr << ", VA truncate " << eval_truncate_va << ")");
auto info_tr = evaluator_tr->evaluate(model, eval_truncate_tr, E, R, worker_id, kv);
auto info_va = evaluator_va->evaluate(model, eval_truncate_va, E, R, worker_id, kv);
sw_eval.stop();
ALOG("Worker " << worker_id << ": eval finished (" << sw_eval << ")");
// save the best model to disk
if (worker_id == 0) {
double curr_mrr = (info_va["mrr_s"] + info_va["mrr_o"])/2;
if (curr_mrr > best_mrr) {
best_mrr = curr_mrr;
}
printf("\n");
printf(" Dist EV Elapse %f\n", sw_eval.elapsed_s());
printf("======================================\n");
pretty_print(std::to_string(epoch)+std::string("-TR"), info_tr);
printf("\n");
pretty_print(std::to_string(epoch)+std::string("-VA"), info_va);
printf("\n");
printf("%i-VA MRR_CURR %.2f\n", epoch, 100*best_mrr);
printf("%i-VA MRR_BEST %.2f\n", epoch, 100*best_mrr);
printf("\n");
}
}
void RunWorker(int customer_id, ServerT* server=nullptr) {
std::unordered_map<std::string, util::Stopwatch> sw {};
WorkerT kv(customer_id, *server);
int worker_id = ps::MyRank()*num_threads+customer_id; // a unique id for this worker thread
int N = sros_tr.size();
int N_per_thread = ceil(1.0 * N / num_workers);
vector<int> pi = range(N_per_thread, N_per_thread*worker_id);
ALOG("Worker " << worker_id << " reads data points " << pi[0] << ".." << pi[pi.size()-1]);
std::mt19937 gen_shuffle (model_seed^worker_id);
// replicate all keys on all nodes throughout training
// (sensible only in ablation experiments)
if (enforce_full_replication && customer_id == 0) {
std::vector<Key> keys (num_keys);
std::iota(keys.begin(), keys.end(), 0);
kv.Intent(keys, 0, CLOCK_MAX);
}
kv.WaitSync();
kv.Barrier();
kv.WaitSync();
// Initialize model
kv.BeginSetup();
if (init_parameters != "none" && worker_id == 0) {
vector<Key> keys (num_keys);
std::iota(keys.begin(), keys.end(), 0);
std::mt19937 gen_initial(model_seed);
vector<double> init_vals;
const std::regex uniform_regex("uniform\\{([-0-9\\+\\.e]+)/([-0-9\\+\\.e]+)\\}");
const std::regex normal_regex("normal\\{([-0-9\\+\\.e]+)/([-0-9\\+\\.e]+)\\}");
std::smatch matches;
if (std::regex_match(init_parameters, matches, uniform_regex)) { // uniform distribution
auto low = std::stod(matches[1].str());
auto high = std::stod(matches[2].str());
ALOG("Init model (uniform{" << low << "/" << high <<"}, seed " << model_seed << ") ... ");