-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.py
More file actions
1638 lines (1390 loc) · 67.2 KB
/
start.py
File metadata and controls
1638 lines (1390 loc) · 67.2 KB
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
import time
from collections import defaultdict
from typing import List, Tuple, Set, Dict, Optional, Union
import statistics
from bubble import Bubble
from group import group, is_balanced
from oracle import ExternalOracle, ParseException
from parse_tree import ParseNode, ParseTreeList, build_grammar, START
from grammar import *
from token_expansion import expand_tokens
from union import UnionFind
from replacement_utils import get_strings_with_replacement, get_strings_with_replacement_in_rule, \
lvl_n_derivable
import config
from next_tid import allocate_tid
from PrettyPrint import PrettyPrintTree
from label_llm import generate_label_api, regenerate_label
from bubble_llm import bubble_api
from bubble_pair_llm import bubble_pair_api
import json
import string
"""
Bulk of the Arvada algorithm.
"""
###################### Settings for ICSE'24 Submission #########################
# MAX_SAMPLES_PER_COALESCE = 50 << number of strings to sample from the #
# grammar induced by a marge. Increase to #
# increase chance of catching unsound #
# merges, at the cost of runtime. #
# MAX_GROUP_LEN = 10 << max number of elements in a bubble. #
# Reducing will decrease runtime of algo, #
# at cost of missing some bubblings #
# #
# MUST_EXPAND_IN_COALESCE = False << additional setting, requiring a merge to #
# not only be valid, but also expand the #
# language accepted by the learned grammar #
# MUST_EXPAND_IN_PARTIAL= False << same thing but for partial merges #
###############################################################################
MAX_SAMPLES_PER_COALESCE = 50
MIN_GROUP_LEN = 3
MAX_GROUP_LEN = 10
MUST_EXPAND_IN_COALESCE = False
MUST_EXPAND_IN_PARTIAL= False
ORIGINAL_COALESCE_TIME = 0
BUILD_TIME = 0
LAST_COALESCE_TIME = 0
EXPAND_TIME = 0
MINIMIZE_TIME = 0
TIME_GENERATING_EXAMPLES = 0
TIME_GROUPING = 0
REAPPLY = 0
LLM_CALLS = 0
USE_LLM = config.USE_LLM
TREEVADA = config.TREEVADA
HDD = config.HDD
HALF_MERGE = True
def get_times():
from replacement_utils import TIME_GENERATING_EXAMPLES_INTERNAL
return {'FIRST_COALESCE' : ORIGINAL_COALESCE_TIME, 'BUILD': BUILD_TIME,
'LAST_COALESCE' : LAST_COALESCE_TIME, 'EXPAND': EXPAND_TIME, 'MINIMIZE': MINIMIZE_TIME,
'OVERALL_EXAMPLE_GEN': TIME_GENERATING_EXAMPLES + TIME_GENERATING_EXAMPLES_INTERNAL,
'OVERALL_GROUPING': TIME_GROUPING, 'REAPPLY_COUNT': REAPPLY}
def check_recall(oracle, grammar: Grammar):
"""
Helper function to check whether grammar is consistent with oracle.
"""
positives = grammar.sample_positives(10, 10)
for pos in positives:
try:
oracle.parse(pos)
except:
return False
return True
def build_start_grammar(oracle, leaves, bbl_bounds = (3,10)):
"""
ORACLE is a CachingOracle or ExternalOracle with a .parse method, which
returns True if the example given is in the ORACLE's language
LEAVES is a list of positive examples, each a list of characters.
Returns a grammar that maximally expands LEAVES w.r.t. ORACLE.
"""
global LAST_COALESCE_TIME
global EXPAND_TIME
global MINIMIZE_TIME
global MIN_GROUP_LEN
global MAX_GROUP_LEN
MIN_GROUP_LEN, MAX_GROUP_LEN = bbl_bounds
print('Building the starting trees...'.ljust(50), end='\r')
llm_trees, treevada_trees = build_trees(oracle, leaves)
print('Building initial grammar...'.ljust(50), end='\r')
llm_grammar, llm_hdd_grammar, treevada_grammar, treevada_hdd_grammar = None, None, None, None
for i, trees in enumerate([llm_trees, treevada_trees]):
if trees is None:
continue
grammar = build_grammar(trees)
print('Coalescing nonterminals...'.ljust(50), end='\r')
s = time.time()
grammar, new_trees, coalesce_caused, _ = coalesce(oracle, trees, grammar)
# grammar, new_trees, partial_coalesces = coalesce_partial(oracle, new_trees, grammar)
grammar = expand_tokens(oracle, grammar, new_trees)
grammar = minimize(grammar)
LAST_COALESCE_TIME += time.time() - s
if HDD:
augmented = {t.derived_string(): t for t in new_trees}
reduced_trees = hdd_decompose(new_trees, oracle, augmented)
if len(reduced_trees) > 0:
print(f"HDD decomposed {len(reduced_trees)} new trees.")
grammar_reduced = build_grammar(reduced_trees)
grammar_reduced = expand_tokens(oracle, grammar_reduced, reduced_trees)
new_trees += reduced_trees
grammar_reduced = minimize(grammar_reduced)
# print(str(grammar))
# print(str(grammar_reduced))
hdd_grammar = grammar.copy()
hdd_grammar.merge(grammar_reduced)
# hdd_grammar = minimize(hdd_grammar)
# hdd_grammar = expand_tokens(oracle, hdd_grammar, new_trees)
hdd_grammar = minimize(hdd_grammar)
else:
hdd_grammar = grammar
if i == 0:
llm_grammar = grammar
llm_hdd_grammar = hdd_grammar
else:
treevada_grammar = grammar
treevada_hdd_grammar = hdd_grammar
# s = time.time()
# EXPAND_TIME += time.time() - s
# print('Minimizing initial grammar...'.ljust(50), end='\r')
# s = time.time()
# MINIMIZE_TIME += time.time() - s
return llm_grammar, llm_hdd_grammar, treevada_grammar, treevada_hdd_grammar
def build_naive_parse_trees(leaves: List[List[ParseNode]], bracket_items: List, oracle: ExternalOracle):
"""
Builds naive parse trees for each leaf in `leaves`, assigning each unique
character to its own nonterminal, and uniting them all under the START
nonterminal.
bracket_items is a list of bracket enclosed sequence lengths.
"""
terminals = list(dict.fromkeys([leaf.payload for leaf_lst in leaves for leaf in leaf_lst]))
get_class = {t: t for t in terminals}
quotes = ["\"", "\'"]
def braces_tree(leaves: List[ParseNode], index: int, open_list: List[int], close_list: List[int], first: ParseNode = None):
"""
returns a initial parse tree based on brackets.
input: a {b c}
parse tree:
START
/ \
a t1
/ /\ \
{ b c }
"""
if first:
children = [first]
else:
nonlocal bracket_items
bracket_items = []
children = []
while index < len(leaves):
node = leaves[index]
token = node.payload
if (token == "{" or token == "[" or token == "(") and index in open_list:
index += 1
child, index = braces_tree(leaves, index, open_list, close_list, node)
children.append(child)
elif (token == "}" or token == "]" or token == ")") and index in close_list:
children.append(ParseNode(get_class[token], False, [node]))
bracket_items.append(len(children))
return ParseNode(allocate_tid(), False, children), index + 1
else:
children.append(ParseNode(get_class[token], False, [node]))
index += 1
bracket_items.append(len(children))
return ParseNode(START, False, children), bracket_items.copy()
trees=[]
bracket_counts=[]
avg_bracket_lengths_all_trees=[]
str_lengths = []
for leaf_list in leaves:
leaf_str = [leaf.payload for leaf in leaf_list]
open_close = is_balanced(leaf_str, is_list=True)
if open_close:
new_children, brackets = braces_tree(leaf_list, 0, open_close[0], open_close[1])
else:
print("Flat tree")
new_children = ParseNode(START, False, [ParseNode(get_class[leaf.payload], False, [leaf]) for leaf in leaf_list])
brackets = [len(new_children.children)]
new_children.update_cache_info()
try:
oracle.parse(new_children.derived_string())
except:
print("\nInvalid tree constructed!")
exit(1)
trees.append(new_children)
bracket_counts.append(len(brackets)) #brackets = per tree bracket lengths
avg_bracket_lengths_all_trees.append(sum(brackets)/len(brackets))
str_lengths.append(len(leaf_list))
avg_bracket_count = sum(bracket_counts)/len(bracket_counts) #bracket count across all trees
avg_bracket_lengths = sum(avg_bracket_lengths_all_trees)/len(avg_bracket_lengths_all_trees)
avg_n = sum(str_lengths)/len(str_lengths)
print(f"Average number of brackets: {avg_bracket_count}")
print(f"Average lengths of brackets: {avg_bracket_lengths}")
print(f"Average tokens: {avg_n}")
return trees
def hdd_decompose(trees: List[ParseNode], oracle: ExternalOracle, new_trees: dict[str, ParseNode]):
"""
Hierarchical delta debugging to break down seed inputs into smaller valid inputs.
new_trees contain the newly added decomposed trees
"""
# pt = PrettyPrintTree(lambda x: x.children, lambda x: x.payload)
def try_parse(node: ParseNode):
"""
Try to parse the node and remove single start->start indirections
"""
try:
seed = node.derived_string()
oracle.parse(seed)
# seed = seed.replace(" ", "")
if seed not in new_trees:
if node.payload != START:
node.payload = START
while len(node.children) == 1 and node.payload == node.children[0].payload:
node = node.children[0]
# Check all derivable strings at depth 1
for s in lvl_n_derivable([node], START, 1):
oracle.parse(s)
new_trees[seed] = node
return True
except:
return False
def ddmin(node: ParseNode):
"""
minimizes a flat level into a list of smaller valid levels
"""
reduced = []
n = len(node.children)
granularity = 2
while granularity <= n:
chunk_size = n // granularity
for i in range(granularity):
start = i * chunk_size
end = (i + 1) * chunk_size if i != granularity - 1 else n
trial_node = node.copy()
trial_node.children = trial_node.children[:start] + trial_node.children[end:]
trial_node.update_cache_info()
if try_parse(trial_node):
reduced.append(trial_node)
for i in range(granularity):
start = i * chunk_size
end = (i + 1) * chunk_size if i != granularity - 1 else n
trial_node = node.copy()
trial_node.children = node.children[start:end]
trial_node.update_cache_info()
if try_parse(trial_node):
reduced.append(trial_node)
if reduced:
return reduced
granularity += 1
return [node.copy()]
def hdd(node: ParseNode) -> List[ParseNode]:
if node.is_terminal:
return [node]
nodes = ddmin(node)
for node in nodes:
for index in range(len(node.children)):
idx_children = hdd(node.children[index].copy())
for child in idx_children:
node.children[index] = child
node.cache_valid = False
node.update_cache_info()
try_parse(node)
return nodes
size = len(trees) # initial size
for tree in trees:
copy = tree.copy()
copy.update_cache_info()
_ = hdd(copy)
# Pick newly added stmt
decomposed = list(new_trees.items())[size:]
decomposed_trees = [x[1] for x in decomposed]
return decomposed_trees
def build_naive_parse_trees_2(leaves: List[List[ParseNode]]):
"""
Builds naive parse trees for each leaf in `leaves`, assigning each unique
character to its own nonterminal, and uniting them all under the START
nonterminal.
"""
class_map = defaultdict(allocate_tid)
trees = []
for leaf_lst in leaves:
children = []
for leaf in leaf_lst:
payload = leaf.payload
if len(payload) == 1:
children.append(ParseNode(class_map[payload], False, [leaf]))
else:
grandchildren = [ParseNode(class_map[c], False, [ParseNode(c, True, [])])for c in payload]
children.append(ParseNode(class_map[payload], False, grandchildren))
trees.append(ParseNode(START, False, children))
# trees = [ParseNode(START, False, [ParseNode(get_class[leaf.payload], False, [leaf]) for leaf in leaf_lst])
# for leaf_lst in leaves]
return trees
def apply(grouping: Bubble, trees: List[ParseNode]):
"""
`grouping` is a Bubble, i.e. a representation of a contiguous
sequence of nonterminals that appears someplace in `trees`.
`trees` is a list of parse trees
Returns a new list of trees consisting of bubbling up the grouping
in `grouping` for each tree in `trees`
"""
def matches(group_lst, layer):
"""
GROUP_LST is a contiguous subarray of ParseNodes that are grouped together.
This method requires that len(GRP_LST) > 0.
LAYER another a list of ParseNodes.
Returns the index at which GROUP_LST appears in LAYER, and returns -1 if
the GROUP_LST does not appear in the LAYER. Does not mutate LAYER.
"""
ng, nl = len(group_lst), len(layer)
for i in range(nl):
layer_ind = i # Index into layer
group_ind = 0 # Index into group
while group_ind < ng and layer_ind < nl and layer[layer_ind].payload == group_lst[group_ind].payload:
layer_ind += 1
group_ind += 1
if group_ind == ng: return i
return -1
def apply_single(tree: ParseNode):
"""
TREE is a parse tree.
Applies the GROUPING data structure to a single tree. Applies that
GROUPING to LAYER as many times as possible. Does not mutate TREE.
Returns the new layer. If no updates can be made, do nothing.
"""
group_lst, id = grouping.bubbled_elems, grouping.new_nt
new_tree, ng = tree.copy(), len(group_lst)
# Do replacments in all the children first
for index in range(len(new_tree.children)):
# (self, payload, is_terminal, children)
old_node = new_tree.children[index]
new_tree.children[index] = apply_single(old_node)
# Prevent single nonterminal from bubbling up
ind = matches(group_lst, new_tree.children) if ng < len(new_tree.children) else -1
while ind != -1:
# Prevent bubbling up the same nonterminal
if not new_tree.payload == id:
# if ng == len(new_tree.children):
# pass
parent = ParseNode(id, False, new_tree.children[ind: ind + ng])
new_tree.children[ind: ind + ng] = [parent]
if ng>= len(new_tree.children):
break
ind = matches(group_lst, new_tree.children)
else:
ind = -1
new_tree.update_cache_info()
return new_tree
return [apply_single(tree) for tree in trees]
"""
Given a list of tokens, return the bubble that corresponds to the tokens
"""
def to_bubble(best_trees: List[ParseNode], tokens: List[str]):
"""
Use BFS top-down to find the bubble
"""
node_list = [tree for tree in best_trees]
bubble_one = None
while len(node_list) > 0:
node = node_list.pop(0)
n = len(node.children)
m = len(tokens)
"""
n = number of nodes in the target layer, m = number of tokens in the bubble
"""
if m <= 1:
return None
# Skip if the number of children is less than the bubble size, instead add all children to the queue
if n <= m:
node_list.extend([i for i in node.children if not i.is_terminal])
continue
"""
ignore spaces for bubble search in the trees
"""
no_space = [token for token in tokens if token != ' ']
m = len(no_space)
for i in range(n-m+1):
for j in range(i+m, n+1):
sub_str = [node.children[k].payload for k in range(i, j)]
sub_str = [token for token in sub_str if token != ' ']
if sub_str == no_space:
# skip spaces before i and after j
siblings = [node.children[k] for k in range(i, j)]
start = 0
end = len(siblings)
while siblings[start].payload == ' ':
start += 1
while siblings[end-1].payload == ' ':
end -= 1
# discard single item bubble
if end - start > 1:
bubble_one = Bubble(allocate_tid(), siblings[start:end])
return bubble_one
if len(sub_str) > m:
break
node_list.extend([i for i in node.children if not i.is_terminal])
return bubble_one
def remove_dup(bubble_list: List[List[str]]):
"""
Remove duplicates in a list
"""
seen = set()
bubble_dedup = []
for bubble in bubble_list:
b_tuple = tuple(bubble)
if b_tuple not in seen:
bubble_dedup.append(bubble)
seen.add(b_tuple)
return bubble_dedup
"""
Get the longest flat layer in the tree
"""
def get_tree_layers(best_trees, for_llm = True):
layers = []
def single_layer(tree):
if tree.is_terminal:
return
new_layer = [child.payload for child in tree.children if child.payload != ' ']
# remove brackets as these represent a complete level
if new_layer and new_layer[0] in ['(', '[', '{'] and new_layer[-1] in [')', ']', '}']:
layers.append(new_layer[1:-1])
else:
layers.append(new_layer)
for child in tree.children:
if not child.is_terminal:
single_layer(child)
for tree in best_trees:
single_layer(tree)
all_layers = sorted(layers, key=lambda x: len(x), reverse=True)
# delete duplicates
all_layers_dedup = remove_dup(all_layers)
long = [x for x in all_layers_dedup if len(x) >= 3]
short = [x for x in all_layers_dedup if len(x) < 10 and len(x) > 1]
if not for_llm:
return reversed(short)
# return layers that sums up 500 characters
top_layers = []
sum_len = 0
for layer in long:
top_layers.append(layer)
sum_len += len(layer)
if sum_len > 500 and len(top_layers) >10:
break
return top_layers
def build_trees(oracle, leaves):
"""
ORACLE is an oracle for the grammar we seek to find. We ask the oracle
yes or no replacement questions in this method.
LEAVES should be a list of lists (one list for each input example), where
each sublist contains the tokens that built that example, as ParseNodes.
Iteratively builds parse trees by greedily choosing a substring to "bubble"
up that passes replacement tests at each point in the algorithm, until no
further bubble ups can be made.
Returns a list of finished parse trees (as ParseNode) one for each list of
leaf nodes in `leaves`.
Algorithm:
1. Over all top-level substrings:
a. bubble up the substring
b. perform replacement if possible
2. If a replacement was possible, repeat (1)
"""
global ORIGINAL_COALESCE_TIME
global BUILD_TIME
global TIME_GROUPING
def score(trees: List[ParseNode], new_bubble: Optional[Bubble]) \
-> Tuple[int, List[ParseNode]]:
"""
Tries to merge nonterminals in `trees`, and returns (1, the new trees with labels)
merged if a merge occurs. Score is 0 otherwise.
If `new_bubble` is not None, only checks mergings that involve
the new bubble (against each existing nonterminal if it's a 1-bubble
and between the two introduced nonterminals if it's a 2-bubble)
"""
# Convert LAYERS into a grammar
grammar = build_grammar(trees)
grammar, new_trees, coalesce_caused, coalesced_into = coalesce(oracle, trees, grammar, new_bubble)
new_size = grammar.size()
if coalesce_caused:
return 1, new_trees, coalesced_into
else:
return 0, trees, {}
def get_updated_bubble(bubble, coalesced_into):
"""
After a successful node merge, update the bubble elements to reflect the new nonterminal
"""
if isinstance(bubble, Bubble):
for elem in bubble.bubbled_elems:
if elem.payload in coalesced_into:
# assuming multi-hop coalescing is already handled
new_nt = coalesced_into[elem.payload]
elem.payload = new_nt
bubble.new_nt = allocate_tid()
bubble.bubble_str = ''.join([e.payload for e in bubble.bubbled_elems])
else:
for bubble_single in bubble:
for elem in bubble_single.bubbled_elems:
if elem.payload in coalesced_into:
new_nt = coalesced_into[elem.payload]
elem.payload = new_nt
bubble_single.new_nt = allocate_tid()
bubble_single.bubble_str = ''.join([e.payload for e in bubble_single.bubbled_elems])
return bubble
def update_all_bubbles(all_bubbles, coalesced_into, best_trees):
"""
After a bubble_loop call, update all bubbles to reflect the new nonterminals
"""
for k in list(all_bubbles.keys()):
bubble = all_bubbles[k]
updated_bubble = get_updated_bubble(bubble, coalesced_into)
all_bubbles.pop(k)
bubble_tokens = [e.payload for e in updated_bubble.bubbled_elems]
valid_bubble = to_bubble(best_trees, bubble_tokens)
if valid_bubble:
all_bubbles[valid_bubble.bubble_str] = valid_bubble
def bubble_loop(best_trees, count, bubble_list, no_llm = False, grp_size = -1): # delete grp_size later
updated, nlg = False, len(bubble_list)
loop_coalesce_into = {}
nt_set = set()
print(f"Bubbles in list: {nlg}")
for i, grouping in enumerate(bubble_list):
reapply = True
last = -1
valid_bubble = False
while reapply:
if isinstance(grouping, Bubble):
new_trees = apply(grouping, best_trees)
new_score, new_trees, coalesced_into = score(new_trees, grouping)
grouping_str = f"Successful grouping (single): {grouping.bubbled_elems}\n (aka {[e.derived_string() for e in grouping.bubbled_elems]}"
# grouping_str += f"\n [score of {the_score}]"
else:
bubble_one = grouping[0]
bubble_two = grouping[1]
new_trees = apply(bubble_one, best_trees)
new_trees = apply(bubble_two, new_trees)
new_score, new_trees, coalesced_into = score(new_trees, grouping)
grouping_str = f"Successful grouping (double): {bubble_one.bubbled_elems}, {bubble_two.bubbled_elems}"
grouping_str += f"\n (aka {[e.derived_string() for e in bubble_one.bubbled_elems]}, {[e.derived_string() for e in bubble_two.bubbled_elems]}))"
# grouping_str += f"\n [score of {the_score}]"
### Score
if new_score > 0:
best_trees = new_trees
# pt = PrettyPrintTree(lambda x: x.children, lambda x: x.payload)
# for tree in best_trees:
# print(tree.to_newick())
# pt(tree)
if i == last:
global REAPPLY
REAPPLY += 1
print(f"Reapply: {REAPPLY}")
last = i
print()
print(('[Group len %d] Bubbling iteration %d (%d/%d)...' % (grp_size, count, i + 1, nlg)).ljust(50))
print(grouping_str)
print("coalesced into: ", coalesced_into)
# first, flatten multi-hop coalesced_into
for k in list(coalesced_into.keys()):
v = coalesced_into[k]
while v in coalesced_into and not v == coalesced_into[v]:
v = coalesced_into[v]
coalesced_into[k] = v
grouping = get_updated_bubble(grouping, coalesced_into)
updated, valid_bubble = True, True
# need to maintain another coalesced_into for the entire bubble loop?
loop_coalesce_into.update(coalesced_into)
else:
reapply = False
if valid_bubble:
if no_llm:
break
# flatten loop_coalesce_into
for k in list(loop_coalesce_into.keys()):
v = loop_coalesce_into[k]
while v in loop_coalesce_into and not v == loop_coalesce_into[v]:
v = loop_coalesce_into[v]
loop_coalesce_into[k] = v
return best_trees, updated, loop_coalesce_into
def get_llm_bubble(best_trees, one_bubble = True, retry = 0):
"""
Get list of bubbles from LLM
"""
layer = get_tree_layers(best_trees)
# don't call 2-bubbles if longest layer is less than 7, it might allow redundant merges
if not one_bubble and (not layer or len(layer[0]) < 7):
return []
prompt = '\n'.join([str(i) for i in layer])
bubble_list = bubble_api(prompt) if one_bubble else bubble_pair_api(prompt) # llm call here
global LLM_CALLS
LLM_CALLS += 1
try:
bubble_list = json.loads(bubble_list)['siblings']
except:
print("LLM failed to generate bubbles")
return get_llm_bubble(best_trees, one_bubble, retry + 1) if retry < 3 else []
return bubble_list[:100]
best_trees = build_naive_parse_trees(leaves, [], oracle)
print(f"Branching factor: {branching_factor(best_trees)}")
grammar = build_grammar(best_trees)
# pt = PrettyPrintTree(lambda x: x.children, lambda x: x.payload)
# for tree in best_trees:
# print(tree.derived_string())
# pt(tree)
s = time.time()
print("Beginning coalescing...".ljust(50))
grammar, best_trees, _, _ = coalesce(oracle, best_trees, grammar)
ORIGINAL_COALESCE_TIME += time.time() - s
s = time.time()
# Main algorithm loop. Iteratively increase the length of groups allowed from MIN_GROUP_LEN to MAX_GROUP_LEN
# break the group_size loop if no valid merge after increasing group size by threshold
# for group_size in range(MIN_GROUP_LEN, MAX_GROUP_LEN):
threshold = 5 if USE_LLM else 0
count = 0
all_bubbles = {} # need to update by coalesced_into
while threshold > 0:
group_start = time.time()
updated = True
while updated:
print(f"PRE-BUBBLES")
pre_bubble_layers = get_tree_layers(best_trees, False)
pre_bubbles = [to_bubble(best_trees, b) for b in pre_bubble_layers]
pre_bubbles = [b for b in pre_bubbles if b]
best_trees, updated, coalesced_into = bubble_loop(best_trees, count, pre_bubbles)
if updated:
update_all_bubbles(all_bubbles, coalesced_into, best_trees)
updated = True
while updated:
print(f"1-BUBBLES")
count += 1
bubble_list = get_llm_bubble(best_trees)
# remove duplicates
bubble_dedup = remove_dup(bubble_list)
# sort by length, shorter bubbles should be applied first
# bubble_dedup = sorted(bubble_dedup, key=lambda x: len(x), reverse=True)
# get bubbles from string
for b in bubble_dedup:
cand = ''.join(b)
# if not is_balanced(cand):
# continue
# pop if already in the list
if cand in all_bubbles:
all_bubbles.pop(cand)
grp = to_bubble(best_trees, b)
if grp:
all_bubbles[cand] = grp
# one_bubbles = sorted(all_bubbles.values(), key=lambda x: len(x.bubbled_elems))
# keep last added 50 bubbles
all_bubbles = dict(list(all_bubbles.items())[-100:])
# one_bubbles = list(reversed(all_bubbles.values()))
# sort by length, shorter bubbles should be applied first
one_bubbles = sorted(all_bubbles.values(), key=lambda x: len(x.bubbled_elems))
TIME_GROUPING += time.time() - group_start
best_trees, updated, coalesced_into = bubble_loop(best_trees, count, one_bubbles)
if updated:
threshold = 5
# update all_bubbles according to coalesced_into
update_all_bubbles(all_bubbles, coalesced_into, best_trees)
else:
threshold -= 1
updated = True
print("2-BUBBLES")
while updated:
two_bubbles = []
count += 1
bubble_list = get_llm_bubble(best_trees, False)
# break if not valid 2-bubbles
try:
for first, second in bubble_list:
cand1 = ''.join(first)
cand2 = ''.join(second)
if cand1 == cand2:
continue
if not is_balanced(cand1) or not is_balanced(cand2):
continue
grp1 = all_bubbles.get(cand1, to_bubble(best_trees, first))
if grp1:
all_bubbles[cand1] = grp1
grp2 = all_bubbles.get(cand2, to_bubble(best_trees, second))
if grp2:
all_bubbles[cand2] = grp2
if cand1 == cand2:
continue
if grp1 and grp2:
two_bubbles.append((grp1, grp2))
except:
break
best_trees, updated, coalesced_into = bubble_loop(best_trees, count, two_bubbles)
if updated:
threshold = 5
update_all_bubbles(all_bubbles, coalesced_into, best_trees)
llm_trees = [tree.copy() for tree in best_trees]
if TREEVADA:
# global HALF_MERGE
# HALF_MERGE = False
updated = True
threshold = 5
grp_size = MIN_GROUP_LEN
while updated or threshold:
bubble_list = group(best_trees, grp_size)
best_trees, updated, _ = bubble_loop(best_trees, count, bubble_list, True, grp_size)
count+=1
if not updated:
grp_size += 1
threshold -= 1
else:
threshold = 5
BUILD_TIME += time.time() - s
return llm_trees, best_trees
def coalesce_partial(oracle, trees: List[ParseNode], grammar: Grammar,
coalesce_target: Bubble = None):
"""
ASSUMES: `grammar` is the grammar induced by `trees`
Performs partial coalesces on the grammar. That is, for pairs of nonterminals (nt1, nt2), checks whether:
if nt1 can be replaced by nt2 everywhere, are there any occurrences of nt2 where nt1 can replace nt2.
An "occurrence" of nt2 is a location in a rule in grammar. So even if there are two separate trees
where nt2 occurs in the subtree:
nt0
/ \
nt3 nt2
nt2 beside nt3 as a child of nt0 is considered only "one occurrence"
For efficiency:
While nt1 can range over all nonterminals in the grammar, nt2 ranges only over "character" nonterminals,
that is those whose rules only expand to a single character. Character classes are allowc
ASSUMES: coalesce(oracle, trees, grammar, coalesce_target) has been called previously. In this case, we will never
be in the situation where (nt1, nt2) can partially coalesce and (nt2, nt1) can partially coalesce.
"""
def partially_coalescable(replaceable_everywhere: str, replaceable_in_some_rules: str, trees: ParseTreeList) -> Dict[
Tuple[str, Tuple[str]], List[int]]:
"""
`replaceable_everywhere` and `replaceable_in_some_rules` are both nonterminals
If `replaceable_in_some_rules` can replace `replaceable_everywhere` at every
occurrence of `replaceable_everywhere`, returns the rules (expansions) in which
`replaceable_in_some_rules` can be replaced by `replaceable_everywhere`
"""
global TIME_GENERATING_EXAMPLES
language_expanded = not MUST_EXPAND_IN_PARTIAL
# Get all the expansions where `replaceable_in_some_rules` appears
partial_replacement_locs: List[Tuple[Tuple[str, List[str]], int]] = []
for rule_start, rule in grammar.rules.items():
for body in rule.bodies:
replacement_indices = [idx for idx, val in enumerate(body) if val == replaceable_in_some_rules]
for idx in replacement_indices:
partial_replacement_locs.append(((rule_start, body), idx))
s = time.time()
# Get the set of strings derivable from `replaceable_everywhere`
everywhere_derivable_strings = lvl_n_derivable(trees, replaceable_everywhere, 0 )
# Get the set of strings derivable from `replaceable_in_some_rules`
in_some_derivable_strings = lvl_n_derivable(trees, replaceable_in_some_rules, 0)
TIME_GENERATING_EXAMPLES += time.time() - s
# Check whether `replaceable_everywhere` is replaceable by `replaceable_in_some_rules` everywhere.
everywhere_by_some_candidates = []
for tree in trees:
everywhere_by_some_candidates.extend(
get_strings_with_replacement(tree, replaceable_everywhere, in_some_derivable_strings))
if len(everywhere_by_some_candidates) > MAX_SAMPLES_PER_COALESCE:
everywhere_by_some_candidates = random.sample(everywhere_by_some_candidates, MAX_SAMPLES_PER_COALESCE)
else:
random.shuffle(everywhere_by_some_candidates)
if MUST_EXPAND_IN_PARTIAL and coalesce_target is not None and trees.represented_by_derived_grammar(everywhere_by_some_candidates):
language_expanded = False
else:
language_expanded = MUST_EXPAND_IN_PARTIAL
try:
for replaced_str in everywhere_by_some_candidates:
oracle.parse(replaced_str)
except Exception as e:
return []
if (len(everywhere_derivable_strings) == 0): return {}
# Now check whether there are any rules where `replaeable_in_some_rules` is replaceable by
# `replaceable_everywhere`
replacing_positions: Dict[Tuple[str, Tuple[str]], List[int]] = defaultdict(list)
for replacement_loc in partial_replacement_locs:
rule, posn = replacement_loc
candidate_strs = []
for tree in trees:
candidate_strs.extend(
get_strings_with_replacement_in_rule(tree, rule, posn, everywhere_derivable_strings))
if len(candidate_strs) > MAX_SAMPLES_PER_COALESCE:
candidate_strs = random.sample(candidate_strs, MAX_SAMPLES_PER_COALESCE)
else:
random.shuffle(candidate_strs)
if MUST_EXPAND_IN_PARTIAL and coalesce_target is not None and trees.represented_by_derived_grammar(candidate_strs):
replacing_positions[(rule[0], tuple(rule[1]))].append(posn)
continue
try:
candidate_index = 0
for candidate in candidate_strs:
candidate_index += 1
oracle.parse(candidate)
replacing_positions[(rule[0], tuple(rule[1]))].append(posn)
language_expanded = True
except ParseException as e:
continue
if MUST_EXPAND_IN_PARTIAL and coalesce_target is not None and not language_expanded:
return []
return replacing_positions
def get_updated_grammar(old_grammar, partial_replacement_locs: Dict[Tuple[str, Tuple[str]], List[int]],
full_replacement_nt: str, nt_to_partially_replace: str, new_nt: str):
"""
Creates a copy of `old_grammar` so that the locations in `partial_replacement_locs` are replaced by `new_nt`, and all
occurrences of `full_relacement_nt` are replaced by `new_nt`
"""
# Keep track of whether nt to partially replace still occurs on some rhss
partially_replace_on_rhs = False
grammar = old_grammar.copy()
alt_rule = Rule(new_nt)
for (rule_start, body), posns in partial_replacement_locs.items():
rule_to_update = grammar.rules[rule_start]
body_posn = rule_to_update.bodies.index(list(body))
for posn in posns:
rule_to_update.bodies[body_posn][posn] = new_nt
for rule in grammar.rules.values():
for body in rule.bodies:
for idx in range(len(body)):
if body[idx] == full_replacement_nt:
body[idx] = new_nt
elif body[idx] == nt_to_partially_replace:
partially_replace_on_rhs = True
# Now fixup rules to remove any duplicate productions that may have been added during replacement.
for rule in grammar.rules.values():
unique_bodies = []
for body in rule.bodies:
if body not in unique_bodies:
unique_bodies.append(body)
rule.bodies = unique_bodies
alt_rule_bodies = grammar.rules[full_replacement_nt].bodies
alt_rule_bodies.extend(grammar.rules[nt_to_partially_replace].bodies)
grammar.rules.pop(full_replacement_nt)
alt_rule.bodies = alt_rule_bodies
grammar.add_rule(alt_rule)
if not partially_replace_on_rhs:
grammar.rules.pop(nt_to_partially_replace)
return grammar