1: import json
2: import logging
3: import numpy as np
4: import os
5: import pandas as pd
6: import pprint
7: import s3fs
8: import torch
9: import torch.utils
10: import torch.utils.data
11: import wandb
12: 
13: from botorch.test_functions import SyntheticTestFunction
14: from datasets import Dataset
15: from holo.test_functions.closed_form import Ehrlich, RoughMtFuji
16: from omegaconf import DictConfig, OmegaConf
17: from transformers import (
18:     EvalPrediction,
19:     PreTrainedTokenizer,
20: )
21: from transformers.trainer import (
22:     OPTIMIZER_NAME,
23:     SCHEDULER_NAME,
24:     TRAINING_ARGS_NAME,
25:     TRAINER_STATE_NAME,
26: )
27: from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
28: 
29: from typing import (
30:     Any,
31:     Dict,
32:     Iterable,
33:     List,
34:     Mapping,
35:     Optional,
36:     Tuple,
37:     Union,
38: )
39: 
40: torch.set_printoptions(threshold=10_000)
41: 
42: 
43: def maybe_log(logger: logging.Logger, msg: str, level: str = "info"):
44:     if logger is None:
45:         return
46:     log_fn = getattr(logger, level)
47:     log_fn(msg)
48: 
49: 
50: def wandb_setup(cfg: DictConfig):
51:     """
52:     Runs `wandb.init` and `wandb.login`.
53:     The values in `cfg` are logged to the wandb run.
54:     """
55:     if not hasattr(cfg, "wandb_host") or cfg.wandb_host is None:
56:         cfg["wandb_host"] = "https://api.wandb.ai"
57: 
58:     if not hasattr(cfg, "wandb_mode") or cfg.wandb_mode is None:
59:         cfg["wandb_mode"] = "online"
60: 
61:     if not hasattr(cfg, "project_name") or cfg.project_name is None:
62:         cfg["project_name"] = "finetune_ehrlich"
63: 
64:     if not hasattr(cfg, "exp_name") or cfg.exp_name is None:
65:         cfg["exp_name"] = "default_group"
66: 
67:     wandb.login(host=cfg.wandb_host)
68: 
69:     wandb.init(
70:         project=cfg.project_name,
71:         mode=cfg.wandb_mode,
72:         group=cfg.exp_name,
73:         name=cfg.job_name,
74:         config=OmegaConf.to_container(cfg),
75:     )
76: 
77: 
78: # Function `strtobool` copied and adapted from `distutils` (as deprected
79: # in Python 3.10).
80: # Reference: https://github.com/python/cpython/blob/48f9d3e3faec5faaa4f7c9849fecd27eae4da213/Lib/distutils/util.py#L308-L321
81: 
82: 
83: def strtobool(val: str) -> bool:
84:     """Convert a string representation of truth to True or False booleans.
85: 
86:     True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
87:     are 'n', 'no', 'f', 'false', 'off', and '0'.
88: 
89:     Raises:
90:         ValueError: if 'val' is anything else.
91:     """
92:     val = val.lower()
93:     if val in ("y", "yes", "t", "true", "on", "1"):
94:         return True
95:     if val in ("n", "no", "f", "false", "off", "0"):
96:         return False
97:     raise ValueError(
98:         f"Invalid truth value, it should be a string but {val} was provided instead."
99:     )
100: 
101: 
102: def check_if_checkpoint_complete(
103:     fs: s3fs.S3FileSystem,
104:     local_checkpoint_dir: str,
105:     s3_checkpoint_dir: str,
106:     num_gpus: int = 2,
107:     num_shards: int = 3,
108:     logger: logging.Logger = None,
109: ) -> bool:
110:     os.makedirs(local_checkpoint_dir, exist_ok=True)
111:     files_to_check_for = [
112:         "config.json",
113:         "generation_config.json",
114:         OPTIMIZER_NAME,
115:         SCHEDULER_NAME,
116:         TRAINING_ARGS_NAME,
117:         TRAINER_STATE_NAME,
118:         "model.safetensors.index.json",
119:         "special_tokens_map.json",
120:         "tokenizer_config.json",
121:         "tokenizer.json",
122:     ]
123:     files_to_check_for.extend(
124:         [
125:             f"model-{i:05d}-of-{num_shards:05d}.safetensors"
126:             for i in range(1, num_shards + 1)
127:         ]
128:     )
129:     files_to_check_for.extend([f"rng_state_{i}.pth" for i in range(num_gpus)])
130:     if s3_checkpoint_dir.endswith("/"):
131:         s3_checkpoint_dir = s3_checkpoint_dir[:-1]
132:     if not local_checkpoint_dir.endswith("/"):
133:         local_checkpoint_dir += "/"
134:     for fn in files_to_check_for:
135:         if not os.path.exists(os.path.join(local_checkpoint_dir, fn)):
136:             maybe_log(
137:                 logger,
138:                 f"Checkpoint located at {local_checkpoint_dir} not complete. Missing {fn}.",
139:                 level="warning",
140:             )
141:             # But if the file is available on S3, just copy it over!
142:             if fs.exists(f"{s3_checkpoint_dir}/{fn}"):
143:                 maybe_log(
144:                     logger,
145:                     f"Found {fn} in {s3_checkpoint_dir}. Copying over.",
146:                     level="info",
147:                 )
148:                 fs.get(f"{s3_checkpoint_dir}/{fn}", local_checkpoint_dir)
149:             else:
150:                 return False
151:         else:
152:             # Check that it also exists in s3!
153:             if not fs.exists(f"{s3_checkpoint_dir}/{fn}"):
154:                 maybe_log(
155:                     logger,
156:                     f"{fn} found in {local_checkpoint_dir} but not on s3. Copying over to {s3_checkpoint_dir}/.",
157:                     level="info",
158:                 )
159:                 fs.put(f"{local_checkpoint_dir}{fn}", f"{s3_checkpoint_dir}/")
160:     return True
161: 
162: 
163: def find_and_log_checkpoints(
164:     fs: s3fs.S3FileSystem,
165:     s3_output_dir: str,
166:     local_output_dir: str,
167:     num_gpus: int = 2,
168:     num_shards: int = 3,
169:     logger: logging.Logger = None,
170: ) -> Optional[str]:
171:     """
172:     If checkpoints are available, return the latest local checkpoint.
173:     Also ensure that the best checkpoint is saved and copied to local directory.
174:     """
175:     if not s3_output_dir.endswith("/"):
176:         s3_output_dir += "/"
177:     checkpoint_dirs = []
178:     if not fs.exists(s3_output_dir):
179:         maybe_log(logger, f"{s3_output_dir} does not exist.", level="info")
180:         return None
181:     for fp in fs.ls(s3_output_dir):
182:         if f"{PREFIX_CHECKPOINT_DIR}-" in fp:
183:             ckpt_num = fp.split(f"{PREFIX_CHECKPOINT_DIR}-")[-1]
184:             checkpoint_dirs.append((f"s3://{fp}", int(ckpt_num)))
185:     if len(checkpoint_dirs) == 0:
186:         return None
187:     checkpoint_dirs = sorted(checkpoint_dirs, key=lambda p: p[1])
188:     found_good_ckpt = False
189:     for ckpt_idx in range(len(checkpoint_dirs) - 1, -1, -1):
190:         latest_s3_checkpoint_dir = checkpoint_dirs[ckpt_idx][0]
191:         latest_local_checkpoint_dir = os.path.join(
192:             local_output_dir, f"{PREFIX_CHECKPOINT_DIR}-{checkpoint_dirs[ckpt_idx][1]}"
193:         )
194:         if check_if_checkpoint_complete(
195:             fs,
196:             latest_local_checkpoint_dir,
197:             latest_s3_checkpoint_dir,
198:             num_gpus=num_gpus,
199:             num_shards=num_shards,
200:             logger=logger,
201:         ):
202:             found_good_ckpt = True
203:             break
204:     if not found_good_ckpt:
205:         return None
206: 
207:     # Now look for best checkpoint
208:     trainer_state = json.load(
209:         open(f"{latest_local_checkpoint_dir}/{TRAINER_STATE_NAME}")
210:     )
211:     best_ckpt_dir = trainer_state["best_model_checkpoint"]
212:     if best_ckpt_dir is None:
213:         return latest_local_checkpoint_dir
214:     best_ckpt_num = best_ckpt_dir.split(f"{PREFIX_CHECKPOINT_DIR}-")[-1]
215:     best_ckpt_results = check_if_checkpoint_complete(
216:         fs,
217:         best_ckpt_dir,
218:         f"{s3_output_dir}{PREFIX_CHECKPOINT_DIR}-{best_ckpt_num}",
219:         num_gpus=num_gpus,
220:         num_shards=num_shards,
221:         logger=logger,
222:     )
223:     if best_ckpt_results is None:
224:         maybe_log(
225:             logger,
226:             f"Found latest checkpoint {latest_local_checkpoint_dir} but not the best checkpoint {best_ckpt_dir}.",
227:             level="warning",
228:         )
229:         return None
230:     return latest_local_checkpoint_dir
231: 
232: 
233: def truncate_after_right_bracket(
234:     generated_str: str,
235:     logger: logging.Logger = None,
236:     return_num_chars_truncated: bool = False,
237: ) -> Union[str, Tuple[str, int]]:
238:     """If the generated string contains a right bracket, truncate all content after it."""
239:     right_bracket = "]"
240:     num_truncated_chars = 0
241:     if right_bracket not in generated_str:
242:         if return_num_chars_truncated:
243:             return generated_str, num_truncated_chars
244:         return generated_str
245:     idx = generated_str.find(right_bracket)
246:     if idx != -1:
247:         content_to_truncate = generated_str[idx + 1 :]
248:         num_truncated_chars = len(content_to_truncate)
249:         truncated_str = generated_str[: idx + 1]
250:     else:
251:         truncated_str = generated_str
252:     if return_num_chars_truncated:
253:         return truncated_str, num_truncated_chars
254:     return truncated_str
255: 
256: 
257: def truncate_after_right_bracket_w_logps(
258:     output_token_ids: torch.Tensor,
259:     output_logps: torch.Tensor,
260:     tokenizer: PreTrainedTokenizer,
261:     length_normalized: bool = True,
262: ) -> Tuple[str, float]:
263:     """
264:     Given the output token IDs and token log-likelihoods, truncate both
265:     after the first right bracket.
266: 
267:     output_token_ids: 1-D tensor containing the token IDs of the output sequence. Shape: (max_new_tokens,)
268:     output_logps: 1-D tensor containing the log-probs of each output token. Shape: (max_new_tokens,)
269:     tokenizer: pre-trained tokenizer
270:     length_normalized: If true, returns the average log prob. Otherwise, returns the sum.
271: 
272:     Returns a tuple of the truncated string and the sum or average of the log probs.
273:     """
274:     assert output_token_ids.shape == output_logps.shape
275:     rbrac_id = tokenizer.encode("]")[0]
276: 
277:     if rbrac_id in output_token_ids:
278:         idx = torch.where(output_token_ids == rbrac_id)[0][0].item() + 1
279:         output_token_ids = output_token_ids[:idx]
280:         output_logps = output_logps[:idx]
281:     output_str = tokenizer.decode(output_token_ids)
282:     cum_logps = torch.sum(output_logps)
283:     if length_normalized:
284:         cum_logps = cum_logps / len(output_logps)
285:     return (output_str, cum_logps.item())
286: 
287: 
288: def starts_with_other_tensor(x: torch.Tensor, y: torch.Tensor) -> bool:
289:     """Checks if x (a 1-D tensor) starts with y (another 1-D tensor)"""
290:     return all(x[: len(y)] == y)
291: 
292: 
293: def load_test_fn_from_file(test_fn_fp: str, test_fn_type: str) -> SyntheticTestFunction:
294:     test_fn_params = pd.read_json(test_fn_fp, orient="records", lines=True).to_dict(
295:         "records"
296:     )[0]
297:     if test_fn_type == "ehrlich":
298:         test_fn = Ehrlich(
299:             num_states=test_fn_params["num_states"],
300:             dim=test_fn_params["dim"],
301:             num_motifs=test_fn_params["num_motifs"],
302:             motif_length=test_fn_params["motif_length"],
303:             quantization=test_fn_params["quantization"],
304:             noise_std=test_fn_params["noise_std"],
305:             negate=test_fn_params["negate"],
306:             random_seed=test_fn_params["random_seed"],
307:         )
308:     else:
309:         test_fn = RoughMtFuji(
310:             dim=test_fn_params["dim"],
311:             additive_term=test_fn_params["additive_term"],
312:             random_term_std=test_fn_params["random_term_std"],
313:             noise_std=test_fn_params["noise_std"],
314:             negate=test_fn_params["negate"],
315:             random_seed=test_fn_params["random_seed"],
316:         )
317:     return test_fn
318: 
319: 
320: def parse_particle_and_score(
321:     input_str: str, test_fn: SyntheticTestFunction
322: ) -> Optional[Tuple[List[int], float]]:
323:     """
324:     Checks that <input_str> can be parsed into a list with test_fn.dim integer elements.
325:     For the Ehrlich function, also checks the range of the values.
326: 
327:     If parsable, returns tuple of (particle, score). otherwise, returns None.
328:     """
329:     try:
330:         particle = json.loads(input_str)
331:     except:
332:         return None
333:     if not isinstance(particle, list):
334:         return None
335:     try:
336:         if any([int(x) != x for x in particle]):
337:             return None
338:     except:
339:         return None
340:     particle = [int(x) for x in particle]
341:     if len(particle) != test_fn.dim:
342:         return None
343:     if hasattr(test_fn, "num_states"):
344:         if any([x >= test_fn.num_states or x < 0 for x in particle]):
345:             return None
346:     score = test_fn(torch.LongTensor([particle])).item()
347:     return particle, score
348: 
349: 
350: def preprocess_generations(
351:     generated_token_ids: torch.LongTensor,
352:     inputs: Mapping[str, Any],
353:     tokenizer: PreTrainedTokenizer,
354: ) -> torch.LongTensor:
355:     """
356:     Workaround for a bug where the HuggingFace Trainer evaluate() function
357:     gathers the generations across GPUs but not the inputs. Find the generations that map to the inputs on this device.
358:     """
359:     generated_token_ids[generated_token_ids == -100] = tokenizer.pad_token_id
360:     input_ids = inputs["input_ids"]
361:     input_ids[input_ids == -100] = tokenizer.pad_token_id
362: 
363:     if generated_token_ids.shape[0] > input_ids.shape[0]:
364:         generation_idxs = []
365:         for i in range(input_ids.shape[0]):
366:             ex_input_ids = input_ids[i]
367:             # get only the part of the input IDs that is before the target sequence
368:             target_idxs = torch.where(inputs["labels"][i] != -100)[0]
369:             if len(target_idxs) > 0:
370:                 len_non_target_ids = target_idxs[0]
371:             else:
372:                 len_non_target_ids = 0
373:             ex_input_ids = ex_input_ids[:len_non_target_ids]
374:             for j in range(generated_token_ids.shape[0]):
375:                 if starts_with_other_tensor(generated_token_ids[j], ex_input_ids):
376:                     generation_idxs.append(j)
377:                     break
378:             if len(generation_idxs) != i + 1:
379:                 generated_token_ids_str = "\n".join(
380:                     [f"{t}" for t in generated_token_ids]
381:                 )
382:                 raise ValueError(
383:                     f"Could not find an input with IDs that the current generation starts with.\n"
384:                     + f"Original input:{input_ids[i]}\n{input_ids[i].shape}\n"
385:                     + f"Sliced input:\n{ex_input_ids}\n{ex_input_ids.shape}\n"
386:                     + f"Labels:\n{inputs['labels'][i]}\n{inputs['labels'][i].shape}\n"
387:                     + f"Generations:\n{generated_token_ids_str}\n{generated_token_ids.shape}"
388:                 )
389:         generated_token_ids = generated_token_ids[generation_idxs]
390:     return generated_token_ids
391: 
392: 
393: def postprocess_generations(
394:     generated_token_ids: torch.LongTensor,
395:     input_ids: torch.LongTensor,
396:     labels: torch.LongTensor,
397:     tokenizer: PreTrainedTokenizer,
398:     logger: logging.Logger,
399: ) -> Tuple[List[str], int]:
400:     """
401:     Remove the inputs from the output generations and truncate characters past the first ']'
402:     symbol. Decode generations.
403:     """
404:     predictions = []
405:     for i in range(generated_token_ids.shape[0]):
406:         ex_input_ids = input_ids[i]
407:         # get only the part of the input IDs that is before the target sequence
408:         target_idxs = torch.where(labels[i] != -100)[0]
409:         if len(target_idxs) > 0:
410:             len_non_target_ids = target_idxs[0]
411:         else:
412:             len_non_target_ids = len(labels[i])
413:         ########
414: 
415:         input_decode = tokenizer.decode(
416:             ex_input_ids,
417:             skip_special_tokens=True,
418:             clean_up_tokenization_spaces=True,
419:         )
420:         entire_decode = tokenizer.decode(
421:             generated_token_ids[i],
422:             skip_special_tokens=True,
423:             clean_up_tokenization_spaces=True,
424:         )
425:         decoded_generation = tokenizer.decode(
426:             generated_token_ids[i][len_non_target_ids:],
427:             skip_special_tokens=True,
428:             clean_up_tokenization_spaces=True,
429:         )
430:         logger.info(
431:             f"Entire decode: {entire_decode}.\nInput tokens: {input_decode}\nDecoded after removing initial prompt tokens: {decoded_generation}"
432:         )
433:         truncated, num_chars_truncated = truncate_after_right_bracket(
434:             decoded_generation, logger=logger, return_num_chars_truncated=True
435:         )
436:         predictions.append(truncated)
437:     return predictions, num_chars_truncated
438: 
439: 
440: class EvaluatorPlainPairs:
441:     def __init__(
442:         self,
443:         cfg: DictConfig,
444:         tokenizer: PreTrainedTokenizer,
445:         logger: logging.Logger = None,
446:     ):
447:         self.tokenizer = tokenizer
448:         self.test_fn = load_test_fn_from_file(cfg.test_fn_fp, cfg.test_fn_type)
449:         self.reset()
450:         self.logger = logger
451: 
452:     def reset(self):
453:         self.num_parsable = 0
454:         self.num_correct_length = 0
455:         self.num_values_in_range = 0
456:         self.num_feasible = 0
457:         self.num_total = 0
458:         self.num_chars_truncated = []
459:         self.scores = []
460:         self.expected_scores = []
461: 
462:     @torch.no_grad()
463:     def __call__(
464:         self, eval_pred: EvalPrediction, compute_result: bool = False
465:     ) -> Optional[Mapping[str, float]]:
466:         generated_token_ids, _, inputs = eval_pred
467:         generated_token_ids = preprocess_generations(
468:             generated_token_ids, inputs, self.tokenizer
469:         )
470: 
471:         self.num_total += generated_token_ids.shape[0]
472:         input_ids = inputs["input_ids"]
473:         predictions, num_chars_truncated = postprocess_generations(
474:             generated_token_ids,
475:             input_ids,
476:             inputs["labels"],
477:             self.tokenizer,
478:             self.logger,
479:         )
480:         self.num_chars_truncated.append(num_chars_truncated)
481:         input_strs = self.tokenizer.batch_decode(
482:             input_ids,
483:             skip_special_tokens=True,
484:             clean_up_tokenization_spaces=True,
485:         )
486:         exp_scores = []
487:         for input_str in input_strs:
488:             input_str = input_str[: input_str.find("Particle:")]
489:             input_str = input_str[len("Score:") :]
490:             exp_score = float(input_str)
491:             exp_scores.append(exp_score)
492:         # make new lists for predictions and targets because not all
493:         # scores will be added (since some are NaN or inf)
494:         parsed_predictions = []
495:         targets = []
496:         for i in range(len(predictions)):
497:             pred = predictions[i]
498:             # first see if parsable as tensor of ints
499:             try:
500:                 pred_list = json.loads(pred)
501:                 assert isinstance(pred_list, list)
502:                 particle = []
503:                 for x in pred_list:
504:                     if int(x) != x:
505:                         continue
506:                     particle.append(int(x))
507:             except Exception:
508:                 # not parsable
509:                 maybe_log(
510:                     self.logger,
511:                     f"Prediction is not parsable. Continuing. Prediction:\n{pred}",
512:                     level="warning",
513:                 )
514:                 continue
515:             self.num_parsable += 1
516:             if len(particle) != self.test_fn.dim:
517:                 maybe_log(
518:                     self.logger,
519:                     f"Prediction has the wrong length ({len(particle)} != {self.test_fn.dim}): {particle}",
520:                     level="warning",
521:                 )
522:                 continue
523:             self.num_correct_length += 1
524:             if any([x < 0 or x >= self.test_fn.num_states for x in particle]):
525:                 maybe_log(
526:                     self.logger,
527:                     f"Prediction has some elements that are outside the range [0, {self.test_fn.num_states - 1}]: {particle}",
528:                     level="warning",
529:                 )
530:                 continue
531:             self.num_values_in_range += 1
532:             particle = torch.FloatTensor(particle)
533:             score = self.test_fn(particle).item()
534:             if score == float("inf"):
535:                 maybe_log(
536:                     self.logger,
537:                     f"obs score {score} is inf. Continuing...",
538:                     level="warning",
539:                 )
540:                 continue
541:             self.num_feasible += 1
542:             if exp_scores[i] == float("inf"):
543:                 maybe_log(
544:                     self.logger,
545:                     f"exp score {exp_scores[i]} is inf. Continuing...",
546:                     level="warning",
547:                 )
548:                 continue
549:             parsed_predictions.append(score)
550:             targets.append(exp_scores[i])
551:         self.scores.extend(parsed_predictions)
552:         self.expected_scores.extend(targets)
553: 
554:         if not compute_result:
555:             return
556:         self.expected_scores = np.array(self.expected_scores)
557:         self.scores = np.array(self.scores)
558:         squared_errors = (
559:             (self.expected_scores - self.scores) ** 2 if len(self.scores) > 0 else None
560:         )
561:         output_dict = {
562:             "%_parsable": self.num_parsable / self.num_total,
563:             "%_correct_length": (
564:                 self.num_correct_length / self.num_parsable
565:                 if self.num_parsable > 0
566:                 else None
567:             ),
568:             "%_values_in_range": (
569:                 self.num_values_in_range / self.num_correct_length
570:                 if self.num_correct_length > 0
571:                 else None
572:             ),
573:             "%_feasible": (
574:                 self.num_feasible / self.num_values_in_range
575:                 if self.num_values_in_range > 0
576:                 else None
577:             ),
578:             "avg_score": np.mean(self.scores) if len(self.scores) > 0 else None,
579:             "avg_num_chars_truncated": np.mean(self.num_chars_truncated),
580:             "rmse": (
581:                 np.sqrt(np.mean(squared_errors)) if squared_errors is not None else None
582:             ),
583:         }
584:         self.reset()
585:         return output_dict
586: 
587: 
588: def get_response_template_plain_pairs(tokenizer: PreTrainedTokenizer):
589:     response_template_with_context = "\nParticle:"
590:     response_template_ids = tokenizer.encode(
591:         response_template_with_context, add_special_tokens=False
592:     )
593:     return response_template_ids
594: 
595: 
596: def formatting_texts_func_plain_pairs(
597:     examples: Mapping[str, Iterable[Any]]
598: ) -> List[str]:
599:     output_texts = []
600:     for i in range(len(examples["score"])):
601:         score = examples["score"][i]
602:         particles = [int(x) for x in json.loads(examples["particle"][i])]
603:         particles_str = json.dumps(particles)
604:         output_texts.append(f"Score: {score:.2f}\nParticle: {particles_str}")
605:     return output_texts
606: 
607: 
608: def get_response_template_edit_pairs(tokenizer: PreTrainedTokenizer):
609:     response_template_with_context = "\n"
610:     response_template_ids = tokenizer.encode(
611:         response_template_with_context, add_special_tokens=False
612:     )
613:     return response_template_ids
614: 
615: 
616: def formatting_texts_func_edit_pairs(
617:     examples: Mapping[str, Iterable[Any]],
618:     include_target: bool = True,
619:     higher_score_particle_field: str = "higher_score_particle",
620:     lower_score_particle_field: str = "lower_score_particle",
621:     prefix: str = "<inc>",
622: ) -> List[str]:
623:     # lower score is better!
624:     output_texts = []
625:     if prefix:
626:         prefix_str = f"{prefix} "
627:     else:
628:         prefix_str = ""
629:     for i in range(len(examples[higher_score_particle_field])):
630:         input_particle = [int(x) for x in examples[higher_score_particle_field][i]]
631:         if include_target:
632:             target_particle = [int(x) for x in examples[lower_score_particle_field][i]]
633:             target_str = f"{json.dumps(target_particle)}"
634:         else:
635:             target_str = ""
636:         particles_str = f"{prefix_str}{json.dumps(input_particle)}\n{target_str}"
637:         output_texts.append(particles_str)
638:     return output_texts
639: 
640: 
641: class EvaluatorEditPairs:
642:     def __init__(
643:         self,
644:         cfg: DictConfig,
645:         tokenizer: PreTrainedTokenizer,
646:         logger: logging.Logger = None,
647:         control_code: str = "<inc>",
648:     ):
649:         self.tokenizer = tokenizer
650:         self.test_fn = load_test_fn_from_file(cfg.test_fn_fp, cfg.test_fn_type)
651:         self.reset()
652:         self.logger = logger
653:         self.control_code = control_code
654: 
655:     def reset(self):
656:         self.num_parsable = 0
657:         self.num_correct_length = 0
658:         self.num_values_in_range = 0
659:         self.num_feasible = 0
660:         self.num_total = 0
661:         self.num_repeated_input = 0
662:         self.num_chars_truncated = []
663:         self.scores = []
664:         self.rewards = []
665:         self.num_decreased_score = 0
666: 
667:     def get_reward(self, input_score: float, target_score: float) -> float:
668:         if input_score is None or np.isinf(input_score) or np.isnan(input_score):
669:             input_score = 0.0
670:         if target_score is None or np.isinf(target_score) or np.isnan(target_score):
671:             target_score = 0.0
672:         if input_score > target_score:
673:             return input_score - target_score
674:         return 0.0
675: 
676:     @torch.no_grad()
677:     def __call__(
678:         self, eval_pred: EvalPrediction, compute_result: bool = False
679:     ) -> Optional[Mapping[str, float]]:
680:         generated_token_ids, _, inputs = eval_pred
681:         generated_token_ids = preprocess_generations(
682:             generated_token_ids, inputs, self.tokenizer
683:         )
684:         self.num_total += generated_token_ids.shape[0]
685: 
686:         input_ids = inputs["input_ids"]
687:         predictions, num_chars_truncated = postprocess_generations(
688:             generated_token_ids,
689:             input_ids,
690:             inputs["labels"],
691:             self.tokenizer,
692:             self.logger,
693:         )
694:         self.num_chars_truncated.append(num_chars_truncated)
695: 
696:         input_strs = self.tokenizer.batch_decode(
697:             input_ids,
698:             skip_special_tokens=True,
699:             clean_up_tokenization_spaces=True,
700:         )
701:         input_scores = []
702:         input_particles = []
703:         for input_str in input_strs:
704:             input_str = input_str[len(self.control_code) :]
705:             input_str = input_str[: input_str.find("\n")]
706:             input_particle = torch.FloatTensor(json.loads(input_str))
707:             input_particles.append(input_particle)
708:             input_score = self.test_fn(input_particle).item()
709:             input_scores.append(input_score)
710: 
711:         # make new lists for predictions because not all
712:         # scores will be added (since some are NaN or inf)
713:         parsed_predictions = []
714:         for i in range(len(predictions)):
715:             pred = predictions[i]
716:             # first see if parsable as tensor of ints
717:             try:
718:                 pred_list = json.loads(pred)
719:                 assert isinstance(pred_list, list)
720:                 particle = []
721:                 for x in pred_list:
722:                     if int(x) != x:
723:                         continue
724:                     particle.append(int(x))
725:             except Exception:
726:                 # not parsable
727:                 maybe_log(
728:                     self.logger,
729:                     f"Prediction is not parsable. Continuing. Prediction:\n{pred}",
730:                     level="warning",
731:                 )
732:                 continue
733:             self.num_parsable += 1
734:             if len(particle) != self.test_fn.dim:
735:                 maybe_log(
736:                     self.logger,
737:                     f"Prediction has the wrong length ({len(particle)} != {self.test_fn.dim}): {particle}",
738:                     level="warning",
739:                 )
740:                 continue
741:             self.num_correct_length += 1
742:             if any([x < 0 or x >= self.test_fn.num_states for x in particle]):
743:                 maybe_log(
744:                     self.logger,
745:                     f"Prediction has some elements that are outside the range [0, {self.test_fn.num_states - 1}]: {particle}",
746:                     level="warning",
747:                 )
748:                 continue
749:             self.num_values_in_range += 1
750:             particle = torch.FloatTensor(particle)
751:             score = self.test_fn(particle).item()
752:             reward = self.get_reward(input_scores[i], score)
753:             self.rewards.append(reward)
754:             # score is in (-1.0, infinity)
755:             if score < input_scores[i]:
756:                 self.num_decreased_score += 1
757:             elif score == input_scores[i]:
758:                 # check if the model outputted the same particle as was in the prompt
759:                 is_same = all([x == y for x, y in zip(particle, input_particles[i])])
760:                 if is_same:
761:                     self.num_repeated_input += 1
762: 
763:             if score == float("inf"):
764:                 maybe_log(
765:                     self.logger,
766:                     f"obs score {score} is inf. Continuing...",
767:                     level="warning",
768:                 )
769:                 continue
770:             self.num_feasible += 1
771:             parsed_predictions.append(score)
772:         self.scores.extend(parsed_predictions)
773: 
774:         if not compute_result:
775:             return
776:         self.scores = np.array(self.scores)
777:         self.rewards = np.array(self.rewards)
778:         output_dict = {
779:             "%_parsable": self.num_parsable / self.num_total,
780:             "%_correct_length": (
781:                 self.num_correct_length / self.num_parsable
782:                 if self.num_parsable > 0
783:                 else None
784:             ),
785:             "%_values_in_range": (
786:                 self.num_values_in_range / self.num_correct_length
787:                 if self.num_correct_length > 0
788:                 else None
789:             ),
790:             "%_decreased_score": (
791:                 self.num_decreased_score / self.num_values_in_range
792:                 if self.num_values_in_range > 0
793:                 else None
794:             ),
795:             "%_repeated_input": (
796:                 self.num_repeated_input / self.num_values_in_range
797:                 if self.num_values_in_range > 0
798:                 else None
799:             ),
800:             "%_feasible": (
801:                 self.num_feasible / self.num_values_in_range
802:                 if self.num_values_in_range > 0
803:                 else None
804:             ),
805:             "avg_score": np.mean(self.scores) if len(self.scores) > 0 else None,
806:             "min_score": np.min(self.scores) if len(self.scores) > 0 else None,
807:             "avg_num_chars_truncated": np.mean(self.num_chars_truncated),
808:             "avg_reward": np.mean(self.rewards) if len(self.rewards) > 0 else None,
809:             "max_reward": np.max(self.rewards) if len(self.rewards) > 0 else None,
810:         }
811:         maybe_log(
812:             self.logger,
813:             f"num_parsable: {self.num_parsable}, num_total: {self.num_total},"
814:             + f" num_correct_length: {self.num_correct_length}, "
815:             + f"num_values_in_range: {self.num_values_in_range}, "
816:             + f"num_decreased_score: {self.num_decreased_score}, "
817:             + f"num_repeated_input: {self.num_repeated_input}, "
818:             + f"num_feasible: {self.num_feasible} ",
819:             level="info",
820:         )
821:         self.reset()
822:         return output_dict
823: 
824: 
825: def get_ehrlich_rewards(
826:     input_scores: List[float], target_scores: List[float]
827: ) -> torch.Tensor:
828:     rewards = []
829:     for i, t in zip(input_scores, target_scores):
830:         if i is None or np.isinf(i) or np.isnan(i):
831:             i = 0.0  # set scores of infeasible particles to 0
832:         if t is None or np.isinf(t) or np.isnan(t):
833:             t = 0.0
834:         if i > t:
835:             rewards.append(i - t)
836:         else:
837:             rewards.append(0)
838:     return torch.FloatTensor(rewards)
839: 
840: 
841: def get_ehrlich_metrics_for_outputs(
842:     random_batches_dataset: torch.utils.data.Dataset,
843:     test_fn: SyntheticTestFunction,
844:     outputs: List[str],
845:     input_field_name: str,
846:     input_score_field_name: str,
847: ) -> Dict[str, float]:
848:     """
849:     Returns both a dictionary of computed metrics as well as the list of scores.
850:     """
851:     input_particles = [d[input_field_name] for d in random_batches_dataset]
852:     input_scores = [d[input_score_field_name] for d in random_batches_dataset]
853:     total_chars_truncated = 0
854:     num_parsable = 0
855:     num_correct_length = 0
856:     num_values_in_range = 0
857:     num_feasible = 0
858:     num_repeated_input = 0
859:     all_scores_including_nulls = []
860:     num_decreased_score = 0
861:     rewards = []
862: 
863:     for i, o in enumerate(outputs):
864:         o, num_chars_truncated = truncate_after_right_bracket(
865:             o, return_num_chars_truncated=True
866:         )
867:         total_chars_truncated += num_chars_truncated
868:         try:
869:             o_list = json.loads(o)
870:             assert isinstance(o_list, list)
871:             assert all([int(x) == x for x in o_list])
872:             particle = [int(x) for x in o_list]
873:         except Exception:
874:             logging.warning(f"Prediction is not parsable. Continuing. Prediction:\n{o}")
875:             all_scores_including_nulls.append(None)
876:             continue
877:         num_parsable += 1
878:         if len(o_list) != test_fn.dim:
879:             all_scores_including_nulls.append(None)
880:             continue
881:         num_correct_length += 1
882:         if isinstance(test_fn, Ehrlich):
883:             if any([x < 0 or x >= test_fn.num_states for x in particle]):
884:                 all_scores_including_nulls.append(None)
885:                 continue
886:             num_values_in_range += 1
887:         if particle == input_particles[i]:
888:             num_repeated_input += 1
889:         particle = torch.FloatTensor(particle)
890:         score = test_fn(particle).item()
891:         reward = get_ehrlich_rewards([input_scores[i]], [score])[0].item()
892:         rewards.append(reward)
893:         if input_scores[i] is None and score != float("inf"):
894:             num_decreased_score += 1
895:         elif input_scores[i] is not None and score < input_scores[i]:
896:             num_decreased_score += 1
897:         if score == float("inf"):
898:             all_scores_including_nulls.append(None)
899:             continue
900:         num_feasible += 1
901:         all_scores_including_nulls.append(score)
902:     num_total = len(outputs)
903:     scores_wo_nulls = [s for s in all_scores_including_nulls if s is not None]
904:     output_metrics = {
905:         "%_parsable": num_parsable / num_total,
906:         "%_correct_length": (
907:             num_correct_length / num_parsable if num_parsable > 0 else np.nan
908:         ),
909:         "%_decreased_score": (
910:             num_decreased_score / num_values_in_range
911:             if num_values_in_range > 0
912:             else np.nan
913:         ),
914:         "%_repeated_input": (
915:             num_repeated_input / num_values_in_range
916:             if num_values_in_range > 0
917:             else np.nan
918:         ),
919:         "%_feasible": (
920:             num_feasible / num_values_in_range if num_values_in_range > 0 else np.nan
921:         ),
922:         "avg_score": (np.mean(scores_wo_nulls) if len(scores_wo_nulls) > 0 else np.nan),
923:         "min_score": (np.min(scores_wo_nulls) if len(scores_wo_nulls) > 0 else np.nan),
924:         "avg_reward": (np.mean(rewards) if len(rewards) > 0 else np.nan),
925:         "max_reward": np.max(rewards) if len(rewards) > 0 else np.nan,
926:         "avg_num_chars_truncated": total_chars_truncated / num_total,
927:     }
928:     if isinstance(test_fn, Ehrlich):
929:         output_metrics["%_values_in_range"] = (
930:             num_values_in_range / num_correct_length
931:             if num_correct_length > 0
932:             else np.nan
933:         )
934:     return output_metrics