-
Notifications
You must be signed in to change notification settings - Fork 2
/
hdp_grammar.h
1982 lines (1780 loc) · 70.4 KB
/
hdp_grammar.h
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
/**
* hdp_grammar.h
*
* Created on: Jul 18, 2015
* Author: asaparov
*/
#ifndef HDP_GRAMMAR_H_
#define HDP_GRAMMAR_H_
#include <core/lex.h>
#include <hdp/mcmc.h>
#include <cinttypes>
#include "grammar.h"
#include "morphology.h"
struct nonterminal_pair {
unsigned int first;
unsigned int second;
double prior_probability;
};
struct nonterminal_pair_iterator {
unsigned int first;
unsigned int second;
unsigned int nonterminal_count;
template<typename V>
nonterminal_pair_iterator(const dense_categorical<V>& prior) :
first(1), second(1), nonterminal_count(prior.atom_count) { }
inline bool has_next() const {
return first <= nonterminal_count;
}
inline nonterminal_pair next() {
nonterminal_pair pair;
pair.first = first;
pair.second = second;
pair.prior_probability = 1.0 / (nonterminal_count * nonterminal_count);
second++;
if (second > nonterminal_count) {
first++;
second = 1;
}
return pair;
}
};
template<typename NonterminalPrior, typename TerminalPrior>
struct rule_prior
{
typedef double value_type;
NonterminalPrior nonterminal_prior;
TerminalPrior terminal_prior;
double max_nonterminal_probability;
double max_nonterminal_log_probability;
rule_prior(const NonterminalPrior& nonterminal, const TerminalPrior& terminal)
: nonterminal_prior(nonterminal), terminal_prior(terminal)
{
compute_max_nonterminal_probability();
}
rule_prior(const rule_prior<NonterminalPrior, TerminalPrior>& src)
: nonterminal_prior(src.nonterminal_prior), terminal_prior(src.terminal_prior),
max_nonterminal_probability(src.max_nonterminal_probability),
max_nonterminal_log_probability(src.max_nonterminal_log_probability)
{ }
constexpr part_of_speech get_part_of_speech() const {
return POS_OTHER;
}
template<typename Semantics>
double probability(const rule<Semantics>& observation) const {
if (observation.is_terminal()) {
return terminal_prior.probability(sequence(observation.t.terminals, observation.t.length));
} else {
if (observation.nt.length != 2)
return 0.0;
auto nonterminals = array_multiset<unsigned int>(2);
if (!get_nonterminals(nonterminals, observation)) exit(EXIT_FAILURE);
double score = nonterminal_prior.probability(nonterminals)
/ (array_length(Semantics::functions) * array_length(Semantics::functions));
return score * pow(max_nonterminal_probability, 2 - observation.nt.length);
}
}
template<typename Semantics>
inline double probability(const array_multiset<rule<Semantics>>& observations) const {
double product = 1.0;
for (const auto& entry : observations.counts)
product *= pow(probability(entry.key), entry.value);
return product;
}
template<typename Semantics>
double log_probability(const rule<Semantics>& observation) const {
if (observation.is_terminal()) {
return terminal_prior.log_probability(sequence(observation.t.terminals, observation.t.length));
} else {
if (observation.nt.length != 2)
return -std::numeric_limits<double>::infinity();
auto nonterminals = array_multiset<unsigned int>(2);
if (!get_nonterminals(nonterminals, observation)) exit(EXIT_FAILURE);
double score = nonterminal_prior.log_probability(nonterminals) - 2 * Semantics::log_function_count;
return score + max_nonterminal_log_probability * (2 - observation.nt.length);
}
}
template<typename Semantics>
inline double log_probability(const array_multiset<rule<Semantics>>& observations) const {
double sum = 0.0;
for (const auto& entry : observations.counts)
sum += log_probability(entry.key) * entry.value;
return sum;
}
inline void compute_max_nonterminal_probability() {
double maximum = 0.0;
for (unsigned int i = 0; i < nonterminal_prior.atom_count; i++)
maximum = max(maximum, nonterminal_prior.probability(i + 1));
max_nonterminal_probability = maximum;
max_nonterminal_log_probability = log(maximum);
}
static inline bool copy(
const rule_prior<NonterminalPrior, TerminalPrior>& src,
rule_prior<NonterminalPrior, TerminalPrior>& dst)
{
if (!core::copy(src.nonterminal_prior, dst.nonterminal_prior)
|| !core::copy(src.terminal_prior, dst.terminal_prior))
return false;
dst.compute_max_nonterminal_probability();
return true;
}
static inline void free(rule_prior<NonterminalPrior, TerminalPrior>& prior) {
core::free(prior.nonterminal_prior);
core::free(prior.terminal_prior);
}
private:
template<typename Semantics>
static inline bool get_nonterminals_helper(
array_multiset<unsigned int>& nonterminals,
const rule<Semantics>& observation,
unsigned int count = 1)
{
for (unsigned int i = 0; i < observation.nt.length; i++)
if (!nonterminals.add_unsorted(observation.nt.nonterminals[i], count))
return false;
return true;
}
template<typename Semantics>
static bool get_nonterminals(
array_multiset<unsigned int>& nonterminals,
const rule<Semantics>& observation)
{
if (!get_nonterminals_helper(nonterminals, observation)) return false;
if (nonterminals.counts.size > 1)
insertion_sort(nonterminals.counts.keys, nonterminals.counts.values, (unsigned int) nonterminals.counts.size);
return true;
}
template<typename Semantics>
static bool get_nonterminals(
array_multiset<unsigned int>& nonterminals,
const array_multiset<rule<Semantics>>& observations)
{
for (auto entry : observations.counts) {
if (!get_nonterminals_helper(nonterminals, entry.key, entry.value))
return false;
}
if (nonterminals.counts.size > 1)
insertion_sort(nonterminals.counts.keys, nonterminals.counts.values, (unsigned int) nonterminals.counts.size);
return true;
}
};
template<typename NonterminalPrior, typename TerminalPrior>
inline bool init(
rule_prior<NonterminalPrior, TerminalPrior>& pi,
const rule_prior<NonterminalPrior, TerminalPrior>& src)
{
if (!init(pi.nonterminal_prior, src.nonterminal_prior)) return false;
if (!init(pi.terminal_prior, src.terminal_prior)) {
free(pi.nonterminal_prior);
return false;
}
pi.compute_max_nonterminal_probability();
return true;
}
template<typename NonterminalPrior, typename TerminalPrior, typename Stream>
inline bool read(rule_prior<NonterminalPrior, TerminalPrior>& prior, Stream& stream)
{
if (!read(prior.nonterminal_prior, stream) || !read(prior.terminal_prior, stream))
return false;
prior.compute_max_nonterminal_probability();
return true;
}
template<typename NonterminalPrior, typename TerminalPrior, typename Stream>
inline bool write(const rule_prior<NonterminalPrior, TerminalPrior>& prior, const Stream& stream)
{
return write(prior.nonterminal_prior, stream)
&& write(prior.terminal_prior, stream);
}
template<typename NonterminalPrior, typename TerminalPrior, typename Semantics>
bool sample(const rule_prior<NonterminalPrior, TerminalPrior>& prior, rule<Semantics>& output, bool is_preterminal)
{
typedef typename Semantics::function function;
if (is_preterminal) {
sequence& tokens = *((sequence*) alloca(sizeof(sequence)));
if (!sample(prior.terminal_prior, tokens))
return false;
output.nonterminals = tokens.tokens;
output.functions = (function*) malloc(sizeof(function));
output.length = tokens.length;
if (output.functions == NULL) {
fprintf(stderr, "sample ERROR: Insufficient memory for terminal production rule.\n");
free(output.nonterminals);
return false;
}
output.functions[0] = Semantics::terminal_function();
} else {
core::pair<function, function> sampled_transformations =
sample_uniform(Semantics::transformations);
if (!init(output, 2)) return false;
output.functions[0] = sampled_transformations.key;
output.functions[1] = sampled_transformations.value;
if (!sample(prior.nonterminal_prior, output.nonterminals[0])
|| !sample(prior.nonterminal_prior, output.nonterminals[1]))
{
free(output);
return false;
}
}
return true;
}
template<typename TerminalPrior>
struct terminal_prior
{
typedef double value_type;
TerminalPrior prior;
hash_set<sequence> excluded;
part_of_speech pos;
terminal_prior(const TerminalPrior& prior, part_of_speech pos) : prior(prior), excluded(16), pos(pos) { }
terminal_prior(const terminal_prior<TerminalPrior>& src) :
prior(src.prior), excluded(src.excluded.capacity), pos(src.pos)
{
if (!excluded.add_all(src.excluded)) exit(EXIT_FAILURE);
}
inline part_of_speech get_part_of_speech() const {
return pos;
}
template<typename Semantics>
double probability(const rule<Semantics>& observation) const {
sequence seq(observation.t.terminals, observation.t.length);
if (excluded.contains(seq)) return 0.0;
else return prior.probability(seq);
}
template<typename Semantics>
inline double probability(const array_multiset<rule<Semantics>>& observations) const {
double product = 1.0;
for (const auto& entry : observations.counts)
product *= pow(probability(entry.key), entry.value);
return product;
}
template<typename Semantics>
double log_probability(const rule<Semantics>& observation) const {
sequence seq(observation.t.terminals, observation.t.length);
if (excluded.contains(seq)) return -std::numeric_limits<double>::infinity();
else return prior.log_probability(seq);
}
template<typename Semantics>
inline double log_probability(const array_multiset<rule<Semantics>>& observations) const {
double sum = 0.0;
for (const auto& entry : observations.counts)
sum += log_probability(entry.key) * entry.value;
return sum;
}
static inline bool copy(
const terminal_prior<TerminalPrior>& src,
terminal_prior<TerminalPrior>& dst)
{
return core::copy(src.prior, dst.prior)
&& core::copy(src.excluded, dst.excluded)
&& core::copy(src.pos, dst.pos);
}
static inline void free(terminal_prior<TerminalPrior>& prior) {
core::free(prior.prior);
for (sequence& entry : prior.excluded)
core::free(entry);
core::free(prior.excluded);
}
};
template<typename RulePrior>
inline bool init(
terminal_prior<RulePrior>& pi,
const terminal_prior<RulePrior>& src)
{
pi.pos = src.pos;
if (!init(pi.prior, src.prior)) return false;
if (!hash_set_init(pi.excluded, src.excluded.capacity)) {
free(pi.prior); return false;
} else if (!pi.excluded.add_all(src.excluded)) {
free(pi.excluded); free(pi.prior);
return false;
}
return true;
}
template<typename RulePrior, typename Stream>
inline bool read(terminal_prior<RulePrior>& prior, Stream& stream)
{
if (!read(prior.pos, stream)
|| !read(prior.prior, stream)) return false;
if (!read(prior.excluded, stream)) {
free(prior.prior); return false;
}
return true;
}
template<typename RulePrior, typename Stream>
inline bool write(const terminal_prior<RulePrior>& prior, const Stream& stream)
{
return write(prior.pos, stream) && write(prior.prior, stream) && write(prior.excluded, stream);
}
template<typename TerminalPrior, typename Semantics>
bool sample(const terminal_prior<TerminalPrior>& prior, rule<Semantics>& output)
{
sequence& tokens = *((sequence*) alloca(sizeof(sequence)));
while (true) {
if (!sample(prior.prior, tokens))
return false;
if (!prior.excluded.contains(tokens)) break;
free(tokens);
}
output.type = rule_type::TERMINAL;
output.t.terminals = tokens.tokens;
output.t.length = tokens.length;
output.t.inflected = nullptr;
output.t.inflected_length = 0;
return true;
}
template<typename RulePrior, typename Semantics>
struct rule_list_prior
{
typedef double value_type;
RulePrior backoff_prior;
hash_map<rule<Semantics>, pair<double, double>> rules;
rule_list_prior(const RulePrior& backoff_prior) : backoff_prior(backoff_prior), rules(4) { }
rule_list_prior(const rule_list_prior<RulePrior, Semantics>& src) :
backoff_prior(src.backoff_prior), rules(src.rules.table.capacity)
{
if (!initialize(src.rules)) exit(EXIT_FAILURE);
}
~rule_list_prior() {
free();
}
inline part_of_speech get_part_of_speech() const {
return backoff_prior.get_part_of_speech();
}
double probability(const rule<Semantics>& observation) const {
if (rules.table.size == 0) {
return backoff_prior.probability(observation);
} else {
bool contains;
pair<double, double>& entry = rules.get(observation, contains);
if (contains)
return entry.key;
else return 0.0;
}
}
inline double probability(const array_multiset<rule<Semantics>>& observations) const {
double product = 1.0;
for (const auto& entry : observations.counts)
product *= pow(probability(entry.key), entry.value);
return product;
}
inline double log_probability(const rule<Semantics>& observation) const {
if (rules.table.size == 0) {
return backoff_prior.log_probability(observation);
} else {
bool contains;
pair<double, double>& entry = rules.get(observation, contains);
if (contains)
return entry.value;
else return -std::numeric_limits<double>::infinity();
}
}
inline double log_probability(const array_multiset<rule<Semantics>>& observations) const {
double sum = 0.0;
for (const auto& entry : observations.counts)
sum += log_probability(entry.key) * entry.value;
return sum;
}
bool finish() {
double total = 0.0;
unsigned int uniform_rules = 0;
for (const auto& entry : rules) {
if (entry.value.key == 0.0) uniform_rules++;
else total += entry.value.key;
}
if (total > 1.0) {
fprintf(stderr, "rule_list_prior.finish WARNING: Total probability is greater than 1.\n");
return false;
}
double uniform_probability = (1.0 - total) / uniform_rules;
double log_uniform_probability = log(uniform_probability);
for (pair<rule<Semantics>&, pair<double, double>&> entry : rules) {
if (entry.value.key == 0.0) {
entry.value.key = uniform_probability;
entry.value.value = log_uniform_probability;
} else {
entry.value.value = log(entry.value.key);
}
}
return true;
}
static inline bool copy(const rule_list_prior<RulePrior, Semantics>& src, rule_list_prior<RulePrior, Semantics>& dst) {
return init(dst, src);
}
static inline void free(rule_list_prior<RulePrior, Semantics>& prior) {
prior.free();
core::free(prior.backoff_prior);
core::free(prior.rules);
}
private:
inline bool initialize(const hash_map<rule<Semantics>, pair<double, double>>& src) {
return rules.put_all(src);
}
inline void free() {
for (auto entry : rules)
core::free(entry.key);
}
template<typename A, typename B>
friend bool init(rule_list_prior<A, B>&, const rule_list_prior<A, B>&);
};
template<typename RulePrior, typename Semantics>
inline bool init(rule_list_prior<RulePrior, Semantics>& prior,
const rule_list_prior<RulePrior, Semantics>& src)
{
if (!init(prior.backoff_prior, src.backoff_prior)) return false;
if (!hash_map_init(prior.rules, src.rules.table.capacity)) {
free(prior.backoff_prior);
return false;
} else if (!prior.initialize(src.rules)) {
free(prior.backoff_prior);
free(prior.rules);
return false;
}
return true;
}
template<typename RulePrior, typename Semantics, typename Stream, typename RuleReader>
inline bool read(rule_list_prior<RulePrior, Semantics>& prior, Stream& stream, RuleReader& reader)
{
if (!read(prior.backoff_prior, stream)) return false;
if (!read(prior.rules, stream, reader)) {
free(prior.backoff_prior);
return false;
}
return true;
}
template<typename RulePrior, typename Semantics, typename Stream, typename RuleWriter>
inline bool write(const rule_list_prior<RulePrior, Semantics>& prior, Stream& stream, RuleWriter& writer)
{
return write(prior.backoff_prior, stream) && write(prior.rules, stream, writer);
}
template<typename RulePrior, typename Semantics>
bool sample(const rule_list_prior<RulePrior, Semantics>& prior, rule<Semantics>& output)
{
if (prior.rules.table.size == 0) {
return sample(prior.backoff_prior, output);
} else {
unsigned int index = 0;
double* probabilities = (double*) malloc(sizeof(double) * prior.rules.table.size);
for (const auto& entry : prior.rules) {
probabilities[index] = entry.value.key;
index++;
}
index = 0;
unsigned int selected = sample_categorical(probabilities, prior.rules.table.size);
free(probabilities);
for (const rule<Semantics>& r : prior.rules.table) {
if (index == selected)
return init(output, r);
index++;
}
/* unreachable */
return false;
}
}
enum nonterminal_type {
NONTERMINAL = 1,
PRETERMINAL = 2,
PRETERMINAL_NUMBER = 3,
PRETERMINAL_STRING = 4
};
template<typename Stream>
inline bool read(nonterminal_type& type, Stream& in) {
unsigned char c;
if (!read(c, in)) return false;
type = static_cast<nonterminal_type>(c);
return true;
}
template<typename Stream>
inline bool write(const nonterminal_type& type, Stream& out) {
return write((unsigned char) type, out);
}
template<typename Stream>
bool print(const nonterminal_type& type, Stream& out) {
switch (type) {
case NONTERMINAL: return print("nonterminal", out);
case PRETERMINAL: return print("preterminal", out);
case PRETERMINAL_NUMBER: return print("preterminal_number", out);
case PRETERMINAL_STRING: return print("preterminal_string", out);
default:
fprintf(stderr, "print ERROR: Unrecognized nonterminal_type.\n");
return false;
}
}
template<typename RulePrior, typename Semantics>
struct hdp_rule_distribution
{
struct cache_value {
hash_map<feature_set, double*> probabilities;
hash_map<rule<Semantics>, array<weighted_feature_set<double>>*> posterior;
static inline void move(const cache_value& src, cache_value& dst) {
core::move(src.probabilities, dst.probabilities);
core::move(src.posterior, dst.posterior);
}
static inline void free(cache_value& value)
{
for (auto entry : value.probabilities) {
core::free(entry.key);
core::free(entry.value);
}
for (auto entry : value.posterior) {
core::free(entry.key);
if (entry.value != NULL) {
for (auto& element : *entry.value)
core::free(element);
core::free(*entry.value);
core::free(entry.value);
}
}
core::free(value.probabilities);
core::free(value.posterior);
}
};
nonterminal_type type;
typename Semantics::feature* feature_sequence;
unsigned int feature_count;
array_multiset<rule<Semantics>> observations;
hdp<RulePrior, constant<rule<Semantics>>, rule<Semantics>, double> h;
hdp_sampler<RulePrior, constant<rule<Semantics>>, rule<Semantics>, double> sampler;
cache<RulePrior, constant<rule<Semantics>>, rule<Semantics>, double> hdp_cache;
double* a; double* b;
hash_map<feature_set, cache_value> likelihood_cache;
array<unsigned int>* root_probabilities;
inline bool has_terminal_rules() const {
return type != NONTERMINAL;
}
inline bool has_nonterminal_rules() const {
return type == NONTERMINAL;
}
inline bool is_string_preterminal() const {
return type == PRETERMINAL_STRING;
}
inline part_of_speech get_part_of_speech() const {
return h.pi.get_part_of_speech();
}
inline void on_resize() {
sampler.n = &h;
}
void clear() {
for (auto entry : likelihood_cache) {
core::free(entry.key);
core::free(entry.value);
}
likelihood_cache.clear();
remove_empty_tables(sampler, hdp_cache);
recompute_root_assignments(sampler);
if (root_probabilities != NULL) {
cleanup_root_probabilities(root_probabilities, (unsigned int) observations.counts.size);
root_probabilities = NULL;
}
}
static void free(hdp_rule_distribution<RulePrior, Semantics>& distribution)
{
if (distribution.feature_count > 0)
core::free(distribution.feature_sequence);
for (auto entry : distribution.likelihood_cache) {
core::free(entry.key);
core::free(entry.value);
}
if (distribution.root_probabilities != NULL) {
cleanup_root_probabilities(distribution.root_probabilities, (unsigned int) distribution.observations.counts.size);
distribution.root_probabilities = NULL;
}
core::free(distribution.likelihood_cache);
core::free(distribution.observations);
core::free(distribution.hdp_cache);
core::free(distribution.sampler);
core::free(distribution.h);
core::free(distribution.a); core::free(distribution.b);
}
};
template<typename RulePrior, typename Semantics>
bool init(
hdp_rule_distribution<RulePrior, Semantics>& distribution,
nonterminal_type type, const RulePrior& rule_prior,
const typename Semantics::feature* features,
const double* a, const double* b, unsigned int feature_count)
{
unsigned int depth = feature_count + 1;
double* alpha = (double*) alloca(sizeof(double) * depth);
if (alpha == NULL) return false;
for (unsigned int i = 0; i < depth; i++)
alpha[i] = a[i] / b[i];
distribution.type = type;
distribution.root_probabilities = NULL;
distribution.feature_count = feature_count;
if (feature_count > 0) {
distribution.feature_sequence = (typename Semantics::feature*)
malloc(sizeof(typename Semantics::feature) * feature_count);
if (distribution.feature_sequence == NULL) {
fprintf(stderr, "init ERROR: Insufficient memory for feature sequence in hdp_rule_distribution.\n");
return false;
}
memcpy(distribution.feature_sequence, features, sizeof(typename Semantics::feature) * feature_count);
}
if (!init(distribution.observations, 16)) {
if (distribution.feature_count > 0) free(distribution.feature_sequence);
return false;
} else if (!hash_map_init(distribution.likelihood_cache, 32)) {
if (distribution.feature_count > 0) free(distribution.feature_sequence);
free(distribution.observations); return false;
} else if (!init(distribution.h, rule_prior, alpha, depth)) {
if (distribution.feature_count > 0) free(distribution.feature_sequence);
free(distribution.observations); free(distribution.likelihood_cache); return false;
} else if (!init(distribution.sampler, distribution.h)) {
if (distribution.feature_count > 0) free(distribution.feature_sequence);
free(distribution.observations); free(distribution.likelihood_cache);
free(distribution.h); return false;
} else if (!init(distribution.hdp_cache, distribution.sampler)) {
if (distribution.feature_count > 0) free(distribution.feature_sequence);
free(distribution.observations); free(distribution.likelihood_cache);
free(distribution.h); free(distribution.sampler); return false;
}
distribution.a = (double*) malloc(sizeof(double) * depth);
if (distribution.a == NULL) {
if (distribution.feature_count > 0) free(distribution.feature_sequence);
free(distribution.observations); free(distribution.likelihood_cache);
free(distribution.h); free(distribution.sampler); free(distribution.hdp_cache);
return false;
}
distribution.b = (double*) malloc(sizeof(double) * depth);
if (distribution.b == NULL) {
if (distribution.feature_count > 0) free(distribution.feature_sequence);
free(distribution.observations); free(distribution.likelihood_cache);
free(distribution.h); free(distribution.sampler); free(distribution.hdp_cache);
free(distribution.a); return false;
}
memcpy(distribution.a, a, sizeof(double) * depth);
memcpy(distribution.b, b, sizeof(double) * depth);
return true;
}
/* NOTE: this constructor is not a copy; it initializes
'distribution' with the same parameters as 'src' */
template<typename RulePrior, typename Semantics>
inline bool init(
hdp_rule_distribution<RulePrior, Semantics>& distribution,
const hdp_rule_distribution<RulePrior, Semantics>& src)
{
return init(distribution, src.h.pi, src.feature_sequence, src.a, src.b, src.feature_count);
}
template<typename RulePrior, typename Semantics>
bool copy(
const hdp_rule_distribution<RulePrior, Semantics>& src,
hdp_rule_distribution<RulePrior, Semantics>& dst)
{
dst.type = src.type;
if (src.root_probabilities == NULL) {
dst.root_probabilities = NULL;
} else {
dst.root_probabilities = copy_root_probabilities(src.sampler, src.root_probabilities, src.observations.counts.size);
if (dst.root_probabilities == NULL) return false;
}
hash_map<const node<rule<Semantics>, double>*, node<rule<Semantics>, double>*> node_map(256);
dst.feature_count = src.feature_count;
if (dst.feature_count > 0) {
dst.feature_sequence = (typename Semantics::feature*)
malloc(sizeof(typename Semantics::feature) * src.feature_count);
if (dst.feature_sequence == NULL) {
fprintf(stderr, "copy ERROR: Insufficient memory for feature sequence in hdp_rule_distribution.\n");
return false;
}
memcpy(dst.feature_sequence, src.feature_sequence, sizeof(typename Semantics::feature) * dst.feature_count);
}
if (!init(dst.observations, src.observations)) {
if (dst.feature_count > 0) free(dst.feature_sequence);
return false;
} else if (!hash_map_init(dst.likelihood_cache, src.likelihood_cache.table.capacity)) {
if (dst.feature_count > 0) free(dst.feature_sequence);
free(dst.observations); return false;
} else if (!copy(src.h, dst.h, node_map)) {
if (dst.feature_count > 0) free(dst.feature_sequence);
free(dst.observations); free(dst.likelihood_cache);
return false;
} else if (!copy(src.sampler, dst.sampler, dst.h, node_map)) {
if (dst.feature_count > 0) free(dst.feature_sequence);
free(dst.observations); free(dst.likelihood_cache);
free(dst.h); return false;
} else if (!init(dst.hdp_cache, src.sampler)) {
if (dst.feature_count > 0) free(dst.feature_sequence);
free(dst.observations); free(dst.likelihood_cache);
free(dst.h); free(dst.sampler); return false;
}
dst.a = (double*) malloc(sizeof(double) * src.h.depth);
if (dst.a == NULL) {
if (dst.feature_count > 0) free(dst.feature_sequence);
free(dst.observations); free(dst.likelihood_cache);
free(dst.h); free(dst.sampler); free(dst.hdp_cache);
return false;
}
dst.b = (double*) malloc(sizeof(double) * src.h.depth);
if (dst.b == NULL) {
if (dst.feature_count > 0) free(dst.feature_sequence);
free(dst.observations); free(dst.likelihood_cache);
free(dst.h); free(dst.sampler); free(dst.hdp_cache);
free(dst.a); return false;
}
memcpy(dst.a, src.a, sizeof(double) * src.h.depth);
memcpy(dst.b, src.b, sizeof(double) * src.h.depth);
return true;
}
/* TODO: the priors should also be read from/written to file,
as each nonterminal could have a different set of priors. */
template<typename RulePrior, typename Semantics, typename Stream, typename AtomReader>
bool read(hdp_rule_distribution<RulePrior, Semantics>& distribution, Stream& stream, AtomReader& atom_reader)
{
distribution.root_probabilities = NULL;
if (!read(distribution.type, stream)
|| !read(distribution.feature_count, stream)
|| !read(distribution.observations, stream, atom_reader)) {
return false;
} else if (!read(distribution.h, stream, atom_reader, atom_reader, atom_reader)) {
free(distribution.observations);
return false;
} else if (!read(distribution.sampler, stream, distribution.h, atom_reader)) {
free(distribution.observations);
free(distribution.h);
return false;
} else if (!hash_map_init(distribution.likelihood_cache, 32)) {
free(distribution.observations);
free(distribution.sampler);
free(distribution.h);
return false;
} else if (!init(distribution.hdp_cache, distribution.sampler)) {
free(distribution.likelihood_cache);
free(distribution.observations);
free(distribution.sampler);
free(distribution.h);
return false;
}
distribution.a = NULL; distribution.b = NULL; distribution.feature_sequence = NULL;
distribution.a = (double*) malloc(sizeof(double) * distribution.h.depth);
distribution.b = (double*) malloc(sizeof(double) * distribution.h.depth);
if (distribution.feature_count > 0) {
distribution.feature_sequence = (typename Semantics::feature*)
malloc(sizeof(typename Semantics::feature) * distribution.feature_count);
}
if (distribution.a == NULL || distribution.b == NULL
|| (distribution.feature_count > 0 && distribution.feature_sequence == NULL)
|| !read(distribution.a, stream, distribution.h.depth)
|| !read(distribution.b, stream, distribution.h.depth)
|| !Semantics::read(distribution.feature_sequence, stream, distribution.feature_count))
{
free(distribution.likelihood_cache); free(distribution.observations);
free(distribution.sampler); free(distribution.h); free(distribution.hdp_cache);
if (distribution.a != NULL) free(distribution.a);
if (distribution.b != NULL) free(distribution.b);
if (distribution.feature_sequence != NULL) free(distribution.feature_sequence);
return false;
}
return true;
}
template<typename RulePrior, typename Semantics, typename Stream, typename AtomWriter>
bool write(const hdp_rule_distribution<RulePrior, Semantics>& distribution, Stream& stream, AtomWriter& atom_writer)
{
return write(distribution.type, stream)
&& write(distribution.feature_count, stream)
&& write(distribution.observations, stream, atom_writer)
&& write(distribution.h, stream, atom_writer, atom_writer, atom_writer)
&& write(distribution.sampler, stream, atom_writer)
&& write(distribution.a, stream, distribution.h.depth)
&& write(distribution.b, stream, distribution.h.depth)
&& Semantics::write(distribution.feature_sequence, stream, distribution.feature_count);
}
template<typename Semantics>
bool get_features(feature_set& set, const Semantics& logical_form,
const typename Semantics::feature* features, unsigned int feature_count)
{
for (unsigned int i = 0; i < feature_count; i++)
{
if (!get_feature(features[i], logical_form, set.features[i], set.excluded[i], set.excluded_counts[i]))
return false;
#if !defined(NDEBUG)
if (set.features[i] == UNION_NODE && set.excluded_counts[i] <= 1)
fprintf(stderr, "get_features WARNING: `get_feature` returned UNION_NODE but `excluded_count` is not greater than 1.\n");
#endif
}
return true;
}
template<typename Semantics>
bool set_features(
Semantics& logical_form,
const weighted_feature_set<double>& posterior,
const typename Semantics::feature* features,
unsigned int feature_count)
{
for (unsigned int i = 0; i < feature_count; i++) {
#if !defined(NDEBUG)
if (posterior.features[i] == UNION_NODE)
fprintf(stderr, "set_features WARNING: Feature with value `UNION_NODE` is unsupported.\n");
#endif
if (posterior.features[i] == IMPLICIT_NODE) {
if (!exclude_features(features[i], logical_form,
posterior.features.excluded[i], posterior.features.excluded_counts[i]))
{
return false;
}
} else if (!set_feature(features[i], logical_form, posterior.features[i]))
/* setting this feature resulted in an empty set of logical forms, so return quietly */
return false;
}
logical_form.recompute_hash();
return true;
}
template<typename RulePrior, typename Semantics>
using hdp_grammar = grammar<Semantics, hdp_rule_distribution<RulePrior, Semantics>>;
template<typename RulePrior, typename Semantics>
bool add(
hdp_rule_distribution<RulePrior, Semantics>& distribution,
const rule<Semantics>& r, const Semantics& logical_form)
{
feature_set set = feature_set(distribution.feature_count);
if (r.is_terminal()) {
rule<Semantics> terminal_rule(sequence(r.t.terminals, r.t.length));
return get_features(set, logical_form, distribution.feature_sequence, distribution.feature_count)
&& distribution.observations.add(terminal_rule)
&& add(distribution.sampler, set.features, set.feature_count, terminal_rule, distribution.hdp_cache);
} else {
return get_features(set, logical_form, distribution.feature_sequence, distribution.feature_count)
&& distribution.observations.add(r)
&& add(distribution.sampler, set.features, set.feature_count, r, distribution.hdp_cache);
}
}
template<typename RulePrior, typename Semantics>
bool remove(hdp_rule_distribution<RulePrior, Semantics>& distribution,
const rule<Semantics>& r, const Semantics& logical_form)
{
feature_set set = feature_set(distribution.feature_count);
if (r.is_terminal()) {
rule<Semantics> terminal_rule(sequence(r.t.terminals, r.t.length));
return get_features(set, logical_form, distribution.feature_sequence, distribution.feature_count)
&& distribution.observations.subtract(terminal_rule) < distribution.observations.counts.size
&& remove(distribution.sampler, set.features, set.feature_count, terminal_rule, distribution.hdp_cache);
} else {
return get_features(set, logical_form, distribution.feature_sequence, distribution.feature_count)
&& distribution.observations.subtract(r) < distribution.observations.counts.size
&& remove(distribution.sampler, set.features, set.feature_count, r, distribution.hdp_cache);
}
}
template<typename RulePrior, typename Semantics>
inline double log_probability(const hdp_rule_distribution<RulePrior, Semantics>& distribution)
{
return log_probability(distribution.sampler)
+ log_probability_each_level(distribution.sampler, distribution.a, distribution.b);
}
template<typename RulePrior, typename Semantics, typename StringMapType>
inline double log_probability(
hdp_rule_distribution<RulePrior, Semantics>& distribution,
const rule<Semantics>& observation,
const Semantics& logical_form,
const StringMapType& token_map)
{
unsigned int length;
weighted<Semantics>* posterior;
if (observation.is_terminal()) {
rule<Semantics> terminal_rule(sequence(observation.t.terminals, observation.t.length));
posterior = log_conditional<false, false>(distribution, terminal_rule, logical_form, token_map, length);
} else {
posterior = log_conditional<false, false>(distribution, observation, logical_form, token_map, length);
}
double weight;
if (length == 0)
weight = -std::numeric_limits<double>::infinity();
else weight = posterior[0].log_probability;
if (posterior != NULL) {
for (unsigned int i = 0; i < length; i++)
free(posterior[i]);
free(posterior);
}
return weight;
}
template<typename RulePrior, typename Semantics>
inline void sample(hdp_rule_distribution<RulePrior, Semantics>& distribution)
{
distribution.clear();
sample_alpha_each_level(distribution.sampler, distribution.a, distribution.b);
sample_hdp<true>(distribution.sampler, distribution.hdp_cache);
}
template<typename RulePrior, typename Semantics>
inline bool sample(
const hdp_rule_distribution<RulePrior, Semantics>& distribution,
rule<Semantics>& sampled_rule, const Semantics& logical_form)