1: import numpy as np
2: import pickle
3: from soar.llm_utils import merge_results, to_formated_list
4: from soar.llm_utils import get_number_of_solved_tasks_bis, get_info, give_n_majority_vote_v2, weighted_sample
5: from soar.post_process.filtering import rm_duplicate_resps
6: from tqdm import tqdm
7: import argparse
8: # should move this in main
9: parser = argparse.ArgumentParser()
10: parser.add_argument("--path_model", type=str, default="/home/flowers/work/hf/Qwen2.5-Coder-7B-Instruct-AWQ")
11: parser.add_argument("--path_embed_model", type=str, default="/home/flowers/work/hf/CodeRankEmbed")
12: parser.add_argument("--split", type=str, default="val")
13: parser.add_argument("--N_sample_task", type=int, default=50)
14: parser.add_argument("--path_folder_solution", type=str, default="/home/flowers/work/arc/aces_arc/save_results/full_pipeline_scratch/yolo/Qwen2.5-Coder-32B-Instruct/gen-1/refinement/")
15: parser.add_argument("--sampling_her",type=str,default="greedy_div",help="sampling strategy for the responses, choice among greedy_div, greedy, uniform, correct, greedy_div_mv")
16: parser.add_argument("--use_prev_gen",action=argparse.BooleanOptionalAction ,default=False,help="merge solution of this generation with previous generation")
17: parser.add_argument("--use_repair_data",action=argparse.BooleanOptionalAction ,default=True,help="use_repair_data")
18: parser.add_argument("--dedup",action=argparse.BooleanOptionalAction ,default=False,help="deduplication of the responses")
19: 
20: args = parser.parse_args()
21: 
22: if args.dedup:
23:     from sentence_transformers import SentenceTransformer
24:     model = SentenceTransformer(args.path_embed_model, trust_remote_code=True)
25: 
26: 
27: if not args.sampling_her in ["greedy_div","greedy","uniform","correct","greedy_div_mv"]:
28:     raise ValueError("sampling_her must be in ['greedy_div','greedy','uniform','correct','greedy_div_mv']")
29: path_model=args.path_model
30: 
31: 
32: split=args.split
33: N_sample_task = args.N_sample_task
34: path_save= args.path_folder_solution + f"data4train-{args.split}-n{args.N_sample_task}-{args.sampling_her}.pkl"
35: 
36: def get_deduplicate_output_one_task(task):
37:     """dedup based on output grid"""
38:     dic_unique_output = {}
39:     for result in task:
40: 
41:         list_out = (
42:             result["predicted_train_output"] +
43:             result["predicted_test_output"]
44:             )
45:         list_out_str = str(list_out)
46:         if list_out_str in dic_unique_output:
47:             dic_unique_output[list_out_str] = result
48:     return list(dic_unique_output.values())
49: 
50: def get_sample_task_uniform(data, N_sample_task):
51:     list_k = list(data.keys())
52:     dic_sample = {}
53:     for k in list_k:
54:         # sample N_sample_task responses uniformly
55:         N_sample = min(N_sample_task,len(data[k]))
56:         dic_sample[k] = np.random.choice(data[k], N_sample, replace=False).tolist()
57:     return dic_sample
58: 
59: def get_sample_task_greedy(data, N_sample_task):
60:     list_k = list(data.keys())
61:     dic_sample = {}
62:     for k in list_k:
63:         # sample N_sample_task responses with the highest score (correct_train_input)
64:         dic_sample[k]  = sorted(data[k], key=lambda x: np.mean(x["correct_train_input"]), reverse=True)[:N_sample_task]
65:     return dic_sample
66: 
67: 
68: def get_sample_task_correct(data, N_sample_task):
69:     list_k = list(data.keys())
70:     dic_sample = {}
71:     for k in list_k:
72:         # sample N_sample_task responses with the highest score (correct_train_input)
73:         v_filtered = [v for v in data[k] if all(v["correct_train_input"] + v["correct_test_input"])]
74:         if len(v_filtered)!=0:
75:             N_sample = min(N_sample_task,len(v_filtered))
76:             dic_sample[k] = np.random.choice(v_filtered, N_sample, replace=False).tolist()
77:     return dic_sample
78: 
79: def get_sample_task_greedy_div(data, N_sample_task,split="train",majority_vote=False):
80:     """sample N_sample_task responses for each task, half of them are sampled greedily, the other half are sampled uniformly among task """
81: 
82:     N_sample_greedy = N_sample_task // 2 #// 2
83:     N_sample_uniform = N_sample_task - N_sample_greedy
84:     list_k = list(data.keys())
85:     min_number_sample = 100000
86:     dic_sample = {}
87:     for k in tqdm(list_k):
88:         # shuffle data
89:         data[k] = np.random.permutation(data[k]).tolist()
90: 
91:         if split=="train":
92:             if args.dedup:
93:                 data[k] = rm_duplicate_resps(model, data[k], threshold = 0.9)
94:             dic_resp_sorted  = sorted(data[k], key=lambda x: (np.mean(x["correct_train_input"]+ (np.array(x["correct_test_input"])*1.1).tolist()),-len(x["code"])), reverse=True)
95:         else:
96:             dic_resp_sorted  = sorted(data[k], key=lambda x:(np.mean(x["correct_train_input"]),-len(x["code"])), reverse=True)
97:         
98: 
99:         if majority_vote:
100:             
101:             for id_resp in range(len(dic_resp_sorted)):
102:                 dic_resp_sorted[id_resp]["id_resp_rm"] = id_resp
103:             _,list_original_resp = give_n_majority_vote_v2(dic_resp_sorted, n_output=min(N_sample_greedy,len(data[k])),return_responses=True)
104:             sampled_responses = weighted_sample(list_original_resp, N_sample_greedy)
105:             dic_sample[k] = sampled_responses
106:             id_to_rm = [dic["id_resp_rm"] for dic in sampled_responses]
107:             dic_other_resp = [dic for dic in dic_resp_sorted if dic["id_resp_rm"] not in id_to_rm]
108:         else:
109:             dic_sample[k] = dic_resp_sorted[:N_sample_greedy]
110:             # take example that were not sampled
111: 
112:             dic_other_resp = dic_resp_sorted[N_sample_greedy:]
113:         # sample N_sample_uniform responses uniformly
114:         list_diverse=[]
115:         
116:         
117:         # dedup given output
118:         dic_other_resp = get_deduplicate_output_one_task(dic_other_resp)
119:         for resp in dic_other_resp:
120:             if not any(resp["correct_train_input"]):
121:                 list_diverse.append(resp)
122:           
123:         if len(list_diverse)<=N_sample_uniform:
124:             # in case we have not enough example wo correct train input 
125:             for resp in dic_other_resp:
126:                 if np.sum(resp["correct_train_input"])==1:
127:                     list_diverse.append(resp)
128:         if len(list_diverse)<=N_sample_uniform:
129:             # in case we have not enough example with 1 correct train input
130:             for resp in dic_other_resp:
131:                 if np.mean(resp["correct_train_input"])<1/2:
132:                     list_diverse.append(resp)
133: 
134:         dic_sample[k] += np.random.choice(list_diverse, min(N_sample_uniform,len(list_diverse)), replace=False).tolist()
135:         min_number_sample = min(min_number_sample,len(dic_sample[k]))
136: 
137:     print("min_number_sample: ",min_number_sample)
138:     return dic_sample
139: 
140: 
141: def rm_long_code(solution_merged, path_model):
142:     from transformers import AutoTokenizer
143:     
144:     tokenizer = AutoTokenizer.from_pretrained(path_model)
145:     n_del = 0
146:     
147:     # Batch process all codes at once
148:     all_codes = []
149:     indices = []
150:     for k, v in solution_merged.items():
151:         for i, item in enumerate(v):
152:             all_codes.append(item["code"])
153:             indices.append((k, i))
154:     
155:     # Tokenize all codes in one batch
156:     # Process in mini-batches
157:     batch_size = 32768*4  # Adjust based on your memory constraints
158:     lengths = []
159:     
160:     for i in tqdm(range(0, len(all_codes), batch_size), desc="Tokenizing in batches"):
161:         batch_codes = all_codes[i:i+batch_size]
162:         batch_tokenized = tokenizer(batch_codes, padding=False)["input_ids"]
163:         batch_lengths = [len(x) for x in batch_tokenized]
164:         lengths.extend(batch_lengths)
165: 
166:     # Process deletions of long codes
167:     to_delete = {}
168:     for idx, (k, i) in enumerate(indices):
169:         if lengths[idx] > 4096 and not any(solution_merged[k][i]["correct_train_input"]):
170:             if k not in to_delete:
171:                 to_delete[k] = []
172:             to_delete[k].append(i)
173:             n_del += 1
174:     
175:     # Delete items (in reverse order for each key)
176:     for k in to_delete:
177:         for i in sorted(to_delete[k], reverse=True):
178:             del solution_merged[k][i]
179:     
180:     return solution_merged
181: 
182: 
183: def count_resp(dic):
184:     count = 0
185:     for k in dic.keys():
186:         count+=len(dic[k])
187:     return count
188: 
189: 
190: def get_previous_paths(path):
191:     """
192:     .../aces_arc/save_results/full_pipeline_scratch/Qwen2.5-Coder-32B-Instruct/gen-1/solution/
193:     -> [.../aces_arc/save_results/full_pipeline_scratch/Qwen2.5-Coder-32B-Instruct/gen-0/solution/, .../aces_arc/save_results/full_pipeline_scratch/Qwen2.5-Coder-32B-Instruct/gen-1/solution/]
194:     """
195: 
196:     # Find the pattern 'gen-X' in the path
197:     
198:     import re
199:     match = re.search(r'gen-(\d+)/', path)
200:     if not match:
201:         print("no match for gen-")
202:         return [path]
203:     if not args.use_prev_gen:
204:         print("use_prev_gen is False, return only current path")
205:         return [path]
206: 
207:     current_gen = int(match.group(1))
208:     base_path = path[:match.start()]
209:     suffix = path[match.end():]
210:     
211:     # Generate all paths from gen-0 to current gen
212:     paths = []
213:     for i in range(current_gen + 1):
214: 
215:         new_path = f"{base_path}gen-{i}/{suffix}"
216:         paths.append(new_path)
217:     return paths[::-1]
218: 
219: # load files
220: 
221: solution = []
222: paths_all_gen = get_previous_paths(args.path_folder_solution)
223: 
224: print("==="*10)
225: print(f"found {len(paths_all_gen)} generations:")
226: print("==="*10)
227: 
228: for path in paths_all_gen:
229:     if args.use_repair_data:
230:         path_solution = f"{path}{split}_sol_repair.pkl"
231:     else:
232:         path_solution = f"{path}{split}_sol.pkl"
233:     try:
234:         with open(path_solution, 'rb') as f:
235:             print(f"loading {path_solution}")
236:             data = to_formated_list(pickle.load(f))
237:             solution += data
238:     except:
239:         print(f"error: can't load {path_solution}")
240: 
241: solution_merged = merge_results(solution)
242: print("result before  rm long code:")
243: get_info(get_number_of_solved_tasks_bis(solution_merged,mv=True))
244: solution_merged = rm_long_code(solution_merged,path_model)
245: print("result after rm long code:")
246: 
247: get_info(get_number_of_solved_tasks_bis(solution_merged,mv=True))
248: 
249: if args.sampling_her == "greedy_div":
250:     data_sampled_her = get_sample_task_greedy_div(solution_merged, N_sample_task,split=split)
251: elif args.sampling_her == "greedy":
252:     data_sampled_her = get_sample_task_greedy(solution_merged, N_sample_task)
253: elif args.sampling_her == "uniform":
254:     data_sampled_her = get_sample_task_uniform(solution_merged, N_sample_task)
255: elif args.sampling_her == "correct":
256:     data_sampled_her = get_sample_task_correct(solution_merged, N_sample_task)
257: elif args.sampling_her == "greedy_div_mv":
258:     data_sampled_her = get_sample_task_greedy_div(solution_merged, N_sample_task,split=split,majority_vote=True)
259: print("result after sampling:")
260: 
261: get_info(get_number_of_solved_tasks_bis(data_sampled_her,mv=True))
262: print("save data sampled at: ", path_save)
263: with open(path_save, "wb") as f:
264:     pickle.dump(to_formated_list(data_sampled_her), f)
265: 