1: """
2: Given a set of (particle, score), generate a dataset for a particular format.
3: """
4: 
5: import hydra
6: import json
7: import logging
8: import numpy as np
9: import pandas as pd
10: import pprint
11: import random
12: import torch
13: 
14: from omegaconf import DictConfig, OmegaConf
15: from pynndescent import PyNNDescentTransformer
16: from scipy.spatial import distance
17: from synthetic_dataset_lib import ranked_fft
18: from tqdm import tqdm
19: from typing import Any, Dict, List, Optional, Tuple
20: 
21: logging.basicConfig(level="INFO", force=True)
22: 
23: 
24: def find_minimal_edit_pairs(cfg: DictConfig, df: pd.DataFrame) -> List[Dict[str, Any]]:
25:     """
26:     Given a dataset of particles and scores, find minimal pairs that have different scores.
27:     """
28:     logging.info(f"Length of original df: {len(df)}")
29:     df = df.drop_duplicates(subset=["particle"])
30:     logging.info(f"Length of df after removing duplicates: {len(df)}")
31:     X = np.array([p for p in df["particle"]])
32:     scores = np.array([s for s in df["score"]])
33:     if cfg.score_lower_threshold is not None:
34:         X, scores = filter_by_score(X, scores, cfg.score_lower_threshold)
35:     pynn_transformer = PyNNDescentTransformer(
36:         n_neighbors=cfg.n_neighbors, metric=cfg.distance_metric
37:     ).fit(X)
38:     transformed = pynn_transformer.transform(X)
39: 
40:     # # take a smaller sample if necessary
41:     # if cfg.n is not None:
42:     #     random.seed(cfg.seed)
43:     #     transformed = transformed[
44:     #         random.sample(
45:     #             range(transformed.shape[0]), k=min(2 * cfg.n, transformed.shape[0])
46:     #         ),
47:     #         :,
48:     #     ]
49: 
50:     # loop through rows instead of doing matrix computation to save memory
51:     idx_pairs = []
52:     for i in tqdm(range(transformed.shape[0])):
53:         # find elements that are nearest neighbors but have different score
54:         # from the original particle
55:         curr_score = scores[i]
56:         nearest_neighbor_idxs = set(transformed.getrow(i).nonzero()[1])
57:         diff_score_idxs = set(np.nonzero(scores != curr_score)[0])
58:         # now find the intersection
59:         eligible_elem_idxs = nearest_neighbor_idxs & diff_score_idxs
60:         if len(eligible_elem_idxs) == 0:
61:             logging.warning(f"No eligible neighbors found.")
62:             continue
63:         eligible_elem_idxs = list(eligible_elem_idxs)
64:         closest_eligible_nbor_idx = eligible_elem_idxs[
65:             np.argmin(
66:                 np.array(
67:                     transformed.getrow(i)[
68:                         [0 for _ in range(len(eligible_elem_idxs))], eligible_elem_idxs
69:                     ]
70:                 )[0]
71:             )
72:         ]
73:         idx_pairs.append((i, closest_eligible_nbor_idx))
74: 
75:     if cfg.n is not None:
76:         random.seed(cfg.seed)
77:         idx_pairs = random.sample(idx_pairs, k=min(cfg.n, len(idx_pairs)))
78:     outputs = get_outputs_from_idx_pairs(idx_pairs, X, scores)
79:     if cfg.max_proportion_infeasible is not None:
80:         outputs = filter_infeasible_examples(cfg, outputs)
81:     return outputs
82: 
83: 
84: def filter_by_score(
85:     library: torch.Tensor, scores: torch.Tensor, score_threshold: float
86: ) -> Tuple[torch.Tensor, torch.Tensor]:
87:     idxs = torch.where(scores > score_threshold)
88:     return library[idxs], scores[idxs]
89: 
90: 
91: def filter_by_score_df(df: pd.DataFrame, score_threshold: float) -> pd.DataFrame:
92:     return df[df["score"] > score_threshold]
93: 
94: 
95: def abs_subtract_replace_infs(x: float, y: float) -> float:
96:     """Replace the infinities with a score of 0.0."""
97:     if np.isinf(x) or np.isnan(x):
98:         x = 0.0
99:     if np.isinf(y) or np.isnan(y):
100:         y = 0.0
101:     return np.abs(x - y)
102: 
103: 
104: def filter_by_likelihood_range(
105:     df: pd.DataFrame, likelihood_quantile_range: Tuple[float, float]
106: ) -> pd.DataFrame:
107:     orig_size = len(df)
108:     if "likelihood" not in df.columns and "loglikelihood" not in df.columns:
109:         logging.error(
110:             f"Neither 'likelihood' nor 'loglikelihood' are in DF columns. Not filtering by likelihood range."
111:         )
112:         return df
113:     elif "likelihood" not in df.columns:
114:         df["likelihood"] = df["loglikelihood"].map(lambda x: np.exp(x))
115:     lower_ll_bound = df["likelihood"].quantile(likelihood_quantile_range[0])
116:     upper_ll_bound = df["likelihood"].quantile(likelihood_quantile_range[1])
117:     df = df[(df["likelihood"] >= lower_ll_bound) & (df["likelihood"] <= upper_ll_bound)]
118:     logging.info(
119:         f"Filtered dataset from {orig_size} down to {len(df)} examples after filtering by likelihood range."
120:     )
121:     return df
122: 
123: 
124: def filter_by_likelihood_lower_threshold(
125:     df: pd.DataFrame, likelihood_quantile_threshold: float
126: ) -> pd.DataFrame:
127:     orig_size = len(df)
128:     if "likelihood" not in df.columns and "loglikelihood" not in df.columns:
129:         logging.error(
130:             f"Neither 'likelihood' nor 'loglikelihood' are in DF columns. Not filtering by likelihood range."
131:         )
132:         return df
133:     elif "likelihood" not in df.columns:
134:         df["likelihood"] = df["loglikelihood"].map(lambda x: np.exp(x))
135:     likelihood_lower_threshold = df["likelihood"].quantile(
136:         likelihood_quantile_threshold
137:     )
138:     df = df[(df["likelihood"] >= likelihood_lower_threshold)]
139:     logging.info(
140:         f"Filtered dataset from {orig_size} down to {len(df)} examples after filtering by lower likelihood threshold."
141:     )
142:     return df
143: 
144: 
145: def find_dense_pairs(
146:     cfg: DictConfig, df: pd.DataFrame, allow_same_score_pair: bool = False
147: ) -> List[Dict[str, Any]]:
148:     """Adapted from PropEn -- find all pairs within a specific edit distance of each other"""
149:     df = df.drop_duplicates(subset=["particle"])
150:     if cfg.n is not None:
151:         if cfg.filter_by_likelihood and len(df) > cfg.n:
152:             df = filter_by_likelihood_lower_threshold(
153:                 df, cfg.likelihood_quantile_threshold
154:             )
155:         elif cfg.filter_by_likelihood_range and len(df) > cfg.n:
156:             df = filter_by_likelihood_range(df, tuple(cfg.likelihood_quantile_range))
157:         df = df.sample(n=min(len(df), cfg.n), random_state=cfg.seed)
158:     if cfg.score_lower_threshold is not None:
159:         df = filter_by_score_df(df, cfg.score_lower_threshold)
160:     library = torch.stack([torch.LongTensor(p) for p in df["particle"]])
161:     ranking_scores = torch.FloatTensor([x for x in df["score"]])
162:     filtered = library
163:     filtered_scores = ranking_scores
164:     filtered = filtered.numpy()
165:     pynn_transformer = PyNNDescentTransformer(
166:         n_neighbors=cfg.n_neighbors, metric=cfg.distance_metric
167:     ).fit(filtered)
168:     transformed = pynn_transformer.transform(filtered)
169:     # loop through rows instead of doing matrix computation to save memory
170:     idx_pairs = set([])
171:     for i in tqdm(range(transformed.shape[0]), desc="Finding pairs"):
172:         # find elements that are nearest neighbors but have different score
173:         # from the original particle and are within a bounded distance
174:         row = transformed.getrow(i)
175:         nearest_neighbor_idxs = row.nonzero()[1]
176:         within_x_distance_idxs = [
177:             idx
178:             for idx, nn_dist in zip(
179:                 nearest_neighbor_idxs,
180:                 np.array(
181:                     row[
182:                         [0 for _ in range(nearest_neighbor_idxs.shape[-1])],
183:                         nearest_neighbor_idxs,
184:                     ]
185:                 )[0].tolist(),
186:             )
187:             if nn_dist <= cfg.dist_x_threshold
188:         ]
189:         if cfg.dist_y_threshold is not None:
190:             selected_idxs = [
191:                 idx
192:                 for idx, score in zip(
193:                     within_x_distance_idxs, filtered_scores[within_x_distance_idxs]
194:                 )
195:                 if abs_subtract_replace_infs(score, filtered_scores[i])
196:                 <= cfg.dist_y_threshold
197:             ]
198:         else:
199:             selected_idxs = within_x_distance_idxs
200:         for idx in selected_idxs:
201:             if i < idx:
202:                 idx_pairs.add((i, idx))
203:             else:
204:                 idx_pairs.add((idx, i))
205:     idx_pairs = list(idx_pairs)
206:     logging.info(f"{len(idx_pairs)} index pairs satisfied conditions.")
207:     outputs = get_outputs_from_idx_pairs(
208:         idx_pairs,
209:         filtered,
210:         filtered_scores,
211:         allow_same_score_pair=allow_same_score_pair,
212:         df=df,
213:     )
214:     if cfg.max_proportion_infeasible is not None:
215:         outputs = filter_infeasible_examples(cfg, outputs)
216:     return outputs
217: 
218: 
219: def get_score_pairs_df(
220:     i: int,
221:     j: int,
222:     scores: torch.Tensor,
223:     library: torch.Tensor,
224:     allow_same_score_pair: bool = False,
225:     df: pd.DataFrame = None,
226: ) -> Optional[Dict[str, Any]]:
227:     score_i = scores[i]
228:     score_j = scores[j]
229:     particle_i = library[i]
230:     particle_j = library[j]
231:     if torch.isnan(score_i).item():
232:         score_i = torch.inf
233:     if torch.isnan(score_j).item():
234:         score_j = torch.inf
235:     if score_i > score_j:
236:         higher_score = score_i
237:         lower_score = score_j
238:         higher_score_p = particle_i
239:         lower_score_p = particle_j
240:         higher_idx = i
241:         lower_idx = j
242:     elif score_j > score_i:
243:         higher_score = score_j
244:         lower_score = score_i
245:         higher_score_p = particle_j
246:         lower_score_p = particle_i
247:         higher_idx = j
248:         lower_idx = i
249:     elif not allow_same_score_pair:
250:         logging.warning(
251:             f"Pair of particles with the same score:\n{particle_i}\n{particle_j}\nScore: {score_i}"
252:         )
253:         return None
254:     else:
255:         higher_score = score_i
256:         lower_score = score_j
257:         higher_score_p = particle_i
258:         lower_score_p = particle_j
259:         higher_idx = i
260:         lower_idx = j
261: 
262:     output_dict = {
263:         "lower_score_particle": lower_score_p.tolist(),
264:         "lower_score": f"{lower_score:.3f}",
265:         "higher_score_particle": higher_score_p.tolist(),
266:         "higher_score": f"{higher_score:.3f}",  # higher score is worse! can be inf
267:     }
268:     if "loglikelihood" in df.columns:
269:         output_dict["lower_particle_loglikelihood"] = df.iloc[lower_idx][
270:             "loglikelihood"
271:         ]
272:         output_dict["higher_particle_loglikelihood"] = df.iloc[higher_idx][
273:             "loglikelihood"
274:         ]
275:     return output_dict
276: 
277: 
278: def get_score_pairs(
279:     score_i: torch.Tensor,  # single-element tensor
280:     score_j: torch.Tensor,
281:     particle_i: torch.Tensor,
282:     particle_j: torch.Tensor,
283:     allow_same_score_pair: bool = False,
284: ) -> Optional[Dict[str, Any]]:
285:     if torch.isnan(score_i).item():
286:         score_i = torch.inf
287:     if torch.isnan(score_j).item():
288:         score_j = torch.inf
289:     if score_i > score_j:
290:         higher_score = score_i
291:         lower_score = score_j
292:         higher_score_p = particle_i
293:         lower_score_p = particle_j
294:     elif score_j > score_i:
295:         higher_score = score_j
296:         lower_score = score_i
297:         higher_score_p = particle_j
298:         lower_score_p = particle_i
299:     elif not allow_same_score_pair:
300:         logging.warning(
301:             f"Pair of particles with the same score:\n{particle_i}\n{particle_j}\nScore: {score_i}"
302:         )
303:         return None
304:     else:
305:         higher_score = score_i
306:         lower_score = score_j
307:         higher_score_p = particle_i
308:         lower_score_p = particle_j
309: 
310:     output_dict = {
311:         "lower_score_particle": lower_score_p.tolist(),
312:         "lower_score": f"{lower_score:.3f}",
313:         "higher_score_particle": higher_score_p.tolist(),
314:         "higher_score": f"{higher_score:.3f}",  # higher score is worse! can be inf
315:     }
316:     return output_dict
317: 
318: 
319: def get_outputs_from_idx_pairs(
320:     idx_pairs: List[Tuple[int, int]],
321:     library: torch.Tensor,
322:     scores: torch.Tensor,
323:     allow_same_score_pair: bool = False,
324:     df: pd.DataFrame = None,
325: ) -> List[Dict[str, Any]]:
326:     outputs = []
327:     for i, j in tqdm(idx_pairs, desc="Creating output records from index pairs"):
328:         output_dict = get_score_pairs_df(
329:             i, j, scores, library, allow_same_score_pair=allow_same_score_pair, df=df
330:         )
331:         if output_dict is not None:
332:             outputs.append(output_dict)
333:     logging.info(f"{len(outputs)} output records.")
334:     return outputs
335: 
336: 
337: def filter_infeasible_examples(
338:     cfg: DictConfig,
339:     curr_examples: List[Dict[str, Any]],
340:     score_field: str = "higher_score",
341: ) -> List[Dict[str, Any]]:
342:     no_infeasible_seq = [
343:         i for i, ex in enumerate(curr_examples) if ex[score_field] != "inf"
344:     ]
345:     w_infeasible_seq = [
346:         i for i, ex in enumerate(curr_examples) if ex[score_field] == "inf"
347:     ]
348:     num_feasible = len(no_infeasible_seq)
349:     max_infeasible_examples = (
350:         num_feasible
351:         * cfg.max_proportion_infeasible
352:         / (1 - cfg.max_proportion_infeasible)
353:     )
354:     max_infeasible_examples = int(np.round(max_infeasible_examples))
355:     random.seed(cfg.seed)
356:     w_infeasible_seq = random.sample(
357:         w_infeasible_seq, k=min(len(w_infeasible_seq), max_infeasible_examples)
358:     )
359:     data_idxs = no_infeasible_seq + w_infeasible_seq
360:     random.shuffle(data_idxs)
361:     output_data = [curr_examples[i] for i in data_idxs]
362:     logging.info(
363:         f"Filtered dataset from {len(curr_examples)} to {len(output_data)} examples after downsampling infeasible examples."
364:     )
365:     return output_data
366: 
367: 
368: def find_preference_pairs(cfg: DictConfig, df: pd.DataFrame) -> List[Dict[str, Any]]:
369:     random.seed(cfg.seed)
370:     df = df.drop_duplicates(subset=["particle"])
371:     if cfg.n is not None:
372:         if cfg.filter_by_likelihood and len(df) > cfg.n:
373:             df = filter_by_likelihood_lower_threshold(
374:                 df, cfg.likelihood_quantile_threshold
375:             )
376:         elif cfg.filter_by_likelihood_range and len(df) > cfg.n:
377:             df = filter_by_likelihood_range(df, tuple(cfg.likelihood_quantile_range))
378:         df = df.sample(n=min(len(df), cfg.n), random_state=cfg.seed)
379: 
380:     if cfg.score_lower_threshold is not None:
381:         df = filter_by_score_df(df, cfg.score_lower_threshold)
382:     if cfg.max_proportion_infeasible is not None:
383:         data = filter_infeasible_examples(
384:             cfg, df.to_dict("records"), score_field="score"
385:         )
386:     else:
387:         data = df.to_dict("records")
388:     library = torch.stack([torch.LongTensor(p["particle"]) for p in data])
389:     ranking_scores = torch.FloatTensor([x["score"] for x in data])
390:     filtered = library
391:     filtered_scores = ranking_scores
392:     filtered = filtered.numpy()
393:     pynn_transformer = PyNNDescentTransformer(
394:         n_neighbors=cfg.n_neighbors, metric=cfg.distance_metric
395:     ).fit(filtered)
396:     transformed = pynn_transformer.transform(filtered)
397:     # loop through rows instead of doing matrix computation to save memory
398:     idx_triples = set([])
399:     for i in tqdm(range(transformed.shape[0]), desc="Finding pairs"):
400:         # find elements that are nearest neighbors
401:         # and are within a bounded distance
402:         row = transformed.getrow(i)
403:         nearest_neighbor_idxs = row.nonzero()[1]
404:         within_x_distance_idxs = [
405:             idx
406:             for idx, nn_dist in zip(
407:                 nearest_neighbor_idxs,
408:                 np.array(
409:                     row[
410:                         [0 for _ in range(nearest_neighbor_idxs.shape[-1])],
411:                         nearest_neighbor_idxs,
412:                     ]
413:                 )[0].tolist(),
414:             )
415:             if nn_dist <= cfg.dist_x_threshold
416:         ]
417:         # get all possible pairs of (y1, y2)
418:         all_pair_idxs = [
419:             (k, j) for k in within_x_distance_idxs for j in within_x_distance_idxs
420:         ]
421:         # also add the index i itself in pairs
422:         all_pair_idxs.extend([(i, k) for k in within_x_distance_idxs])
423:         curr_score = filtered_scores[i].item()
424:         # loop through all possible triples of (x, y1, y2) and check if valid
425:         for pair_idx in all_pair_idxs:
426:             first_score = filtered_scores[pair_idx[0]].item()
427:             second_score = filtered_scores[pair_idx[1]].item()
428:             if first_score < curr_score and second_score >= curr_score:
429:                 # y1 is yw, y2 is yl
430:                 idx_triples.add((i, pair_idx[0], pair_idx[1]))
431:             elif second_score < curr_score and first_score >= curr_score:
432:                 idx_triples.add((i, pair_idx[1], pair_idx[0]))
433:     idx_triples = list(idx_triples)
434:     outputs = []
435:     for x_idx, yw_idx, yl_idx in idx_triples:
436:         output_dict = {
437:             "prompt": filtered[x_idx].tolist(),
438:             "prompt_score": f"{filtered_scores[x_idx]:.3f}",
439:             "chosen": filtered[yw_idx].tolist(),
440:             "chosen_score": f"{filtered_scores[yw_idx]:.3f}",
441:             "rejected": filtered[yl_idx].tolist(),
442:             "rejected_score": f"{filtered_scores[yl_idx]:.3f}",
443:         }
444:         if "loglikelihood" in data[0].keys():
445:             output_dict["prompt_loglikelihood"] = data[x_idx]["loglikelihood"]
446:             output_dict["chosen_loglikelihood"] = data[yw_idx]["loglikelihood"]
447:             output_dict["rejected_loglikelihood"] = data[yl_idx]["loglikelihood"]
448:         outputs.append(output_dict)
449:     return outputs
450: 
451: 
452: @hydra.main(config_path="config", config_name="dataset_edit_pairs")
453: def main(cfg: DictConfig):
454:     logging.basicConfig(level=cfg.log_level.upper(), force=True)
455:     logging.info(f"Config:\n{pprint.pformat(OmegaConf.to_container(cfg))}")
456:     df = pd.read_json(cfg.source_dataset_path, orient="records", lines=True)
457:     df["particle"] = df["particle"].map(
458:         lambda input_str: (
459:             [int(x) for x in json.loads(input_str)]
460:             if isinstance(input_str, str)
461:             else [int(x) for x in input_str]
462:         )
463:     )
464:     if cfg.format == "minimal_edit_pairs":
465:         outputs = find_minimal_edit_pairs(cfg, df)
466:     elif cfg.format == "dense_neighborhood_pairs":
467:         outputs = find_dense_pairs(
468:             cfg, df, allow_same_score_pair=cfg.allow_same_score_pair
469:         )
470:     elif cfg.format == "dense_preference_pairs":
471:         outputs = find_preference_pairs(cfg, df)
472:     else:
473:         raise ValueError(f"Unknown format: '{cfg.format}'.")
474:     outputs = pd.DataFrame(outputs)
475:     outputs.to_json(cfg.output_path, orient="records", lines=True)
476: 
477: 
478: if __name__ == "__main__":
479:     main()