-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultivec_old.c
1535 lines (1338 loc) · 52.3 KB
/
multivec_old.c
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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
#include <unistd.h>
#include <assert.h>
#include <libgen.h>
// PATH_MAX
#include <limits.h>
#ifdef PATH_MAX
#define MAX_STRING PATH_MAX // this version is portable to different platforms. http://stackoverflow.com/questions/4109638/what-is-the-safe-alternative-to-realpath
#else
#define MAX_STRING 1000
#endif
#define MAX_LANGS 20
#define EXP_TABLE_SIZE 1000
#define MAX_EXP 6
#define MAX_SENT_LEN 20000
#define MAX_WORD_PER_SENT 1000
#define MAX_CODE_LENGTH 40
const int vocab_hash_size = 30000000; // Maximum 30 * 0.7 = 21M words in the vocabulary
typedef float real; // Precision of float numbers
struct vocab_word {
long long cn;
int *point;
char *word, *code, codelen;
};
// training structure, useful when training embeddings for multiple languages
struct pair_params **all_pairs; //malloc'd later
struct lang_params **all_langs; //malloc'd later
char **language_indices;
struct pair_params *pair; //current pair being used by TrainModelThread
//struct for all info related to a language: vocab, output file, vectors
struct lang_params {
char lang_name[MAX_STRING];
char output_file[MAX_STRING];
char vocab_file[MAX_STRING];
char config_file[MAX_STRING];
struct vocab_word *vocab;
int *vocab_hash;
// syn0: input embeddings (exist for both hierarchical softmax and negative sampling)
// syn1: output embeddings (hierarchical softmax)
// syn1neg: output embeddings (negative sampling)
// table, vocab_size corresponds to the output side.
long long vocab_max_size, vocab_size, total_words;
real *syn0, *syn1, *syn1neg;
int *table;
int full_vocab; //set to 1 once all training files have been read and vocab is complete
long long unk_id; // index of the <unk> word
//pointers to file-related structs
int num_files;
struct file_params **files; //file structs for lang
};
//struct for training file info
struct file_params {
char train_file[MAX_STRING];
long long file_size;
struct lang_params *lang;
long long num_lines; //number of lines
long long *line_blocks; //offsets in each file for each thread (indexed by thread #)
long long train_words; //number of tokens in training file
long long word_count_actual; //current progress in training file
};
//struct for grouping specific language pairs, alignment info
struct pair_params {
struct file_params *src;
struct file_params *tgt;
// alignment info
char align_file[MAX_STRING];
long long align_num_lines;
long long *align_line_blocks;
};
//looping over languages
int ll1;
//looping over language pairs
int lp1;
int binary = 0, debug_mode = 2, min_count = 5, num_threads = 1, min_reduce = 1;
long long layer1_size = 100;
long long classes = 0;
clock_t start;
char prefix[MAX_STRING];
char output_prefix[MAX_STRING]; // output_prefix.lang: stores embeddings
int eval_opt = 0; // evaluation option
long long specified_train_words = 0;
// cbow or skipgram
int cbow = 1, window = 5;
// hierarchical softmax or negative sampling
int hs = 0, negative = 5;
real *expTable;
const int table_size = 1e8;
// training epoch & learning rate
int num_train_iters = 1, cur_iter = 0, start_iter = 0; // run multiple iterations
real alpha = 0.025, starting_alpha;
// monolingual embeddings
real sample = 1e-4;
/** For bilingual embeddings **/
int align_debug = 0;
int align_opt = 0;
real bi_weight = 4.0; // how much we weight the crosslingual predictions. 4 by default, according to Luong et al. 2015
real bi_alpha; // learning rate for crosslingual predictions, set to alpha * bi_weight;
/** End For bilingual embeddings **/
/** For multilingual embeddings **/
int is_multi = 0;
int num_languages = 0;
int num_pairs = 0;
real samples[MAX_LANGS];
//bi weight also applies to multilingual case
/** End For multilingual embeddings**/
/** Debugging code **/
// print stat of a real array
void print_real_array(real* a_syn, long long num_elements, char* name){
float min = 1000000;
float max = -1000000;
float avg = 0;
long long i;
for(i=0; i<num_elements; ++i){
if (a_syn[i]>max) max = a_syn[i];
if (a_syn[i]<min) min = a_syn[i];
avg += a_syn[i];
}
avg /= num_elements;
printf("%s: min=%f, max=%f, avg=%f\n", name, min, max, avg);
}
// print stats of input and output embeddings
void print_model_stat(struct lang_params *params){
printf("# model stats:\n");
print_real_array(params->syn0, params->vocab_size * layer1_size, (char*) " syn0");
if (hs) print_real_array(params->syn1, params->vocab_size * layer1_size, (char*) " syn1");
if (negative) print_real_array(params->syn1neg, params->vocab_size * layer1_size, (char*) " syn1neg");
}
// print a sent
void print_sent(long long* sent, int sent_len, struct vocab_word* vocab, char* name){
int i;
char buf[MAX_SENT_LEN];
char token[MAX_STRING];
sprintf(buf, "%s ", name);
for(i=0; i<sent_len; i++) {
if(i<(sent_len-1)) {
sprintf(token, "%s ", vocab[sent[i]].word);
strcat(buf, token);
} else {
sprintf(token, "%s\n", vocab[sent[i]].word);
strcat(buf, token);
}
}
printf("%s", buf);
fflush(stdout);
}
/** End Debugging code **/
/** Evaluation code **/
void execute(char* command){
//fprintf(stderr, "# Executing: %s\n", command);
system(command);
}
void eval_mono(char* emb_file, char* lang, int iter) {
char command[MAX_STRING];
/** WordSim **/
chdir("wordsim/code");
fprintf(stderr, "# eval %d %s %s", iter, lang, "wordSim");
sprintf(command, "./run_wordSim.sh %s 1 %s", emb_file, lang);
execute(command);
chdir("../..");
/** Analogy **/
if((iter+1)%5==0 && strcmp(lang, "en")==0){
chdir("analogy/code");
fprintf(stderr, "# eval %d %s %s", iter, "en", "analogy");
sprintf(command, "./run_analogy.sh %s 1", emb_file);
execute(command);
chdir("../..");
}
}
// cross-lingual document classification
void cldc(char* outPrefix, int iter) {
char command[MAX_STRING];
/* de2en */
// prepare data
chdir("cldc/scripts/de2en");
sprintf(command, "./prepare-data-klement-4cat-1000-my-embeddings.ch %s", outPrefix); execute(command);
// run perceptron
fprintf(stderr, "# eval %d %s %s", iter, "de2en", "cldc");
sprintf(command, "./run-perceptron-1000-my-embeddings.ch %s > %s.eval%d", outPrefix, output_prefix, iter);
execute(command);
/** en2de **/
// prepare data
chdir("../en2de");
sprintf(command, "./prepare-data-klement-4cat-1000-my-embeddings.ch %s", outPrefix); execute(command);
// run perceptron
fprintf(stderr, "# eval %d %s %s", iter, "en2de", "cldc");
sprintf(command, "./run-perceptron-1000-my-embeddings.ch %s > %s.eval%d", outPrefix, output_prefix, iter);
execute(command);
chdir("../../..");
}
/** End Evaluation code **/
void InitUnigramTable(struct lang_params *params) {
printf("# Init unigram table\n");
int a, i;
long long train_words_pow = 0;
real d1, power = 0.75;
long long vocab_size = params->vocab_size;
struct vocab_word *vocab = params->vocab;
params->table = (int *)malloc(table_size * sizeof(int));
for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power);
i = 0;
d1 = pow(vocab[i].cn, power) / (real)train_words_pow;
for (a = 0; a < table_size; a++) {
params->table[a] = i;
if (a / (real)table_size > d1) {
i++;
d1 += pow(vocab[i].cn, power) / (real)train_words_pow;
}
if (i >= vocab_size) i = vocab_size - 1;
}
}
// Reads a single word from a file, assuming space + tab + EOL to be word boundaries
// Return word length
int ReadWord(char *word, FILE *fin) {
int a = 0, ch;
while (!feof(fin)) {
ch = fgetc(fin);
if (ch == 13) continue;
if ((ch == ' ') || (ch == '\t') || (ch == '\n')) {
if (a > 0) {
if (ch == '\n') ungetc(ch, fin);
break;
}
if (ch == '\n') {
strcpy(word, (char *)"</s>");
return 4;
} else continue;
}
word[a] = ch;
a++;
if (a >= MAX_STRING - 1) a--; // Truncate too long words
}
word[a] = 0;
return a;
}
// Returns hash value of a word
int GetWordHash(char *word) {
unsigned long long a, hash = 0;
for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a];
hash = hash % vocab_hash_size;
return hash;
}
// Returns position of a word in the vocabulary; if the word is not found, returns -1
int SearchVocab(char *word, const struct vocab_word *vocab, const int *vocab_hash) {
// puts(" Searching vocab...");
unsigned int hash = GetWordHash(word);
while (1) {
if (vocab_hash[hash] == -1) return -1;
if (!strcmp(word, vocab[vocab_hash[hash]].word)) {
return vocab_hash[hash];
}
hash = (hash + 1) % vocab_hash_size;
}
// puts(" Done searching vocab.");
return -1;
}
// Reads a word and returns its index in the vocabulary
int ReadWordIndex(FILE *fin, const struct vocab_word *vocab, const int *vocab_hash) {
char word[MAX_STRING];
int word_len = ReadWord(word, fin);
if(word_len >= MAX_STRING - 2) printf("! long word: %s\n", word);
if (feof(fin)) return -1;
return SearchVocab(word, vocab, vocab_hash);
}
// Adds a word to the vocabulary
int AddWordToVocab(char *word, struct lang_params *params) {
// puts("Adding word to vocab");
unsigned int hash, length = strlen(word) + 1;
long long vocab_size = params->vocab_size;
long long vocab_max_size = params->vocab_max_size;
struct vocab_word *vocab = params->vocab;
int *vocab_hash = params->vocab_hash;
if (length > MAX_STRING) length = MAX_STRING;
vocab[vocab_size].word = (char *)calloc(length, sizeof(char));
strcpy(vocab[vocab_size].word, word);
vocab[vocab_size].cn = 0;
vocab_size++;
// Reallocate memory if needed
if (vocab_size + 2 >= vocab_max_size) {
vocab_max_size += 1000;
vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word));
}
hash = GetWordHash(word);
while (vocab_hash[hash] != -1) {
hash = (hash + 1) % vocab_hash_size;
}
vocab_hash[hash] = vocab_size - 1;
params->vocab_size = vocab_size;
params->vocab_max_size = vocab_max_size;
params->vocab = vocab;
return vocab_size - 1;
}
// Used later for sorting by word counts
int VocabCompare(const void *a, const void *b) {
return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn;
}
// Sorts the vocabulary by frequency using word counts
void SortVocab(struct lang_params *params) {
int a, size;
unsigned int hash;
int *vocab_hash = params->vocab_hash;
struct vocab_word *vocab = params->vocab;
long long vocab_size = params->vocab_size;
// Sort the vocabulary and keep </s> at the first position
qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare);
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
size = vocab_size;
params->total_words = 0;
for (a = 0; a < size; a++) {
// Words occuring less than min_count times will be discarded from the vocab
if ((vocab[a].cn < min_count) && (a != 0)){ // a=0 is </s> and we want to keep it.
vocab_size--;
free(vocab[a].word);
} else {
// Hash will be re-computed, as after the sorting it is not actual
hash=GetWordHash(vocab[a].word);
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash] = a;
params->total_words += vocab[a].cn;
}
}
vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word));
// Allocate memory for the binary tree construction
for (a = 0; a < vocab_size; a++) {
vocab[a].code = (char *)calloc(MAX_CODE_LENGTH, sizeof(char));
vocab[a].point = (int *)calloc(MAX_CODE_LENGTH, sizeof(int));
}
params->vocab = vocab;
params->vocab_size = vocab_size;
}
// Reduces the vocabulary by removing infrequent tokens
void ReduceVocab(struct lang_params *params) {
int a, b = 0;
unsigned int hash;
for (a = 0; a < params->vocab_size; a++) if (params->vocab[a].cn > min_reduce) {
params->vocab[b].cn = params->vocab[a].cn;
params->vocab[b].word = params->vocab[a].word;
b++;
} else free(params->vocab[a].word);
params->vocab_size = b;
for (a = 0; a < vocab_hash_size; a++) params->vocab_hash[a] = -1;
for (a = 0; a < params->vocab_size; a++) {
// Hash will be re-computed, as it is not actual
hash = GetWordHash(params->vocab[a].word);
while (params->vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
params->vocab_hash[hash] = a;
}
fflush(stdout);
min_reduce++;
}
// Create binary Huffman tree using the word counts
// Frequent words will have short uniqe binary codes
void CreateBinaryTree(struct lang_params *params) {
long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH];
char code[MAX_CODE_LENGTH];
long long *count = (long long *)calloc(params->vocab_size * 2 + 1, sizeof(long long));
long long *binary = (long long *)calloc(params->vocab_size * 2 + 1, sizeof(long long));
long long *parent_node = (long long *)calloc(params->vocab_size * 2 + 1, sizeof(long long));
for (a = 0; a < params->vocab_size; a++) count[a] = params->vocab[a].cn;
for (a = params->vocab_size; a < params->vocab_size * 2; a++) count[a] = 1e15;
pos1 = params->vocab_size - 1;
pos2 = params->vocab_size;
// Following algorithm constructs the Huffman tree by adding one node at a time
for (a = 0; a < params->vocab_size - 1; a++) {
// First, find two smallest nodes 'min1, min2'
if (pos1 >= 0) {
if (count[pos1] < count[pos2]) {
min1i = pos1;
pos1--;
} else {
min1i = pos2;
pos2++;
}
} else {
min1i = pos2;
pos2++;
}
if (pos1 >= 0) {
if (count[pos1] < count[pos2]) {
min2i = pos1;
pos1--;
} else {
min2i = pos2;
pos2++;
}
} else {
min2i = pos2;
pos2++;
}
count[params->vocab_size + a] = count[min1i] + count[min2i];
parent_node[min1i] = params->vocab_size + a;
parent_node[min2i] = params->vocab_size + a;
binary[min2i] = 1;
}
// Now assign binary code to each vocabulary word
for (a = 0; a < params->vocab_size; a++) {
b = a;
i = 0;
while (1) {
code[i] = binary[b];
point[i] = b;
i++;
b = parent_node[b];
if (b == params->vocab_size * 2 - 2) break;
}
params->vocab[a].codelen = i;
params->vocab[a].point[0] = params->vocab_size - 2;
for (b = 0; b < i; b++) {
params->vocab[a].code[i - b - 1] = code[b];
params->vocab[a].point[i - b] = point[b] - params->vocab_size;
}
}
free(count);
free(binary);
free(parent_node);
}
void CountWordsFromTrainFile(struct file_params *params) {
char word[MAX_STRING];
FILE *fin;
if (debug_mode > 0) printf("# Count words from %s\n", params->train_file);
fin = fopen(params->train_file, "rb");
if (fin == NULL) {
printf("ERROR: training data file not found!\n");
exit(1);
}
while (1) {
//puts("Reading word");
//printf("Debug mode: %d\n", debug_mode);
//printf("File size: %lld\n", params->file_size);
ReadWord(word, fin);
if (feof(fin)) break;
params->train_words++;
if ((debug_mode > 1) && (params->train_words % 100000 == 0)) {
printf("%lldK%c", params->train_words / 1000, 13);
fflush(stdout);
}
}
if (debug_mode > 0) {
printf(" Words in train file: %lld\n", params->train_words);
}
params->file_size = ftell(fin);
fclose(fin);
}
void LearnVocabFromTrainFiles(struct lang_params *params) {
//this does not remove any previous vocab-related info in params, but updates it if the new file
// has new information
char word[MAX_STRING];
FILE *fin;
long long a, i;
for (a = 0; a < vocab_hash_size; a++) params->vocab_hash[a] = -1;
puts("Vocabulary set to -1");
for (ll1=0; ll1 < (params->num_files); ll1++) {
struct file_params *file = params->files[ll1];
if (debug_mode > 0) {
printf("# Learn vocab for %s from %s (file %d of %d)\n", params->lang_name, file->train_file, ll1+1, params->num_files);
}
fin = fopen(file->train_file, "rb");
if (fin == NULL) {
printf("ERROR: training data file not found!\n");
exit(1);
}
params->vocab_size = 0;
AddWordToVocab((char *)"</s>", params);
while (1) {
ReadWord(word, fin);
if (feof(fin)) break;
file->train_words++;
if ((debug_mode > 1) && (file->train_words % 100000 == 0)) {
printf("%lldK%c", file->train_words / 1000, 13);
fflush(stdout);
}
i = SearchVocab(word, params->vocab, params->vocab_hash);
if (i == -1) {
a = AddWordToVocab(word, params);
params->vocab[a].cn = 1;
} else params->vocab[i].cn++;
if (params->vocab_size > vocab_hash_size * 0.7) ReduceVocab(params);
}
SortVocab(params);
if (debug_mode > 0) {
printf("\n");
printf(" Vocab size: %lld\n", params->vocab_size);
printf(" Words in train file: %lld\n", file->train_words);
}
file->file_size = ftell(fin);
fclose(fin);
}
printf("Finished learning vocab for language %s\n", params->lang_name);
params->full_vocab = 1;
}
void SaveVocab(struct lang_params *params) {
long long i;
FILE *fo = fopen(params->vocab_file, "wb");
for (i = 0; i < params->vocab_size; i++) fprintf(fo, "%s %lld\n", params->vocab[i].word, params->vocab[i].cn);
fclose(fo);
}
void ReadVocab(struct lang_params *params) {
long long a, i = 0;
char c;
char word[MAX_STRING];
FILE *fin = fopen(params->vocab_file, "rb");
if (fin == NULL) {
printf("Vocabulary file not found\n");
exit(1);
}
for (a = 0; a < vocab_hash_size; a++) params->vocab_hash[a] = -1;
params->vocab_size = 0;
while (1) {
ReadWord(word, fin);
if (feof(fin)) break;
a = AddWordToVocab(word, params);
fscanf(fin, "%lld%c", ¶ms->vocab[a].cn, &c);
i++;
}
SortVocab(params);
if (debug_mode > 0) {
printf("Vocab size: %lld\n", params->vocab_size);
// printf("Words in train file: %lld\n", params->train_words);
}
//this doesn't seem to have anything to do wth the vocab, should be moved
// fin = fopen(params->train_files[0], "rb");
// if (fin == NULL) {
// printf("ERROR: training data file not found!\n");
// exit(1);
// }
// fseek(fin, 0, SEEK_END);
// params->file_size = ftell(fin);
// fclose(fin);
}
// To find split points in a file, so that later each thread can handle one chunk of the data
void ComputeBlockStartPoints(char* file_name, int num_blocks, long long **blocks, long long *num_lines) {
printf("# ComputeBlockStartPoints %s, num_blocks=%d\n", file_name, num_blocks);
long long block_size;
int line_count = 0;
int curr_block = 0;
char line[MAX_SENT_LEN];
FILE *file;
*num_lines = 0;
file = fopen(file_name, "r");
while (1) {
fgets(line, MAX_SENT_LEN, file);
if (feof(file)) break;
++(*num_lines);
}
printf(" num_lines=%lld, eof position %lld\n", *num_lines, (long long) ftell(file));
fseek(file, 0, SEEK_SET);
block_size = (*num_lines - 1) / num_blocks + 1;
printf(" block_size=%lld lines\n blocks = [0", block_size);
*blocks = malloc((num_blocks+1) * sizeof(long long));
(*blocks)[0] = 0;
curr_block = 0;
long long int cur_size = 0;
while (1) {
fgets(line, MAX_SENT_LEN, file);
line_count++;
cur_size++;
// done with a block or reach eof
if (cur_size == block_size || line_count==(*num_lines)) {
curr_block++;
(*blocks)[curr_block] = (long long)ftell(file);
printf(" %lld", (*blocks)[curr_block]);
if (line_count==(*num_lines)) { // eof
break;
}
// reset
cur_size = 0;
}
}
printf("]\n");
assert(curr_block==num_blocks);
assert(line_count==(*num_lines));
fclose(file);
}
// neu1: avg context embedding
// syn0: input embeddings (both hs and negative)
// syn1: output node embeddings (hs)
// syn1neg: output embeddings (negative)
// neu1: hidden vector
// neu1e: hidden vector error
void ProcessSkipPair(long long in_word, long long out_word, unsigned long long *next_random,
struct lang_params *in_params, struct lang_params *out_params, real *neu1e, real skip_alpha) {
long long d;
long long l1, l2, c, target, label;
real f, g;
#ifdef DEBUG
printf(" skip %s -> %s\n", in_params->vocab[in_word].word, out_params->vocab[out_word].word); fflush(stdout);
#endif
l1 = in_word * layer1_size;
for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
// HIERARCHICAL SOFTMAX
if (hs) for (d = 0; d < out_params->vocab[out_word].codelen; d++) {
f = 0;
l2 = out_params->vocab[out_word].point[d] * layer1_size;
// Propagate hidden -> output
for (c = 0; c < layer1_size; c++) f += in_params->syn0[c + l1] * out_params->syn1[c + l2];
if (f <= -MAX_EXP) continue;
else if (f >= MAX_EXP) continue;
else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
// 'g' is the gradient multiplied by the learning rate
g = (1 - out_params->vocab[out_word].code[d] - f) * skip_alpha;
// Propagate errors output -> hidden
for (c = 0; c < layer1_size; c++) neu1e[c] += g * out_params->syn1[c + l2];
// Learn weights hidden -> output
for (c = 0; c < layer1_size; c++) out_params->syn1[c + l2] += g * in_params->syn0[c + l1];
}
// NEGATIVE SAMPLING
if (negative > 0) for (d = 0; d < negative + 1; d++) {
if (d == 0) {
target = out_word;
label = 1;
} else {
*next_random = (*next_random) * (unsigned long long)25214903917 + 11;
target = out_params->table[((*next_random) >> 16) % table_size];
if (target == 0) target = (*next_random) % (out_params->vocab_size - 1) + 1;
if (target == out_word) continue;
label = 0;
}
l2 = target * layer1_size;
f = 0;
for (c = 0; c < layer1_size; c++) f += in_params->syn0[c + l1] * out_params->syn1neg[c + l2];
if (f > MAX_EXP) g = (label - 1) * skip_alpha;
else if (f < -MAX_EXP) g = (label - 0) * skip_alpha;
else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * skip_alpha;
for (c = 0; c < layer1_size; c++) neu1e[c] += g * out_params->syn1neg[c + l2];
for (c = 0; c < layer1_size; c++) out_params->syn1neg[c + l2] += g * in_params->syn0[c + l1];
}
// Learn weights input -> hidden
for (c = 0; c < layer1_size; c++) in_params->syn0[c + l1] += neu1e[c];
}
/** Monolingual predictions **/
// side = 0 ---> src
// side = 1 ---> tgt
// neu1: cbow, hidden vectors
// neu1e: skipgram
// syn0: input embeddings (both hs and negative)
// syn1: output embeddings (hs)
// syn1neg: output embeddings (negative)
void ProcessSentence(int sentence_length, long long *sen, struct lang_params *src, unsigned long long *next_random, real *neu1, real *neu1e) {
int a, b, c, sentence_position;
long long out_word, in_word;
for (sentence_position = 0; sentence_position < sentence_length; ++sentence_position) {
out_word = sen[sentence_position];
if (out_word == -1) continue;
for (c = 0; c < layer1_size; c++) neu1[c] = 0;
for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
*next_random = (*next_random) * (unsigned long long)25214903917 + 11;
b = (*next_random) % window;
if (cbow) { //train the cbow architecture
(void)0;
// ProcessCbow(sentence_position, sentence_length, sen, out_word, b, next_random, src, src, neu1, neu1e);
} else { //train skip-gram
for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
c = sentence_position - window + a; // sentence - (window - b) -> sentence + (window - b)
if (c < 0) continue;
if (c >= sentence_length) continue;
in_word = sen[c];
if (in_word == -1) continue;
ProcessSkipPair(in_word, out_word, next_random, src, src, neu1e, alpha);
} // for a (skipgram)
} // end if cbow
} // sentence
}
/** Crosslingual predictions **/
void ProcessSentenceAlign(struct lang_params *src, long long src_word, int src_pos, //int *tgt_id_map,
struct lang_params *tgt, long long* tgt_sent, int tgt_len, int tgt_pos,
unsigned long long *next_random, real *neu1, real *neu1e) {
int neighbor_pos, a;
//int neighbor_pos, neighbor_count;
real b;
// get the range
(*next_random) = (*next_random) * (unsigned long long)25214903917 + 11;
b = (*next_random) % window;
#ifdef DEBUG
long long tgt_word = tgt_sent[tgt_pos];
printf(" align %s (%d) - %s (%d)\n", src->vocab[src_word].word, src_pos, tgt->vocab[tgt_word].word, tgt_pos);
fflush(stdout);
#endif
if (cbow) { // cbow
// tgt -> src
(void)0;
// ProcessCbow(tgt_pos, tgt_len, tgt_sent, src_word, b, next_random, tgt, src, neu1, neu1e);
} else { // skip-gram
for (a = b; a < window * 2 + 1 - b; ++a) if (a != window) {
// src -> tgt neighbor
neighbor_pos = tgt_pos -window + a;
if (neighbor_pos >= 0 && neighbor_pos < tgt_len) {
ProcessSkipPair(src_word, tgt_sent[neighbor_pos], next_random, src, tgt, neu1e, bi_alpha);
}
}
} // end for if (cbow)
}
void *TrainModelThread(void *id) {
puts("Start TrainModelThread");
long long word;
int src_sentence_length = 0, tgt_sentence_length = 0;
long long src_word_count = 0, src_last_word_count = 0, src_sen[MAX_WORD_PER_SENT + 1];
long long tgt_word_count = 0, tgt_sen[MAX_WORD_PER_SENT + 1];
unsigned long long next_random = (long long)id;
clock_t now;
FILE *src_fi = NULL, *tgt_fi = NULL, *align_fi=NULL;
long long int sent_id = 0;
struct file_params *src_train = pair->src;
struct file_params *tgt_train = pair->tgt;
struct lang_params *src_lang = src_train->lang;
struct lang_params *tgt_lang = tgt_train->lang;
// for align
int src_sentence_orig_length=0, tgt_sentence_orig_length=0;
int src_id_map[MAX_WORD_PER_SENT + 1], tgt_id_map[MAX_WORD_PER_SENT + 1]; // map from original indices to new indices if id_map[j]==0, word j is deleted
long long src_sen_orig[MAX_WORD_PER_SENT + 1], tgt_sen_orig[MAX_WORD_PER_SENT + 1];
int src_align_map[MAX_WORD_PER_SENT + 1]; // map from src positions to tgt positions and vice versa
int count;
int src_pos, tgt_pos;
char ch;
real *neu1 = (real *)calloc(layer1_size, sizeof(real)); // cbow
real *neu1e = (real *)calloc(layer1_size, sizeof(real)); // skipgram
long long all_tgt_words = 0;
long long all_src_words = 0;
// src
src_fi = fopen(src_train->train_file, "rb");
fseek(src_fi, src_train->line_blocks[(long long)id], SEEK_SET);
// tgt
tgt_fi = fopen(tgt_train->train_file, "rb");
fseek(tgt_fi, tgt_train->line_blocks[(long long)id], SEEK_SET);
// align
if(align_opt){
align_fi = fopen(pair->align_file, "rb");
fseek(align_fi, pair->align_line_blocks[(long long)id], SEEK_SET);
}
while (1) {
#ifdef DEBUG
printf("# Load sentence %lld, src_word_count %lld, src_last_word_count %lld\n", sent_id, src_word_count, src_last_word_count); fflush(stdout);
printf(" src, sample=%g, dropping words:", sample); fflush(stdout);
#endif
if (src_word_count - src_last_word_count > 10000) {
src_train->word_count_actual += src_word_count - src_last_word_count;
src_last_word_count = src_word_count;
if ((debug_mode > 1)) {
now=clock();
printf("%cAlpha: %f, bi_alpha: %f, Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha, bi_alpha,
(src_train->word_count_actual)/ (real)(num_threads * src_train->train_words + 1) * 100,
src_train->word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));
fflush(stdout);
}
alpha = starting_alpha * (1 - (cur_iter * src_train->train_words + src_train->word_count_actual) / (real)(num_train_iters * src_train->train_words + 1));
if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;
bi_alpha = alpha*bi_weight;
}
// load src sentence
src_sentence_length = 0;
src_sentence_orig_length = 0;
while (1) {
word = ReadWordIndex(src_fi, src_lang->vocab, src_lang->vocab_hash);
all_src_words++;
if (feof(src_fi) || word == 0) break; // end of file or sentence
if(src_sentence_orig_length>=MAX_WORD_PER_SENT) continue; // read enough
// keep the orig src
if (word==-1) src_sen_orig[src_sentence_orig_length] = src_lang->unk_id;
else src_sen_orig[src_sentence_orig_length] = word;
src_sentence_orig_length++;
// unknown token. IMPORTANT: this line needs to be after the one where we store src_sen_orig (for bilingual models to work)
if (word == -1) {
src_id_map[src_sentence_orig_length-1] = -1;
continue;
}
src_word_count++;
// The subsampling randomly discards frequent words while keeping the ranking same
if (sample > 0) {
// larger sample means larger ran, which means discard less frequent
// [ sqrt(freq) / sqrt(sample * N) + 1 ] * (sample * N / freq) = sqrt(sample * N / freq) + (sample * N / freq)
real ran = (sqrt(src_lang->vocab[word].cn / (sample * src_train->train_words)) + 1) * (sample * src_train->train_words) / src_lang->vocab[word].cn;
next_random = next_random * (unsigned long long)25214903917 + 11;
if (ran < (next_random & 0xFFFF) / (real)65536) { // discard
#ifdef DEBUG
printf(" %s", src_lang->vocab[word].word);
#endif
src_id_map[src_sentence_orig_length-1] = -1;
continue;
} else {
src_id_map[src_sentence_orig_length-1] = src_sentence_length;
}
}
src_sen[src_sentence_length] = word;
src_sentence_length++;
}
#ifdef DEBUG
sprintf(prefix, "\n src orig %lld, len %d:", sent_id, src_sentence_orig_length);
print_sent(src_sen_orig, src_sentence_orig_length, src_lang->vocab, prefix);
sprintf(prefix, " src %lld, len %d:", sent_id, src_sentence_length);
print_sent(src_sen, src_sentence_length, src_lang->vocab, prefix);
printf("Press enter to continue:");
getchar();
#endif
ProcessSentence(src_sentence_length, src_sen, src_lang, &next_random, neu1, neu1e);
// load tgt sentence
tgt_sentence_length = 0;
tgt_sentence_orig_length = 0;
#ifdef DEBUG
printf(" tgt, sample=%g, dropping words:", sample); fflush(stdout);
#endif
while (1) {
word = ReadWordIndex(tgt_fi, tgt_lang->vocab, tgt_lang->vocab_hash);
all_tgt_words++;
if (feof(tgt_fi) || word == 0) break; // end of file or sentence
if(tgt_sentence_orig_length>=MAX_WORD_PER_SENT) continue; // read enough
// keep the orig tgt
if (word==-1) tgt_sen_orig[tgt_sentence_orig_length] = tgt_lang->unk_id;
else tgt_sen_orig[tgt_sentence_orig_length] = word;
tgt_sentence_orig_length++;
// unknown token. IMPORTANT: this line needs to be after the one where we store sen_orig for bilingual models to work
if (word == -1) {
tgt_id_map[tgt_sentence_orig_length-1] = -1;
continue;
}
tgt_word_count++;
// The subsampling randomly discards frequent words while keeping the ranking same
if (sample > 0) {
real ran = (sqrt(tgt_lang->vocab[word].cn / (sample * tgt_train->train_words)) + 1) * (sample * tgt_train->train_words) / tgt_lang->vocab[word].cn;
next_random = next_random * (unsigned long long)25214903917 + 11;
if (ran < (next_random & 0xFFFF) / (real)65536) {
#ifdef DEBUG
printf(" %s", tgt_lang->vocab[word].word); fflush(stdout);
#endif
tgt_id_map[tgt_sentence_orig_length-1] = -1;
continue;
} else {
tgt_id_map[tgt_sentence_orig_length-1] = tgt_sentence_length;
}
}
tgt_sen[tgt_sentence_length] = word;
tgt_sentence_length++;
}
#ifdef DEBUG
sprintf(prefix, "\n tgt orig %lld, len %d:", sent_id, tgt_sentence_orig_length);
print_sent(tgt_sen_orig, tgt_sentence_orig_length, tgt_lang->vocab, prefix);
sprintf(prefix, " tgt %lld, len %d:", sent_id, tgt_sentence_length);
print_sent(tgt_sen, tgt_sentence_length, tgt_lang->vocab, prefix);
printf("Press enter to continue:");
getchar();
#endif
ProcessSentence(tgt_sentence_length, tgt_sen, tgt_lang, &next_random, neu1, neu1e);
if (feof(tgt_fi)) {
printf("End of target file\n");
break;
}
if (tgt_word_count > tgt_train->train_words / num_threads) {
printf("Exceeded target words per thread: %lld / %lld with %d threads\n", tgt_word_count, tgt_train->train_words, num_threads);
break;
}
// align
if (align_opt) { // use unsupervised alignments (UnsupAlign)
#ifdef DEBUG
printf("Using unsupervised alignments.\n");
#endif
for (src_pos = 0; src_pos < src_sentence_orig_length; ++src_pos) src_align_map[src_pos] = -1;
while (fscanf(align_fi, "%d %d%c", &src_pos, &tgt_pos, &ch)) {
src_align_map[src_pos] = tgt_pos;
if (ch == '\n') break;
}
for (src_pos = 0; src_pos < src_sentence_orig_length; ++src_pos) {
if(src_id_map[src_pos]==-1) continue;
// get tgt_pos
if(src_align_map[src_pos]==-1){ // no alignment, try to infer
count = 0;
tgt_pos = 0;
if(src_pos>0 && src_align_map[src_pos-1]!=-1){ // previous link
tgt_pos += src_align_map[src_pos-1];
count++;
}
if(src_pos<(src_sentence_orig_length-1) && src_align_map[src_pos+1]!=-1){ // next link
tgt_pos += src_align_map[src_pos+1];
count++;
}
if (count>0) tgt_pos = tgt_pos / count;