forked from robertostling/eflomal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheflomal.c
1381 lines (1268 loc) · 50.6 KB
/
eflomal.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 <stdint.h>
#include <unistd.h>
#include <inttypes.h>
#include <assert.h>
#include <time.h>
#include <omp.h>
#ifndef EXACT_MATH
#include "simd_math_prims.h"
#define expf expapprox
#define logf logapprox
#define powf(x,y) expf(logf(x)*y)
#endif
#define PRIlink PRIu16
#define SCNlink SCNu16
#define PRItoken PRIu32
#define SCNtoken SCNu32
typedef uint16_t link_t;
typedef uint32_t token;
#define NULL_LINK 0xffffU
#define JUMP_ALPHA 0.5
#define FERT_ALPHA 0.5
#define LEX_ALPHA 0.001
#define NULL_ALPHA 0.001
#ifndef DOUBLE_PRECISION
#define COUNT_BITS 32
typedef float count;
#else
#define COUNT_BITS 64
typedef double count;
#endif
// size of the jump statistics array for the HMM model
#define JUMP_ARRAY_LEN 0x800
#define JUMP_SUM (JUMP_ARRAY_LEN-1)
// estimated maximum jump (approximately, will be used for normalization only)
#define JUMP_MAX_EST 100.0
// size of the fertility statistics array (note that there is one such
// distribution per word type, so we need to be a bit strict about its size)
#define FERT_ARRAY_LEN 0x08
// maximum size of sentences (for fixed-size buffers)
#define MAX_SENT_LEN 0x400
#include "random.c"
#include "hash.c"
// these control the threshold of the map data structures (linear lookup vs
// hash table).
// Must be 0 or 2^n-1 (for some n >= 2), where 0 means that linear lookup is
// never used.
#define MAX_FIXED 0
#define MAKE_NAME(NAME) map_token_u32 ## NAME
#define INDEX_TYPE size_t
#define KEY_TYPE token
#define VALUE_TYPE uint32_t
#define EMPTY_KEY ((token)0xffffffffUL)
#define HASH_KEY hash_u32_u32
#include "natmap.c"
#define MIN(x,y) (((x)<(y))?(x):(y))
#define MAX(x,y) (((x)>(y))?(x):(y))
struct sentence {
link_t length;
token tokens[];
};
struct text {
char *filename;
size_t n_sentences;
token vocabulary_size;
struct sentence **sentences;
};
struct text_alignment {
int model;
const struct text *source;
const struct text *target;
link_t **sentence_links;
link_t *buf;
struct map_token_u32 *source_prior;
count *source_prior_sum;
int has_jump_prior;
count jump_prior[JUMP_ARRAY_LEN];
count *fert_prior;
struct map_token_u32 *source_count;
count *inv_source_count_sum;
count jump_counts[JUMP_ARRAY_LEN];
count *fert_counts;
// this number of sentences contain clean parallel data and should
// contribute to the statistics (anything after this should still be
// aligned, but don't trust the statistics):
size_t n_clean; // 0 (the default) means all sentences should be used
count null_prior;
};
double seconds(void) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return 1e-9*(double)ts.tv_nsec + (double)ts.tv_sec;
}
void text_alignment_free(struct text_alignment *ta) {
if (ta->source_prior != NULL) {
for (size_t i=0; i<ta->source->vocabulary_size; i++)
map_token_u32_clear(ta->source_prior + i);
free(ta->source_prior);
free(ta->source_prior_sum);
}
if (ta->fert_prior != NULL) {
free(ta->fert_prior);
}
for (size_t i=0; i<ta->source->vocabulary_size; i++)
map_token_u32_clear(ta->source_count + i);
free(ta->source_count);
free(ta->inv_source_count_sum);
free(ta->sentence_links);
free(ta->buf);
free(ta->fert_counts);
free(ta);
}
void text_alignment_write_moses(
const struct text_alignment *ta, FILE *file, int reverse) {
for (size_t sent=0; sent<ta->target->n_sentences; sent++) {
if (ta->target->sentences[sent] == NULL ||
ta->source->sentences[sent] == NULL) {
fputc('\n', file);
} else {
size_t length = ta->target->sentences[sent]->length;
const link_t *links = ta->sentence_links[sent];
int first = 1;
for (size_t j=0; j<length; j++) {
if (links[j] != NULL_LINK) {
if (reverse) {
fprintf(file, first? "%d-%d": " %d-%d",
(int)j, (int)links[j]);
} else {
fprintf(file, first? "%d-%d": " %d-%d",
(int)links[j], (int)j);
}
first = 0;
}
}
fputc('\n', file);
}
}
}
//void text_alignment_write_vocab(const struct text_alignment *ta, FILE *file) {
// fprintf(file, "%u %u\n",
// ta->source->vocabulary_size-1, ta->target->vocabulary_size-1);
// for (size_t e=1; e<ta->source->vocabulary_size; e++) {
// struct map_token_u32 *sc = ta->source_count + e;
// token fs[sc->n_items];
// uint32_t ns[sc->n_items];
// map_token_u32_items(sc, fs, ns);
// fprintf(file, "%zd", sc->n_items);
// for (size_t i=0; i<sc->n_items; i++) {
// if (fs[i] == 0) {
// perror("text_alignment_write_vocab(): target type id == 0");
// exit(1);
// }
// fprintf(file, " %"PRItoken" %"PRIu32, fs[i]-1, ns[i]);
// }
// fprintf(file, "\n");
// }
//}
void text_alignment_write_stats(const struct text_alignment *ta, FILE *file) {
// Total number of non-zero (e, f) pairs
//size_t n_priors = 0;
//for (size_t e=0; e<ta->source->vocabulary_size; e++)
// n_priors += ta->source_count[e].n_items;
//fprintf(file, "%"PRItoken" %"PRItoken" %zd\n",
// ta->source->vocabulary_size, ta->target->vocabulary_size,
// n_priors);
//for (token e=0; e<ta->source->vocabulary_size; e++) {
// size_t k = ta->source_count[e].n_items;
// token fs[k];
// uint32_t ns[k];
// map_token_u32_items(ta->source_count + e, fs, ns);
// for (size_t i=0; i<k; i++)
// fprintf(file, "%"PRItoken" %"PRItoken" %"PRIu32"\n",
// e, fs[i], ns[i]);
//}
fprintf(file, "%d\n", JUMP_ARRAY_LEN);
for (size_t i=0; i<JUMP_ARRAY_LEN; i++) {
fprintf(file, "%d\n", (int)roundf(ta->jump_counts[i]-JUMP_ALPHA));
}
}
// Get the index of the jump distribution parameter vector for a jump from
// position i to j (in a sentence with total length len)
inline static size_t get_jump_index(int i, int j, int len) {
return (size_t)MAX(0, MIN(JUMP_ARRAY_LEN-1, j - i + JUMP_ARRAY_LEN/2));
}
inline static size_t get_fert_index(size_t e, int fert) {
return e*FERT_ARRAY_LEN + (size_t)MIN(fert, FERT_ARRAY_LEN-1);
}
void text_alignment_sample(
struct text_alignment *ta, random_state *state,
count *sentence_scores, struct text_alignment **tas,
int n_samplers) {
const int n_samples = 1;
const int argmax = tas != NULL;
const int model = ta->model;
struct sentence **source_sentences = ta->source->sentences;
struct sentence **target_sentences = ta->target->sentences;
// probability distribution to sample from
count ps[MAX_SENT_LEN+1];
// fertility of tokens in sentence
int fert[MAX_SENT_LEN];
count *jump_counts = ta->jump_counts;
count *fert_counts = ta->fert_counts;
const size_t n_sentences =
ta->n_clean? ta->n_clean: ta->target->n_sentences;
// the fertility distributions (unlike the jump and lexical distributions)
// are sampled explicitly, and the categorical distributions are fixed
// throughout the iteration.
if (model >= 3) {
size_t *e_count = malloc(sizeof(size_t)*ta->source->vocabulary_size);
if (e_count == NULL) {
perror("text_alignment_sample(): unable to allocate e_count");
exit(1);
}
for (size_t i=0; i<ta->source->vocabulary_size; i++)
e_count[i] = 0;
if (ta->fert_prior != NULL) {
// TODO: decide on whether to add FERT_ALPHA
// TODO: 0 or 1-based? NULL included?
for (size_t i=0; i<FERT_ARRAY_LEN*ta->source->vocabulary_size; i++)
{
fert_counts[i] = ta->fert_prior[i] + (count) FERT_ALPHA;
}
} else {
for (size_t i=0; i<FERT_ARRAY_LEN*ta->source->vocabulary_size; i++)
fert_counts[i] = (count) FERT_ALPHA;
}
// go through the text and compute fertility statistics
for (size_t sent=0; sent<n_sentences; sent++) {
link_t *links = ta->sentence_links[sent];
// in case this sentence pair should not be aligned, skip it
if (links == NULL) continue;
const struct sentence *source_sentence = source_sentences[sent];
const struct sentence *target_sentence = target_sentences[sent];
const size_t source_length = source_sentence->length;
const size_t target_length = target_sentence->length;
const token *source_tokens = source_sentence->tokens;
for (size_t i=0; i<source_length; i++)
fert[i] = 0;
for (size_t j=0; j<target_length; j++)
if (links[j] != NULL_LINK)
fert[links[j]]++;
for (size_t i=0; i<source_length; i++) {
e_count[source_tokens[i]]++;
fert_counts[get_fert_index(source_tokens[i], fert[i])] += 1.0;
}
}
// sample a categorical fertility distribution from the posterior
// for each source word e.
//
// since we only ever want to use
// P(phi(i)) / P(phi(i)-1)
// position i directly stores this value.
// Index 0 is undefined, and the maximum value contains a very
// low probability (because it should never be used).
for (token e=1; e<ta->source->vocabulary_size; e++) {
// skip vocabulary items that do not actually occur in this text
if (e_count[e] == 0) continue;
count alpha[FERT_ARRAY_LEN];
count *buf = fert_counts + get_fert_index(e, 0);
memcpy(alpha, buf, FERT_ARRAY_LEN*sizeof(count));
#if COUNT_BITS == 32
random_dirichlet32_unnormalized(state, FERT_ARRAY_LEN, alpha, buf);
#else
random_dirichlet64_unnormalized(state, FERT_ARRAY_LEN, alpha, buf);
#endif
buf[FERT_ARRAY_LEN-1] = (count) 1e-10;
for (size_t i=FERT_ARRAY_LEN-2; i; i--)
buf[i] /= buf[i-1];
}
free(e_count);
}
count *acc_ps = NULL;
if (argmax) acc_ps = malloc(MAX_SENT_LEN*(MAX_SENT_LEN+1)*sizeof(count));
// aa_jp1_table[j] will contain the alignment of the nearest non-NULL
// aligned word to the right (or source_sentence->length if there is no
// such word)
int aa_jp1_table[MAX_SENT_LEN];
int aa_jp1;
for (size_t sent=0; sent<ta->target->n_sentences; sent++) {
link_t *links = ta->sentence_links[sent];
// in case this sentence pair should not be aligned, skip it
if (links == NULL) continue;
const struct sentence *source_sentence = source_sentences[sent];
const struct sentence *target_sentence = target_sentences[sent];
const size_t source_length = source_sentence->length;
const size_t target_length = target_sentence->length;
const token *source_tokens = source_sentence->tokens;
const token *target_tokens = target_sentence->tokens;
int samples_left = n_samples-1;
int samplers_left = n_samplers-1;
if (argmax) {
for (size_t k=0; k<target_length*(source_length+1); k++)
acc_ps[k] = (count) 0.0;
}
// This is the head of a loop (look for gotos below) which iterates
// n_samples * n_samplers times, accumulating distributions from the
// independent samplers.
resample:;
if (tas != NULL) ta = tas[samplers_left];
size_t acc_base = 0;
links = ta->sentence_links[sent];
// if HMM model is used:
if (model >= 2) {
// initialize table of nearest non-NULL alignment to the right
aa_jp1 = source_length;
for (size_t j=target_length; j>0; j--) {
aa_jp1_table[j-1] = aa_jp1;
if (links[j-1] != NULL_LINK) aa_jp1 = links[j-1];
}
}
// if fertility model is used:
if (model >= 3) {
// compute fertilities of the tokens in this sentence
for (size_t i=0; i<source_length; i++)
fert[i] = 0;
for (size_t j=0; j<target_length; j++)
if (links[j] != NULL_LINK)
fert[links[j]]++;
}
// aa_jm1 will always contain the alignment of the nearest non-NULL
// aligned word to the left (or -1 if there is no such word)
int aa_jm1 = -1;
for (size_t j=0; j<target_length; j++) {
const token f = target_tokens[j];
const link_t old_i = links[j];
token old_e;
aa_jp1 = aa_jp1_table[j];
if(old_i == NULL_LINK) {
old_e = 0;
} else {
old_e = source_tokens[old_i];
if (model >= 3)
fert[old_i]--;
}
uint32_t reduced_count = 0;
if (sent < n_sentences) {
ta->inv_source_count_sum[old_e] =
(count)1.0
/ ((count)1.0/ta->inv_source_count_sum[old_e] -
(count)1.0);
reduced_count =
map_token_u32_add(ta->source_count + old_e, f, -1);
if (reduced_count & 0x80000000UL) {
fprintf(stderr,
"old_e = %"PRItoken", n_items = %zd, dynamic = %u\n",
old_e, (size_t)ta->source_count[old_e].n_items,
map_token_u32_is_dynamic(ta->source_count + old_e));
}
assert ((reduced_count & 0x80000000UL) == 0);
}
size_t skip_jump = 0;
if (model >= 2) {
skip_jump = get_jump_index(
aa_jm1, aa_jp1, source_length);
}
if (model >= 2 && sent < n_sentences) {
if (links[j] == NULL_LINK) {
// if this target token is NULL aligned, only one jump
// needs to be removed from the statistics:
jump_counts[JUMP_SUM] -= (count) 1.0;
jump_counts[skip_jump] -= (count) 1.0;
} else {
// otherwise, there are two jumps:
const size_t old_jump1 = get_jump_index(
aa_jm1, links[j], source_length);
const size_t old_jump2 = get_jump_index(
links[j], aa_jp1, source_length);
jump_counts[JUMP_SUM] -= (count) 2.0;
jump_counts[old_jump1] -= (count) 1.0;
jump_counts[old_jump2] -= (count) 1.0;
}
}
count ps_sum = 0.0;
uint32_t null_n = 0;
map_token_u32_get(ta->source_count + 0, f, &null_n);
// for speed, we use separate versions of the inner loop depending
// on the model used (in spite of the code redundancy)
if (model >= 3) {
size_t jump1 = get_jump_index(
aa_jm1, 0, source_length);
size_t jump2 = get_jump_index(
0, aa_jp1, source_length);
for (size_t i=0; i<source_length; i++) {
const token e = source_tokens[i];
const size_t fert_idx = get_fert_index(e, fert[i]+1);
uint32_t n = 0;
map_token_u32_get(ta->source_count + e, f, &n);
if (ta->source_prior != NULL) {
float alpha = 0.0f;
map_token_u32_get(ta->source_prior + e, f,
(uint32_t*)&alpha);
alpha += LEX_ALPHA;
ps_sum += ta->inv_source_count_sum[e] *
((count)alpha + (count)n) *
jump_counts[jump1] * jump_counts[jump2] *
fert_counts[fert_idx];
} else {
ps_sum += ta->inv_source_count_sum[e] *
(LEX_ALPHA + (count)n) *
jump_counts[jump1] * jump_counts[jump2] *
fert_counts[fert_idx];
}
ps[i] = ps_sum;
// We can same a few cycles by replacing calls to
// get_jump_index() with bounded increment/decrement
// operations of the jump length distribution indexes
jump1 = MIN(JUMP_ARRAY_LEN-1, jump1+1);
jump2 = MAX(0, jump2-1);
}
if (sentence_scores != NULL) {
count max_p = 0.0;
for (size_t i=0; i<source_length; i++) {
const count p = ps[i] - (i? ps[i-1]: 0.0);
if (p > max_p) max_p = p;
}
sentence_scores[sent] += logf(
max_p / ((count)jump_counts[JUMP_SUM]*
(count)jump_counts[JUMP_SUM]));
}
// rather than scaling the non-NULL probabilities with Z^-2
// for the jump distribution normalization factor Z, we scale
// the NULL probability with Z^1 instead, since the sampling
// distribution will be normalized anyway.
// Beware of this if you ever make modifications here!
ps_sum += ta->null_prior * ta->inv_source_count_sum[0] *
(NULL_ALPHA +(count)null_n) *
jump_counts[JUMP_SUM] * jump_counts[skip_jump];
} else if (model >= 2) {
size_t jump1 = get_jump_index(
aa_jm1, 0, source_length);
size_t jump2 = get_jump_index(
0, aa_jp1, source_length);
for (size_t i=0; i<source_length; i++) {
const token e = source_tokens[i];
uint32_t n = 0;
map_token_u32_get(ta->source_count + e, f, &n);
if (ta->source_prior != NULL) {
float alpha = 0.0f;
map_token_u32_get(ta->source_prior + e, f,
(uint32_t*)&alpha);
alpha += LEX_ALPHA;
ps_sum += ta->inv_source_count_sum[e] *
(alpha + (count)n) *
jump_counts[jump1] * jump_counts[jump2];
} else {
ps_sum += ta->inv_source_count_sum[e] *
(LEX_ALPHA + (count)n) *
jump_counts[jump1] * jump_counts[jump2];
}
ps[i] = ps_sum;
// We can same a few cycles by replacing calls to
// get_jump_index() with bounded increment/decrement
// operations of the jump length distribution indexes
jump1 = MIN(JUMP_ARRAY_LEN-1, jump1+1);
jump2 = MAX(0, jump2-1);
}
if (sentence_scores != NULL) {
count max_p = 0.0;
for (size_t i=0; i<source_length; i++) {
const count p = ps[i] - (i? ps[i-1]: 0.0);
if (p > max_p) max_p = p;
}
sentence_scores[sent] += logf(
max_p / ((count)jump_counts[JUMP_SUM]*
(count)jump_counts[JUMP_SUM]));
}
// rather than scaling the non-NULL probabilities with Z^-2
// for the jump distribution normalization factor Z, we scale
// the NULL probability with Z^1 instead, since the sampling
// distribution will be normalized anyway.
// Beware of this if you ever make modifications here!
ps_sum += ta->null_prior * ta->inv_source_count_sum[0] *
(NULL_ALPHA + (count)null_n) *
jump_counts[JUMP_SUM] * jump_counts[skip_jump];
} else {
for (size_t i=0; i<source_length; i++) {
const token e = source_tokens[i];
uint32_t n = 0;
map_token_u32_get(ta->source_count + e, f, &n);
if (ta->source_prior != NULL) {
float alpha = 0.0f;
map_token_u32_get(ta->source_prior + e, f,
(uint32_t*)&alpha);
alpha += LEX_ALPHA;
ps_sum += ta->inv_source_count_sum[e] *
(alpha + (count)n);
} else {
ps_sum += ta->inv_source_count_sum[e] *
(LEX_ALPHA + (count)n);
}
ps[i] = ps_sum;
}
if (sentence_scores != NULL) {
count max_p = 0.0;
for (size_t i=0; i<source_length; i++) {
const count p = ps[i] - (i? ps[i-1]: 0.0);
if (p > max_p) max_p = p;
}
sentence_scores[sent] += logf(max_p);
}
ps_sum += ta->null_prior * ta->inv_source_count_sum[0] *
(NULL_ALPHA + (count)null_n);
}
ps[source_length] = ps_sum;
if (argmax) {
count scale = (count)1.0 / ps_sum;
acc_ps[acc_base] += ps[0] * scale;
for (size_t i=1; i<source_length+1; i++)
acc_ps[acc_base+i] += (ps[i] - ps[i-1]) * scale;
acc_base += source_length+1;
}
link_t new_i;
if (sentence_scores == NULL) {
if ((!argmax) || samples_left) {
// normal case: simply from distribution
new_i = random_unnormalized_cumulative_categorical32(
state, ps, source_length+1);
} else {
// if we have collected enough samples, do argmax over
// the accumulated probabilities
new_i = 0;
acc_base -= source_length+1;
count best_p = acc_ps[acc_base + 0];
for (size_t i=1; i<source_length+1; i++) {
const count p = acc_ps[acc_base + i];
if (p > best_p) {
new_i = i;
best_p = p;
}
}
acc_base += source_length+1;
}
} else {
// if we are just calculating scores, don't sample at all
// this could have been a no-op, but old_i is NULL_LINK in
// case of unaligned words, whereas new_i is assumed to be one
// index beyond the sentence (== source_length)
new_i = (old_i == NULL_LINK)? source_length : old_i;
}
token new_e;
if (new_i == source_length) {
new_e = 0;
links[j] = NULL_LINK;
} else {
new_e = source_tokens[new_i];
links[j] = new_i;
if (model >= 3)
fert[new_i]++;
}
if (sent < n_sentences) {
if (old_e != new_e && reduced_count == 0) {
// If we reduced the old count to zero and we sampled a
// link to a different source token, remove the old zero
// count in order to save space.
int r = map_token_u32_delete(ta->source_count + old_e, f);
assert (r);
}
ta->inv_source_count_sum[new_e] =
(count)1.0
/ ((count)1.0/ta->inv_source_count_sum[new_e] + (count)1.0);
map_token_u32_add(ta->source_count + new_e, f, 1);
}
if (sent < n_sentences && model >= 2) {
if (new_e == 0) {
jump_counts[JUMP_SUM] += (count) 1.0;
jump_counts[skip_jump] += (count) 1.0;
} else {
const size_t new_jump1 = get_jump_index(
aa_jm1, new_i, source_length);
const size_t new_jump2 = get_jump_index(
new_i, aa_jp1, source_length);
jump_counts[JUMP_SUM] += (count) 2.0;
jump_counts[new_jump1] += (count) 1.0;
jump_counts[new_jump2] += (count) 1.0;
}
}
if (model >= 2 && new_e != 0)
aa_jm1 = new_i;
}
if (sentence_scores != NULL)
sentence_scores[sent] /= (count)target_length;
if (argmax) {
if (samplers_left) {
samplers_left--;
goto resample;
} else if (samples_left) {
samplers_left = n_samplers-1;
samples_left--;
goto resample;
}
}
}
if (argmax) free(acc_ps);
}
void text_alignment_make_counts(struct text_alignment *ta) {
const int model = ta->model;
struct sentence **source_sentences = ta->source->sentences;
struct sentence **target_sentences = ta->target->sentences;
// TODO: do we need a special case for NULL links? Probably not, since
// NULL alignment statistics could also provide valuable prior
// information
//map_token_u32_reset(ta->source_count + 0);
//ta->inv_source_count_sum[0] =
// NULL_ALPHA * (count)ta->target->vocabulary_size;
for (size_t i=0; i<ta->source->vocabulary_size; i++) {
map_token_u32_reset(ta->source_count + i);
if (ta->source_prior != NULL) {
ta->inv_source_count_sum[i] = ta->source_prior_sum[i];
} else {
ta->inv_source_count_sum[i] =
LEX_ALPHA * (count)ta->target->vocabulary_size;
}
}
if (model >= 2) {
if (ta->has_jump_prior) {
// TODO: decide on whether to add JUMP_ALPHA
ta->jump_counts[JUMP_SUM] = (count) (JUMP_MAX_EST*JUMP_ALPHA);
for (size_t i=0; i<JUMP_ARRAY_LEN-1; i++) {
ta->jump_counts[i] = ta->jump_prior[i] + (count) JUMP_ALPHA;
ta->jump_counts[JUMP_SUM] += ta->jump_prior[i];
}
} else {
for (size_t i=0; i<JUMP_ARRAY_LEN-1; i++)
ta->jump_counts[i] = (count) JUMP_ALPHA;
ta->jump_counts[JUMP_SUM] = (count) (JUMP_MAX_EST*JUMP_ALPHA);
}
}
const size_t n_sentences =
ta->n_clean? ta->n_clean: ta->target->n_sentences;
for (size_t sent=0; sent<n_sentences; sent++) {
link_t *links = ta->sentence_links[sent];
if (links == NULL) continue;
const struct sentence *source_sentence = source_sentences[sent];
const struct sentence *target_sentence = target_sentences[sent];
const size_t source_length = source_sentence->length;
const size_t target_length = target_sentence->length;
int aa_jm1 = -1;
for (size_t j=0; j<target_length; j++) {
const link_t i = links[j];
const token e = (i == NULL_LINK)? 0 : source_sentence->tokens[i];
const token f = target_sentence->tokens[j];
ta->inv_source_count_sum[e] += (count)1.0;
map_token_u32_add(ta->source_count + e, f, 1);
if (model >= 2 && e != 0) {
const size_t jump = get_jump_index(aa_jm1, i, source_length);
aa_jm1 = i;
ta->jump_counts[jump] += (count)1.0;
ta->jump_counts[JUMP_SUM] += (count)1.0;
}
}
if (model >= 2 && aa_jm1 >= 0) {
ta->jump_counts[get_jump_index(
aa_jm1, source_length, source_length)] += (count) 1.0;
ta->jump_counts[JUMP_SUM] += (count) 1.0;
}
}
for (size_t i=0; i<ta->source->vocabulary_size; i++)
ta->inv_source_count_sum[i] = (count)1.0 / ta->inv_source_count_sum[i];
}
void text_alignment_randomize(struct text_alignment *ta, random_state *state) {
struct sentence **source_sentences = ta->source->sentences;
struct sentence **target_sentences = ta->target->sentences;
for (size_t sent=0; sent<ta->target->n_sentences; sent++) {
link_t *links = ta->sentence_links[sent];
if (links == NULL) continue;
const struct sentence *source_sentence = source_sentences[sent];
const struct sentence *target_sentence = target_sentences[sent];
for (size_t j=0; j<target_sentence->length; j++) {
if (random_uniform32(state) < ta->null_prior) {
links[j] = NULL_LINK;
} else {
links[j] = random_uint32_biased(state, source_sentence->length);
}
}
}
}
int text_alignment_load_priors(
struct text_alignment *ta, const char *filename, int reverse)
{
size_t lineno = 1;
FILE *file = (!strcmp(filename, "-"))? stdin: fopen(filename, "r");
if (file == NULL) {
perror("text_alignment_load_priors(): failed to open text file");
return -1;
}
size_t source_vocabulary_size, target_vocabulary_size, n_lex_priors,
n_jump_priors, n_fert_priors,
n_fwd_jump_priors, n_fwd_fert_priors,
n_rev_jump_priors, n_rev_fert_priors;
if (fscanf(file, "%zd %zd %zd %zd %zd %zd %zd\n",
&source_vocabulary_size,
&target_vocabulary_size,
&n_lex_priors,
&n_fwd_jump_priors,
&n_rev_jump_priors,
&n_fwd_fert_priors,
&n_rev_fert_priors) != 7)
{
fprintf(stderr,
"text_alignment_load_priors(): failed to read header in %s\n",
filename);
if (file != stdin) fclose(file);
return -1;
}
lineno++;
if (reverse) {
n_jump_priors = n_rev_jump_priors;
n_fert_priors = n_rev_fert_priors;
} else {
n_jump_priors = n_fwd_jump_priors;
n_fert_priors = n_fwd_fert_priors;
}
if (n_lex_priors) {
if ((ta->source_prior =
malloc(ta->source->vocabulary_size*sizeof(struct map_token_u32))
) == NULL)
{
perror("text_alignment_load_priors(): "
"failed to allocate buffer pointers");
exit(EXIT_FAILURE);
}
for (size_t i=0; i<ta->source->vocabulary_size; i++)
map_token_u32_create(ta->source_prior + i);
if ((ta->source_prior_sum =
malloc(sizeof(count)*ta->source->vocabulary_size)) == NULL)
{
perror("text_alignment_load_priors(): "
"failed to allocate counter array");
exit(EXIT_FAILURE);
}
for (size_t i=0; i<ta->source->vocabulary_size; i++) {
ta->source_prior_sum[i] = 0.0;
}
}
if (n_fert_priors) {
if ((ta->fert_prior =
malloc(ta->source->vocabulary_size*sizeof(count)*FERT_ARRAY_LEN))
== NULL)
{
perror("text_alignment_create(): failed to allocate fertility "
"prior array");
exit(EXIT_FAILURE);
}
for (size_t i=0;i<ta->source->vocabulary_size*FERT_ARRAY_LEN;i++)
ta->fert_prior[i] = 0.0;
}
// TODO: check that JUMP_ALPHA and FERT_ALPHA are added where they should,
// otherwise add here! (above and below)
if (n_jump_priors) {
ta->has_jump_prior = 1;
for (size_t i=0; i<JUMP_ARRAY_LEN; i++)
ta->jump_prior[i] = 0.0;
}
size_t t;
if (reverse) {
t = source_vocabulary_size;
source_vocabulary_size = target_vocabulary_size;
target_vocabulary_size = t;
}
if (source_vocabulary_size != ta->source->vocabulary_size ||
target_vocabulary_size != ta->target->vocabulary_size)
{
fprintf(stderr,
"text_alignment_load_priors(): vocabulary size mismatch, "
"source is %zd (expected %"PRItoken") "
"and target is %zd (expected %"PRItoken") in %s\n",
source_vocabulary_size, ta->source->vocabulary_size,
target_vocabulary_size, ta->target->vocabulary_size,
filename);
if (file != stdin) fclose(file);
return -1;
}
for (size_t i=0; i<n_lex_priors; i++) {
token e, f, t;
float alpha;
if (fscanf(file, "%"SCNtoken" %"SCNtoken" %f\n", &e, &f, &alpha) != 3) {
fprintf(stderr,
"text_alignment_load_priors(): error in line %zd of %s\n",
i+2, filename);
if (file != stdin) fclose(file);
return -1;
}
lineno++;
if (reverse) {
t = e;
e = f;
f = t;
}
// TODO: fix this properly
map_token_u32_add(ta->source_prior + e, f, *((uint32_t*)&alpha));
ta->source_prior_sum[e] += alpha;
}
if (n_lex_priors) {
for (size_t e=0; e<ta->source->vocabulary_size; e++) {
ta->source_prior_sum[e] +=
LEX_ALPHA * (float)ta->target->vocabulary_size;
}
}
for (size_t i=0; i<n_fwd_jump_priors; i++) {
int jump;
size_t jump_index;
float alpha;
if (fscanf(file, "%d %f\n", &jump, &alpha) != 2) {
fprintf(stderr,
"text_alignment_load_priors(): error in line %zd of %s\n",
lineno, filename);
if (file != stdin) fclose(file);
return -1;
}
jump_index = MAX(0, MIN(JUMP_ARRAY_LEN-1, jump + JUMP_ARRAY_LEN/2));
if (! reverse)
ta->jump_prior[jump_index] += alpha;
lineno++;
}
for (size_t i=0; i<n_rev_jump_priors; i++) {
int jump;
size_t jump_index;
float alpha;
if (fscanf(file, "%d %f\n", &jump, &alpha) != 2) {
fprintf(stderr,
"text_alignment_load_priors(): error in line %zd of %s\n",
i+2, filename);
if (file != stdin) fclose(file);
return -1;
}
jump_index = MAX(0, MIN(JUMP_ARRAY_LEN-1, jump + JUMP_ARRAY_LEN/2));
if (reverse)
ta->jump_prior[jump_index] += alpha;
lineno++;
}
for (size_t i=0; i<n_fwd_fert_priors; i++) {
int k;
token e;
size_t fert_index;
float alpha;
if (fscanf(file, "%"SCNtoken" %d %f\n", &e, &k, &alpha) != 3) {
fprintf(stderr,
"text_alignment_load_priors(): error in line %zd of %s\n",
lineno, filename);
if (file != stdin) fclose(file);
return -1;
}
fert_index = get_fert_index(e, k);
if (! reverse) {
if (e >= ta->source->vocabulary_size) {
fprintf(stderr,
"text_alignment_load_priors(): index %"PRItoken" out"
" of range (forward)", e);
if (file != stdin) fclose(file);
return -1;
}
ta->fert_prior[fert_index] += alpha;
}
lineno++;
}
for (size_t i=0; i<n_rev_fert_priors; i++) {
int k;
token e;
size_t fert_index;
float alpha;
if (fscanf(file, "%"SCNtoken" %d %f\n", &e, &k, &alpha) != 3) {
fprintf(stderr,
"text_alignment_load_priors(): error in line %zd of %s\n",
lineno, filename);
if (file != stdin) fclose(file);
return -1;
}
fert_index = get_fert_index(e, k);
if (reverse) {
if (e >= ta->source->vocabulary_size) {
fprintf(stderr,
"text_alignment_load_priors(): index %"PRItoken" out"
" of range (reverse)", e);
if (file != stdin) fclose(file);
return -1;
}
ta->fert_prior[fert_index] += alpha;
}
lineno++;
}
return 0;
}
struct text_alignment *text_alignment_create(
const struct text *source, const struct text *target)
{
if (source->n_sentences != target->n_sentences) {
fprintf(stderr, "text_alignment_create(): number of sentences "
"differ in texts!\n");
return NULL;
}
struct text_alignment *ta;
if ((ta = malloc(sizeof(*ta))) == NULL) {
perror("text_alignment_create(): failed to allocate structure");
exit(EXIT_FAILURE);
}
ta->model = 1;
ta->source = source;
ta->target = target;
ta->n_clean = 0;
// These should be initialized with text_alignment_load_priors()
ta->source_prior = NULL;
ta->source_prior_sum = NULL;
ta->fert_prior = NULL;
ta->has_jump_prior = 0;
size_t buf_size = 0;
for (size_t i=0; i<target->n_sentences; i++) {
if (target->sentences[i] != NULL && source->sentences[i] != NULL)
buf_size += (size_t)target->sentences[i]->length;
}
if ((ta->buf = malloc(buf_size*sizeof(link_t))) == NULL) {
perror("text_alignment_create(): failed to allocate buffer");
exit(EXIT_FAILURE);
}
if ((ta->sentence_links = malloc(target->n_sentences*sizeof(link_t*)))
== NULL)
{
perror("text_alignment_create(): failed to allocate buffer pointers");
exit(EXIT_FAILURE);
}
link_t *ptr = ta->buf;
for (size_t i=0; i<target->n_sentences; i++) {
if (target->sentences[i] != NULL && source->sentences[i] != NULL)
{