-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser.h
4831 lines (4317 loc) · 177 KB
/
parser.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
/**
* parser.h
*
* Created on: Jul 15, 2015
* Author: asaparov
*/
#ifndef PARSER_H_
#define PARSER_H_
#include <math.h>
#if !defined(NDEBUG)
//#define DEBUG_PARSER
#endif
#if defined(DEBUG_PARSER)
bool DEBUG_PARSER_VALUE = true;
#endif
#if defined(DEBUG_PARSER)
#define PRINT_SEARCH_STATES
#endif
constexpr bool USE_SLICE_SAMPLING = false; /* enable/disable slice sampling (only affects sampling) */
constexpr bool USE_BEAM_SEARCH = false; /* enable/disable beam search (only affects parsing) */
constexpr bool USE_NONTERMINAL_PREITERATOR = false; /* use nonterminal_iterator states either before or after completing rule_states */
constexpr unsigned int BEAM_WIDTH = 10000;
constexpr unsigned int PRINT_PROBABILITY_PRECISION = 20;
/* Beta prior parameters for the slice variable */
constexpr double SLICE_ALPHA = 10.0;
constexpr double SLICE_BETA = 1.0;
const double slice_normalization = lgamma(SLICE_ALPHA + SLICE_BETA) - lgamma(SLICE_ALPHA) - lgamma(SLICE_BETA);
/* TODO: the following is for debugging; delete it */
#include <core/utility.h>
const thread_local core::string_map_scribe* debug_terminal_printer;
const thread_local core::string_map_scribe* debug_nonterminal_printer;
thread_local bool debug_flag = false;
thread_local bool detect_duplicate_logical_forms = false;
#include "grammar.h"
#include <core/map.h>
#include <math/distributions.h>
#include <math/log.h>
#include <mutex>
#include <set>
thread_local double minimum_priority = 0.0;
thread_local const char* parser_prefix = "";
using namespace core;
template<typename Semantics>
struct tokenized_sentence
{
template<typename LabelSemantics, class Enable = void> struct node_label;
template<typename LabelSemantics>
struct node_label<LabelSemantics, typename std::enable_if<!std::is_empty<LabelSemantics>::value>::type> {
unsigned int nonterminal;
LabelSemantics logical_form;
node_label(unsigned int nonterminal, const LabelSemantics& logical_form) :
nonterminal(nonterminal), logical_form(logical_form) { }
static inline unsigned int hash(const node_label<LabelSemantics>& key) {
return default_hash(key.nonterminal) ^ LabelSemantics::hash(key.logical_form);
}
static inline bool is_empty(const node_label<LabelSemantics>& key) {
return key.nonterminal == 0;
}
static inline void move(const node_label<LabelSemantics>& src, node_label<LabelSemantics>& dst) {
dst.nonterminal = src.nonterminal;
core::move(src.logical_form, dst.logical_form);
}
static inline void free(node_label<LabelSemantics>& src) {
core::free(src.logical_form);
}
inline bool operator == (const node_label<Semantics>& other) {
return nonterminal == other.nonterminal
&& logical_form == other.logical_form;
}
};
template<typename LabelSemantics>
struct node_label<LabelSemantics, typename std::enable_if<std::is_empty<LabelSemantics>::value>::type> {
unsigned int nonterminal;
node_label(unsigned int nonterminal, const LabelSemantics& logical_form) : nonterminal(nonterminal) { }
static inline unsigned int hash(const node_label<LabelSemantics>& key) {
return default_hash(key.nonterminal);
}
static inline bool is_empty(const node_label<LabelSemantics>& key) {
return key.nonterminal == 0;
}
static inline void move(const node_label<LabelSemantics>& src, node_label<LabelSemantics>& dst) {
dst.nonterminal = src.nonterminal;
}
static inline void free(node_label<LabelSemantics>& src) { }
inline bool operator == (const node_label<LabelSemantics>& other) {
return nonterminal == other.nonterminal;
}
};
unsigned int length;
syntax_node<Semantics>** tokens;
unsigned int* end_terminal;
/* cache for storing probabilities of fixed subtrees */
hash_map<node_label<Semantics>, double>* cache;
tokenized_sentence(sequence sentence) : length(0), tokens(NULL), end_terminal(NULL), cache(NULL)
{
if (!initialize(sentence))
exit(EXIT_FAILURE);
}
tokenized_sentence(syntax_node<Semantics>** token_array, unsigned int count) :
length(0), tokens(NULL), end_terminal(NULL), cache(NULL)
{
if (!initialize(token_array, count))
exit(EXIT_FAILURE);
}
~tokenized_sentence() { free(); }
template<typename Distribution, typename StringMapType>
double subtree_probability(
grammar<Semantics, Distribution>& G,
unsigned int nonterminal,
const Semantics& logical_form,
const StringMapType& token_map,
unsigned int index)
{
if (!cache[index].check_size())
exit(EXIT_FAILURE);
bool contains; unsigned int bucket;
double& probability = cache[index].get(node_label<Semantics>(nonterminal, logical_form), contains, bucket);
if (!contains) {
/* cache doesn't contain this entry, so compute and store it */
probability = log_probability(G, *tokens[index], logical_form, token_map, nonterminal);
cache[index].table.keys[bucket] = {nonterminal, logical_form};
cache[index].table.size++;
}
return probability;
}
static inline void free(tokenized_sentence<Semantics>& sequence) {
sequence.free();
}
private:
inline bool initialize(sequence sentence) {
if (!resize(sentence.length)) {
free(); return false;
}
for (unsigned int i = 0; i < sentence.length; i++)
{
tokens[length] = (syntax_node<Semantics>*) malloc(sizeof(syntax_node<Semantics>));
if (tokens[length] == NULL) {
fprintf(stderr, "tokenized_sentence ERROR: Insufficient memory for syntax_node.\n");
free(); return false;
} else if (!init(*tokens[length], {sentence.tokens + i, 1})) {
fprintf(stderr, "tokenized_sentence ERROR: Insufficient memory for cache.\n");
core::free(tokens[length]);
free(); return false;
} else if (!hash_map_init(cache[length], 32)) {
fprintf(stderr, "tokenized_sentence ERROR: Insufficient memory for cache.\n");
core::free(*tokens[length]); core::free(tokens[length]);
free(); return false;
}
length++;
}
for (unsigned int i = 0; i < length; i++)
end_terminal[i] = length;
return true;
}
inline bool initialize(syntax_node<Semantics>** token_array, unsigned int count) {
unsigned int capacity = 1 << (core::log2(count) + 2);
if (!resize(capacity)) {
free(); return false;
}
for (unsigned int i = 0; i < count; i++)
{
if (!ensure_capacity(capacity, length + token_array[i]->right.length)) {
free(); return false;
}
if (token_array[i]->is_terminal()) {
for (unsigned int j = 0; j < token_array[i]->right.length; j++) {
tokens[length] = (syntax_node<Semantics>*) malloc(sizeof(syntax_node<Semantics>));
if (tokens[length] == NULL) {
fprintf(stderr, "tokenized_sentence ERROR: Insufficient memory for syntax_node.\n");
free(); return false;
} else if (!init(*tokens[length], {token_array[i]->right.nonterminals + j, 1})) {
fprintf(stderr, "tokenized_sentence ERROR: Insufficient memory for cache.\n");
core::free(tokens[length]);
free(); return false;
} else if (!hash_map_init(cache[length], 32)) {
fprintf(stderr, "tokenized_sentence ERROR: Insufficient memory for cache.\n");
core::free(*tokens[length]); core::free(tokens[length]);
free(); return false;
}
length++;
}
} else {
tokens[length] = token_array[i];
if (!hash_map_init(cache[length], 32)) {
fprintf(stderr, "tokenized_sentence ERROR: Insufficient memory for cache.\n");
free(); return false;
}
tokens[length]->reference_count++;
length++;
}
}
unsigned int next_nonterminal = length;
for (unsigned int i = length; i > 0; i--) {
if (!tokens[i - 1]->is_terminal())
next_nonterminal = i - 1;
end_terminal[i - 1] = next_nonterminal;
}
return true;
}
inline void free()
{
if (tokens != NULL) {
for (unsigned int j = 0; j < length; j++) {
if (tokens[j] != NULL)
core::free(*tokens[j]);
if (tokens[j] != NULL && tokens[j]->reference_count == 0)
core::free(tokens[j]);
}
core::free(tokens);
}
if (cache != NULL) {
for (unsigned int j = 0; j < length; j++) {
for (auto entry : cache[j])
core::free(entry.key);
core::free(cache[j]);
}
core::free(cache);
}
if (end_terminal != NULL)
core::free(end_terminal);
}
inline bool ensure_capacity(unsigned int& capacity, unsigned int new_length) {
if (new_length > capacity) {
core::expand_capacity(capacity, new_length);
return resize(capacity);
}
return true;
}
inline bool resize(unsigned int new_capacity)
{
auto new_tokens = (syntax_node<Semantics>**)
realloc(tokens, sizeof(syntax_node<Semantics>*) * new_capacity);
auto new_cache = (hash_map<node_label<Semantics>, double>*)
realloc(static_cast<void*>(cache), sizeof(hash_map<node_label<Semantics>, double>) * new_capacity);
auto new_end_terminal = (unsigned int*) realloc(
end_terminal, sizeof(unsigned int) * new_capacity);
if (new_tokens == NULL || new_cache == NULL || new_end_terminal == NULL) {
fprintf(stderr, "tokenized_sentence.ensure_capacity ERROR: Out of memory.\n");
return false;
}
tokens = new_tokens;
cache = new_cache;
end_terminal = new_end_terminal;
return true;
}
template<typename A>
friend bool init(tokenized_sentence<A>&, syntax_node<A>**, unsigned int);
};
template<typename Semantics>
inline bool init(tokenized_sentence<Semantics>& tokens, syntax_node<Semantics>** token_array, unsigned int count)
{
tokens.length = 0; tokens.tokens = NULL;
tokens.end_terminal = NULL; tokens.cache = NULL;
return tokens.initialize(token_array, count);
}
enum parse_mode {
MODE_SAMPLE,
MODE_PARSE,
MODE_COMPUTE_BOUNDS,
MODE_GENERATE
};
/* forward declarations */
template<parse_mode Mode, typename Semantics> struct cell_value;
template<parse_mode Mode, typename Semantics, typename StringMapType> struct chart;
template<parse_mode Mode, typename Semantics, class Enable = void> struct agenda;
struct span {
unsigned int start;
unsigned int end;
inline unsigned int length() const {
return end - start;
}
};
template<typename Stream>
inline bool print(const span& positions, Stream& out) {
return fprintf(out, "[%u, %u]", positions.start, positions.end) >= 0;
}
inline bool is_negative_inf(double value) {
return (value == -std::numeric_limits<double>::infinity());
}
template<parse_mode Mode, typename Semantics, class Enable = void>
struct syntax_state;
template<parse_mode Mode, typename Semantics>
struct syntax_state<Mode, Semantics, typename std::enable_if<
Mode == MODE_SAMPLE || Mode == MODE_COMPUTE_BOUNDS>::type>
{
/* for sampling, we only record the rule */
rule<Semantics> r;
syntax_state(const syntax_node<Semantics>* const* terminal_tokens, unsigned int length) :
r(terminal_tokens, length) { }
syntax_state(const syntax_node<Semantics>* nonterminal_token) : r(nonterminal_token->right) {
/* we don't need information about subtree tokens
when sampling or computing log probability bounds */
}
syntax_state(const sequence& terminal) : r(terminal) { }
syntax_state(const rule<Semantics>& r) : r(r) { }
syntax_state(const syntax_state<Mode, Semantics>& src) : r(src.r) { }
inline rule<Semantics>& get_rule() {
return r;
}
inline const rule<Semantics>& get_rule() const {
return r;
}
inline const syntax_node<Semantics>& get_tree() const {
fprintf(stderr, "syntax_state.get_tree ERROR: This function can only be called in PARSE mode.\n");
exit(EXIT_FAILURE);
}
inline bool operator == (const syntax_state<Mode, Semantics>& other) const {
return r == other.r;
}
static inline void free(syntax_state<Mode, Semantics>& state) {
core::free(state.r);
}
};
template<parse_mode Mode, typename Semantics>
struct syntax_state<Mode, Semantics, typename std::enable_if<
Mode == MODE_PARSE || Mode == MODE_GENERATE>::type>
{
syntax_node<Semantics> tree;
syntax_state(const syntax_node<Semantics>* const* terminal_tokens, unsigned int length) :
tree(terminal_tokens, length) { }
syntax_state(const syntax_node<Semantics>* nonterminal_token) : tree(*nonterminal_token) { }
syntax_state(const sequence& terminal) : tree(terminal) { }
syntax_state(const rule<Semantics>& r) : tree(r) { }
syntax_state(const syntax_state<Mode, Semantics>& src) : tree(src.tree) { }
inline rule<Semantics>& get_rule() {
return tree.right;
}
inline const rule<Semantics>& get_rule() const {
return tree.right;
}
inline const syntax_node<Semantics>& get_tree() const {
return tree;
}
inline bool operator == (const syntax_state<Mode, Semantics>& other) const {
return tree == other.tree;
}
static inline void free(syntax_state<Mode, Semantics>& state) {
core::free(state.tree);
}
};
template<parse_mode Mode, typename Semantics, typename std::enable_if<
Mode == MODE_SAMPLE || Mode == MODE_COMPUTE_BOUNDS>::type* = nullptr>
inline bool init(syntax_state<Mode, Semantics>& state, const rule<Semantics>& r)
{
state.r = r;
return true;
}
template<parse_mode Mode, typename Semantics, typename std::enable_if<
Mode == MODE_SAMPLE || Mode == MODE_COMPUTE_BOUNDS>::type* = nullptr>
inline bool init(
syntax_state<Mode, Semantics>& state,
const syntax_state<Mode, Semantics>& src)
{
state.r = src.r;
return true;
}
template<parse_mode Mode, typename Semantics, typename std::enable_if<
Mode == MODE_PARSE || Mode == MODE_GENERATE>::type* = nullptr>
inline bool init(syntax_state<Mode, Semantics>& state, const rule<Semantics>& r) {
return init(state.tree, r);
}
template<parse_mode Mode, typename Semantics, typename std::enable_if<
Mode == MODE_PARSE || Mode == MODE_GENERATE>::type* = nullptr>
inline bool init(
syntax_state<Mode, Semantics>& state,
const syntax_state<Mode, Semantics>& src)
{
return init(state.tree, src.tree);
}
template<parse_mode Mode, typename Semantics, typename Stream, typename NonterminalPrinter, typename TerminalPrinter,
typename std::enable_if<Mode == MODE_SAMPLE || Mode == MODE_COMPUTE_BOUNDS>::type* = nullptr>
inline bool print(const syntax_state<Mode, Semantics>& syntax, Stream& stream,
NonterminalPrinter& nonterminal_printer, TerminalPrinter& terminal_printer)
{
return print(syntax.r, stream, make_pair<TerminalPrinter&, NonterminalPrinter&>(terminal_printer, nonterminal_printer));
}
template<parse_mode Mode, typename Semantics, typename Stream, typename NonterminalPrinter, typename TerminalPrinter,
typename std::enable_if<Mode == MODE_SAMPLE || Mode == MODE_COMPUTE_BOUNDS>::type* = nullptr>
inline bool print(
const syntax_state<Mode, Semantics>& syntax, Stream& stream, unsigned int indent,
NonterminalPrinter& nonterminal_printer, TerminalPrinter& terminal_printer) {
return print(syntax, stream, nonterminal_printer, terminal_printer);
}
template<parse_mode Mode, typename Semantics, typename Stream, typename NonterminalPrinter, typename TerminalPrinter,
typename std::enable_if<Mode == MODE_PARSE || Mode == MODE_GENERATE>::type* = nullptr>
inline bool print(
const syntax_state<Mode, Semantics>& syntax, Stream& stream, unsigned int indent,
NonterminalPrinter& nonterminal_printer, TerminalPrinter& terminal_printer)
{
return print(syntax.tree, stream, indent, nonterminal_printer, terminal_printer);
}
template<parse_mode Mode, typename Semantics, typename Stream, typename NonterminalPrinter, typename TerminalPrinter,
typename std::enable_if<Mode == MODE_PARSE || Mode == MODE_GENERATE>::type* = nullptr>
inline bool print(const syntax_state<Mode, Semantics>& syntax, Stream& stream,
NonterminalPrinter& nonterminal_printer, TerminalPrinter& terminal_printer) {
return print(syntax.tree, stream, 0, nonterminal_printer, terminal_printer);
}
template<parse_mode Mode, typename Semantics>
struct rule_state {
syntax_state<Mode, Semantics> syntax;
double log_probability;
cell_value<Mode, Semantics>* cell;
Semantics logical_form_set; /* TODO: the logical form is unnecessary in syntactic parsing */
unsigned int rule_position;
unsigned int nonterminal;
/* sentence positions */
unsigned int* positions;
/* TODO: do we need reference counting? is it actually faster than only
freeing unique rule states in the chart? (which involves keeping a hash
set of freed rule states) */
unsigned int reference_count;
#if defined(PRINT_SEARCH_STATES)
unsigned int iteration;
#endif
static inline void free(rule_state<Mode, Semantics>& state) {
state.reference_count--;
if (state.reference_count == 0) {
core::free(state.syntax);
if (Mode != MODE_COMPUTE_BOUNDS)
core::free(state.logical_form_set);
if (Mode != MODE_GENERATE)
core::free(state.positions);
}
}
};
template<parse_mode Mode, typename Semantics>
inline bool init(rule_state<Mode, Semantics>& state,
unsigned int nonterminal, const rule<Semantics>& r, span position)
{
#if !defined(NDEBUG)
if (r.is_terminal())
fprintf(stderr, "init WARNING: A terminal rule was specified when initializing rule_state.\n");
#endif
state.nonterminal = nonterminal;
if (Mode != MODE_GENERATE) {
state.positions = (unsigned int*) malloc(sizeof(unsigned int) * (r.nt.length + 1));
if (state.positions == NULL) {
fprintf(stderr, "init ERROR: Unable to initialize position array in new rule_state.\n");
return false;
}
state.positions[0] = position.start;
state.positions[r.nt.length] = position.end;
}
if (!init(state.syntax, r)) {
if (Mode != MODE_GENERATE) free(state.positions);
return false;
}
state.reference_count = 1;
return true;
}
template<parse_mode Mode, typename Semantics, typename std::enable_if<
Mode == MODE_SAMPLE || Mode == MODE_COMPUTE_BOUNDS>::type* = nullptr>
inline bool add_child(
syntax_state<Mode, Semantics>& state,
const syntax_state<Mode, Semantics>& child,
unsigned int rule_position)
{
return true;
}
template<parse_mode Mode, typename Semantics, typename std::enable_if<
Mode == MODE_PARSE || Mode == MODE_GENERATE>::type* = nullptr>
inline bool add_child(
syntax_state<Mode, Semantics>& state,
const syntax_state<Mode, Semantics>& child,
unsigned int rule_position)
{
state.tree.children[rule_position] =
(syntax_node<Semantics>*) malloc(sizeof(syntax_node<Semantics>));
if (state.tree.children[rule_position] == NULL) {
fprintf(stderr, "add_child ERROR: Out of memory.\n");
return false;
}
*state.tree.children[rule_position] = child.tree;
return true;
}
template<parse_mode Mode, typename Semantics>
inline bool init(
rule_state<Mode, Semantics>& state,
const rule_state<Mode, Semantics>& src,
const syntax_state<Mode, Semantics>& syntax)
{
const rule<Semantics>& rule = src.syntax.get_rule();
#if !defined(NDEBUG)
if (rule.is_terminal())
fprintf(stderr, "init WARNING: A terminal rule was specified when initializing rule_state.\n");
#endif
state.nonterminal = src.nonterminal;
state.log_probability = src.log_probability;
if (Mode != MODE_GENERATE) {
state.positions = (unsigned int*) malloc(sizeof(unsigned int) * (rule.nt.length + 1));
if (state.positions == NULL) {
fprintf(stderr, "init ERROR: Unable to initialize position array in new rule_state.\n");
return false;
}
for (unsigned int i = 0; i < src.rule_position + 2; i++)
state.positions[i] = src.positions[i];
state.positions[rule.nt.length] = src.positions[rule.nt.length];
}
if (!init(state.syntax, src.syntax)) {
if (Mode != MODE_GENERATE) free(state.positions);
return false;
} else if (!add_child(state.syntax, syntax, src.rule_position)) {
if (Mode != MODE_GENERATE) free(state.positions);
free(state.syntax);
return false;
}
state.reference_count = 1;
return true;
}
template<typename Stream>
inline bool print_rule_positions(const unsigned int* positions,
unsigned int rule_position, unsigned int rule_length, Stream& out)
{
if (!print('[', out)) return false;
if (rule_length == 0)
return print(']', out);
if (!print(positions[0], out)) return false;
for (unsigned int i = 1; i <= rule_position + 1; i++) {
if (!print(", ", out) || !print(positions[i], out))
return false;
}
if (rule_position + 1 == rule_length) {
return print(']', out);
} else if (rule_position + 1 < rule_length && rule_length > 2)
if (!print(", ...", out)) return false;
return print(", ", out) && print(positions[rule_length], out) && print(']', out);
}
template<parse_mode Mode, typename Semantics, typename Stream,
typename NonterminalPrinter, typename TerminalPrinter>
inline bool print(
const rule_state<Mode, Semantics>& state, Stream& out, unsigned int indent,
NonterminalPrinter& nonterminal_printer, TerminalPrinter& terminal_printer)
{
const rule<Semantics>& r = state.syntax.get_rule();
return print("nonterminal = ", out) && print(state.nonterminal, out, nonterminal_printer)
&& print('\n', out) && print_indent(indent, out) && print("syntax: ", out) && print(state.syntax, out, indent, nonterminal_printer, terminal_printer)
&& (Mode == MODE_COMPUTE_BOUNDS || (print('\n', out) && print_indent(indent, out) && print("logical_form: ", out) && print(state.logical_form_set, out, terminal_printer)))
&& print('\n', out) && print_indent(indent, out) && print("log_probability: ", out) && print(state.log_probability, out, PRINT_PROBABILITY_PRECISION)
&& print('\n', out) && print_indent(indent, out) && print("rule_position: ", out) && print(state.rule_position, out)
&& (Mode == MODE_GENERATE || (print('\n', out) && print_indent(indent, out) && print("positions: ", out) && print_rule_positions(state.positions, state.rule_position, r.nt.length, out)))
#if defined(PRINT_SEARCH_STATES)
&& (state.iteration == 0 || (print('\n', out) && print_indent(indent, out) && print("(processed at iteration ", out) && print(state.iteration, out) && print(')', out)));
#else
&& true;
#endif
}
template<parse_mode Mode, typename Semantics, typename Stream,
typename NonterminalPrinter, typename TerminalPrinter>
inline bool print(const rule_state<Mode, Semantics>& state, Stream& out,
NonterminalPrinter& nonterminal_printer, TerminalPrinter& terminal_printer) {
return print(state, out, 0, nonterminal_printer, terminal_printer);
}
template<parse_mode Mode, typename Semantics>
struct nonterminal_state {
double log_probability;
syntax_state<Mode, Semantics> syntax;
Semantics logical_form_set; /* TODO: the logical form is unnecessary in syntactic parsing */
unsigned int* positions;
#if defined(PRINT_SEARCH_STATES)
unsigned int iteration;
#endif
static inline void free(nonterminal_state<Mode, Semantics>& state) {
core::free(state.syntax);
if (Mode != MODE_COMPUTE_BOUNDS)
core::free(state.logical_form_set);
if (Mode != MODE_GENERATE)
core::free(state.positions);
}
};
template<parse_mode Mode, typename Semantics>
inline bool init(nonterminal_state<Mode, Semantics>& state,
const syntax_state<Mode, Semantics>& syntax,
const unsigned int* positions,
const Semantics& logical_form_set,
double priority)
{
const rule<Semantics>& rule = syntax.get_rule();
if (Mode != MODE_GENERATE) {
state.positions = (unsigned int*) malloc(
sizeof(unsigned int) * (rule.is_terminal() ? 2 : (rule.nt.length + 1)));
if (state.positions == NULL) return false;
memcpy(state.positions, positions,
sizeof(unsigned int) * (rule.is_terminal() ? 2 : (rule.nt.length + 1)));
}
state.log_probability = priority;
if (!init(state.syntax, syntax)) {
if (Mode != MODE_GENERATE) free(state.positions);
return false;
}
if (Mode != MODE_COMPUTE_BOUNDS)
state.logical_form_set = logical_form_set;
return true;
}
/* for computing logsumexp of an array of nonterminal_states */
template<typename Semantics>
inline double log_probability(const nonterminal_state<MODE_SAMPLE, Semantics>& state) {
return state.log_probability;
}
template<parse_mode Mode, typename Semantics>
struct nonterminal_iterator_state
{
unsigned int nonterminal;
syntax_state<Mode, Semantics> syntax;
cell_value<Mode, Semantics>* cell;
unsigned int* positions;
weighted<Semantics>* posterior;
unsigned int posterior_length;
unsigned int iterator;
static inline void free(nonterminal_iterator_state<Mode, Semantics>& state) {
core::free(state.syntax);
if (Mode != MODE_GENERATE)
core::free(state.positions);
for (unsigned int i = 0; i < state.posterior_length; i++)
core::free(state.posterior[i]);
core::free(state.posterior);
}
};
template<parse_mode Mode, typename Semantics, typename StringMapType>
inline bool init(
nonterminal_iterator_state<Mode, Semantics>& state,
chart<Mode, Semantics, StringMapType>& parse_chart,
unsigned int nonterminal, double inner_probability,
const syntax_state<Mode, Semantics>& syntax,
weighted<Semantics>* posterior,
unsigned int posterior_length,
cell_value<Mode, Semantics>* cell,
unsigned int* positions)
{
const rule<Semantics>& rule = syntax.get_rule();
state.nonterminal = nonterminal;
state.cell = cell;
state.posterior_length = posterior_length;
state.posterior = posterior;
unsigned int length = rule.is_terminal() ? 2 : (rule.nt.length + 1);
if (Mode != MODE_GENERATE) {
state.positions = (unsigned int*) malloc(sizeof(unsigned int) * length);
if (state.positions == NULL) {
fprintf(stderr, "init ERROR: Unable to initialize "
"position array in new nonterminal_iterator_state.\n");
return false;
}
memcpy(state.positions, positions, sizeof(unsigned int) * length);
}
if (!init(state.syntax, syntax)) {
if (Mode != MODE_GENERATE) free(state.positions);
return false;
}
for (unsigned int i = 0; i < posterior_length; i++) {
posterior[i].log_probability += inner_probability;
double old_prior = 0.0;
if (Mode != MODE_SAMPLE && Mode != MODE_GENERATE && Mode != MODE_COMPUTE_BOUNDS)
old_prior = min(log_probability<false>(posterior[i].object), cell->prior_probability);
if (USE_NONTERMINAL_PREITERATOR) {
double right, prior = old_prior;
if (!rule.is_terminal() && (Mode == MODE_PARSE || Mode == MODE_GENERATE)) {
right_probability(rule, posterior[i].object, positions, parse_chart, old_prior, right, prior);
posterior[i].log_probability += right;
} else if (Mode != MODE_SAMPLE) {
posterior[i].log_probability += old_prior;
}
} else {
posterior[i].log_probability += old_prior;
}
}
if (state.posterior_length > 1)
sort(state.posterior, state.posterior_length, default_sorter());
while (state.posterior_length > 0) {
if (!std::isinf(posterior[state.posterior_length - 1].log_probability))
break;
free(posterior[state.posterior_length - 1]);
state.posterior_length--;
}
return true;
}
template<parse_mode Mode, typename Semantics, typename Stream,
typename NonterminalPrinter, typename TerminalPrinter>
inline bool print(const nonterminal_iterator_state<Mode, Semantics>& state, Stream& out,
NonterminalPrinter& nonterminal_printer, TerminalPrinter& terminal_printer)
{
const rule<Semantics>& r = state.syntax.get_rule();
unsigned int length = r.is_terminal() ? 2 : (r.nt.length + 1);
return print("nonterminal = ", out) && print(state.nonterminal, out, nonterminal_printer)
&& print("\nnext logical form: ", out) && print(state.posterior[state.iterator].object, out, terminal_printer)
&& print("\nnext log probability: ", out) && print(state.posterior[state.iterator].log_probability, out, PRINT_PROBABILITY_PRECISION)
&& print("\nsyntax: ", out) && print(state.syntax, out, nonterminal_printer, terminal_printer)
&& (Mode == MODE_GENERATE || (print("\npositions: ", out) && print(state.positions, length, out)));
}
template<parse_mode Mode, typename Semantics>
struct invert_iterator_state {
rule_state<Mode, Semantics>* rule;
Semantics* inverse; /* TODO: the inverter is unnecessary in syntactic parsing */
unsigned int inverse_count;
unsigned int index;
syntax_state<Mode, Semantics> syntax; /* TODO: during sampling, this field is unnecessary */
double log_probability;
static inline void free(invert_iterator_state<Mode, Semantics>& state)
{
if (Mode != MODE_COMPUTE_BOUNDS) {
for (unsigned int i = 0; i < state.inverse_count; i++)
core::free(state.inverse[i]);
core::free(state.inverse);
}
core::free(state.syntax);
core::free(*state.rule);
if (state.rule->reference_count == 0)
core::free(state.rule);
}
};
template<parse_mode Mode, typename Semantics, typename Stream,
typename NonterminalPrinter, typename TerminalPrinter>
inline bool print(const invert_iterator_state<Mode, Semantics>& state, Stream& out,
NonterminalPrinter& nonterminal_printer, TerminalPrinter& terminal_printer)
{
return print("\nlog_probability: ", out) && print(state.log_probability, out, PRINT_PROBABILITY_PRECISION)
&& (Mode == MODE_COMPUTE_BOUNDS || (print("\ninverted logical form: ", out) && print(state.inverse[state.index], out, terminal_printer)))
&& print("\nsyntax: ", out) && print(state.syntax, out, nonterminal_printer, terminal_printer)
&& print("\nrule state: ", out) && print(*state.rule, out, 1, nonterminal_printer, terminal_printer);
}
template<parse_mode Mode, typename Semantics>
struct rule_completer_state {
cell_value<Mode, Semantics>* cell;
Semantics logical_form_set; /* TODO: the logical form is unnecessary in syntactic parsing */
syntax_state<Mode, Semantics> syntax; /* TODO: during sampling, this field is unnecessary */
double log_probability;
span position;
const array<rule_state<Mode, Semantics>*>* waiting_states;
unsigned int iterator;
static inline void free(rule_completer_state<Mode, Semantics>& state) {
if (Mode != MODE_COMPUTE_BOUNDS)
core::free(state.logical_form_set);
core::free(state.syntax);
}
};
template<parse_mode Mode, typename Semantics, typename Stream,
typename NonterminalPrinter, typename TerminalPrinter>
inline bool print(const rule_completer_state<Mode, Semantics>& state, Stream& out,
NonterminalPrinter& nonterminal_printer, TerminalPrinter& terminal_printer)
{
return print("\nlog_probability: ", out) && print(state.log_probability, out, PRINT_PROBABILITY_PRECISION)
&& print("\nlogical_form: ", out) && print(state.logical_form_set, out, terminal_printer)
&& print("\nsyntax: ", out) && print(state.syntax, out, nonterminal_printer, terminal_printer)
&& (Mode == MODE_GENERATE || (print("\nposition: ", out) && print(state.position, out)))
&& print("\nwaiting state: ", out) && print(*state.waiting_states->data[state.iterator], out, 1, nonterminal_printer, terminal_printer);
}
template<typename Semantics>
inline void completer_log_probability(
rule_completer_state<MODE_SAMPLE, Semantics>& completer,
const array<nonterminal_state<MODE_SAMPLE, Semantics>>& nonterminals)
{
completer.log_probability = logsumexp(nonterminals.data, (unsigned int) nonterminals.length);
}
template<parse_mode Mode, typename Semantics, typename std::enable_if<Mode != MODE_SAMPLE>::type* = nullptr>
inline void completer_log_probability(
rule_completer_state<Mode, Semantics>& completer,
const array<nonterminal_state<Mode, Semantics>>& nonterminals)
{ }
/* for iterating over terminals in order of descending probability during generation */
template<parse_mode Mode, typename Semantics>
struct terminal_iterator_state
{
unsigned int nonterminal;
cell_value<Mode, Semantics>* cell;
Semantics logical_form;
weighted<sequence>* terminals;
unsigned int terminal_count;
unsigned int iterator;
static inline void free(terminal_iterator_state<Mode, Semantics>& state) {
for (unsigned int i = 0; i < state.terminal_count; i++)
core::free(state.terminals[i]);
core::free(state.terminals);
core::free(state.logical_form);
}
};
template<parse_mode Mode, typename Semantics>
bool init(terminal_iterator_state<Mode, Semantics>& iterator,
unsigned int nonterminal, cell_value<Mode, Semantics>* cell,
const Semantics& logical_form, weighted<sequence>* terminals,
unsigned int terminal_count)
{
iterator.nonterminal = nonterminal;
iterator.cell = cell;
iterator.terminals = terminals;
iterator.terminal_count = terminal_count;
iterator.iterator = 0;
iterator.logical_form = logical_form;
return true;
}
template<parse_mode Mode, typename Semantics, typename Stream,
typename NonterminalPrinter, typename TerminalPrinter>
inline bool print(const terminal_iterator_state<Mode, Semantics>& state, Stream& out,
NonterminalPrinter& nonterminal_printer, TerminalPrinter& terminal_printer)
{
return print("nonterminal = ", out) && print(state.nonterminal, out, nonterminal_printer)
&& print("\nlogical form: ", out) && print(state.logical_form, out, terminal_printer)
&& print("\nnext terminal: ", out) && print(state.terminals[state.iterator].object, out, terminal_printer)
&& print("\nnext log probability: ", out) && print(state.terminals[state.iterator].log_probability, out, PRINT_PROBABILITY_PRECISION);
}
enum search_phase {
PHASE_RULE,
PHASE_TERMINAL_ITERATOR,
PHASE_NONTERMINAL_ITERATOR,
PHASE_INVERT_ITERATOR,
PHASE_RULE_COMPLETER
};
template<parse_mode Mode, typename Semantics>
struct parser_search_state {
double priority;
search_phase phase;
union {
rule_state<Mode, Semantics>* rule;
terminal_iterator_state<Mode, Semantics>* terminal_iterator;
nonterminal_iterator_state<Mode, Semantics>* nonterminal_iterator;
invert_iterator_state<Mode, Semantics>* invert_iterator;
rule_completer_state<Mode, Semantics>* rule_completer;
};
#if defined(PRINT_SEARCH_STATES)
unsigned int iteration;
#endif
inline double get_priority() const {
return priority;
}
static inline void free(parser_search_state<Mode, Semantics>& state) {
switch (state.phase) {
case PHASE_RULE:
core::free(*state.rule);
if (state.rule->reference_count == 0)
core::free(state.rule);
break;
case PHASE_TERMINAL_ITERATOR:
core::free(*state.terminal_iterator); core::free(state.terminal_iterator); break;
case PHASE_NONTERMINAL_ITERATOR:
core::free(*state.nonterminal_iterator); core::free(state.nonterminal_iterator); break;
case PHASE_INVERT_ITERATOR:
core::free(*state.invert_iterator); core::free(state.invert_iterator); break;
case PHASE_RULE_COMPLETER:
break;
}
}
};
template<parse_mode Mode, typename Semantics>
inline bool operator < (
const parser_search_state<Mode, Semantics>& first,
const parser_search_state<Mode, Semantics>& second)
{
if (first.get_priority() < second.get_priority()) return true;
else if (first.get_priority() > second.get_priority()) return false;
return (first.phase == PHASE_RULE_COMPLETER && second.phase != PHASE_RULE_COMPLETER);
}
template<parse_mode Mode, typename Semantics, typename Stream>
inline bool print_iteration(const parser_search_state<Mode, Semantics>& state, Stream& out)
{
#if defined(PRINT_SEARCH_STATES)
fprintf(stderr, "\n(created on iteration %u)", state.iteration);
#endif
return true;
}
template<parse_mode Mode, typename Semantics, typename Stream,
typename NonterminalPrinter, typename TerminalPrinter>
inline bool print(const parser_search_state<Mode, Semantics>& state, Stream&& out,
NonterminalPrinter& nonterminal_printer, TerminalPrinter& terminal_printer)