-
Notifications
You must be signed in to change notification settings - Fork 0
/
llm_randomness_eval.py
3145 lines (2733 loc) · 107 KB
/
llm_randomness_eval.py
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 random
import argparse
import logging
from pathlib import Path
import sys
import json
import os
import itertools
from enum import StrEnum, auto
import time
import torch
import ray
from openai import OpenAI
from config.config_utils import (
Config,
load_model_config,
load_judge_config,
load_experiment_config,
load_augmentation_config,
load_comparisons_config,
)
from config.config_keys import (
get_key_from_attribute_name,
REQUIRED_EXPERIMENT_CONFIG_KEYS,
OPTIONAL_EXPERIMENT_CONFIG_KEYS,
)
from model_utils import (
load_model,
load_tokenizer,
get_generation_inputs,
get_generation_outputs,
create_openai_input_file,
API,
INVALID_API_ERROR,
)
from dataset import get_dataset_class
from dataset.dataset import Dataset
from augmentation import get_augmentation_class
from augmentation.augmentation import Augmentation
from pair import (
PAIR_SYSTEM_PROMPT,
PAIR_INIT_PROMPT,
PAIR_PROCESS_RESPONSE,
PAIR_INIT_ASSISTANT_PREFILL,
PAIR_ASSISTANT_PREFILL,
)
EXPERIMENT_MESSAGE_PREFIX = "(\"{experiment_name}\") "
EXPERIMENT_AUGMENTATION_MESSAGE_PREFIX = (
"(\"{experiment_name}\":\"{augmentation_name}\") "
)
EXPERIMENT_MODEL_MESSAGE_PREFIX = "(\"{experiment_name}\":\"{model_alias}\") "
ALL_MESSAGE_PREFIX = (
"(\"{experiment_name}\":\"{model_alias}\":\"{augmentation_name}\") "
)
SKIPPING_MESSAGE = "Skipping..."
SKIPPING_EXPERIMENT_MESSAGE = "Skipping experiment..."
SKIPPING_CALCULATION_MESSAGE = "Skipping calculation..."
SKIPPING_COMPARISONS_MESSAGE = "Skipping comparisons for it..."
DUPLICATE_EXPERIMENT_MESSAGE = (
"Experiment \"{experiment_name}\" already started. "
f"{SKIPPING_MESSAGE}"
)
DUPLICATE_AUGMENTATION_MESSAGE = (
f"{EXPERIMENT_MESSAGE_PREFIX}"
"Augmentation \"{augmentation_name}\" already loaded. "
f"{SKIPPING_MESSAGE}"
)
DUPLICATE_MODEL_MESSAGE = (
f"{EXPERIMENT_MESSAGE_PREFIX}"
"Model \"{model_alias}\" already started. "
f"{SKIPPING_MESSAGE}"
)
PREVIOUS_RESULTS_FOUND_MESSAGE = (
f"{ALL_MESSAGE_PREFIX}"
"Loaded previous results found at \"{results_path}\"."
)
AUGMENTATION_UNIQUE_NAME_KEY_VALUE_PAIR = "_{key}_{value}"
AUGMENTATION_UNIQUE_NAME_SUFFIX = "_samples_{samples}"
AUGMENTATION_UNIQUE_NAME_VALUE_REPLACEMENTS = [
(".", "_"),
]
EXPERIMENT_AUGMENTATIONS_KEY = get_key_from_attribute_name(
attribute_name="augmentations",
config_keys=REQUIRED_EXPERIMENT_CONFIG_KEYS,
)
COMPARISONS_KEY = get_key_from_attribute_name(
attribute_name="comparisons",
config_keys=OPTIONAL_EXPERIMENT_CONFIG_KEYS,
)
LOAD_AUGMENTATION_CONFIG_NAME = (
"{experiment_name}."
f"{EXPERIMENT_AUGMENTATIONS_KEY}"
"[{i}]"
)
COMPARISONS_NAME = (
"{experiment_name}."
f"{COMPARISONS_KEY}"
"[{i}]"
)
EXPERIMENT_CONFIG_MESSAGE = (
f"{EXPERIMENT_MESSAGE_PREFIX}"
"Loaded experiment configuration:\n{config}"
)
JUDGE_CONFIG_MESSAGE = (
f"{EXPERIMENT_MESSAGE_PREFIX}"
"Loaded \"{judge_alias}\" judge configuration:\n{config}"
)
JUDGE_CONFIG_PREVIOUSLY_LOADED_MESSAGE = (
f"{EXPERIMENT_MESSAGE_PREFIX}"
"Judge configuration for \"{judge_alias}\" previously loaded."
)
MODEL_CONFIG_MESSAGE = (
f"{EXPERIMENT_MODEL_MESSAGE_PREFIX}"
"Loaded model configuration:\n{config}"
)
MODEL_CONFIG_PREVIOUSLY_LOADED_MESSAGE = (
f"{EXPERIMENT_MODEL_MESSAGE_PREFIX}"
"Model configuration previously loaded."
)
AUGMENTATION_KWARGS_FOR_UNIQUE_NAME = " ({augmentation_kwargs})"
AUGMENTATION_MESSAGE_SAMPLES = " {aug_samples} samples of"
AUGMENTATION_MESSAGE = (
f"{EXPERIMENT_AUGMENTATION_MESSAGE_PREFIX}"
"Augmented each prompt with{augmentation_samples} the "
"\"{augmentation_base_name}\"{augmentation_kwargs} augmentation."
)
AUGMENT_PROMPT_ERROR = (
f"{EXPERIMENT_AUGMENTATION_MESSAGE_PREFIX}"
"Error augmenting prompts:\n\t{message}\n"
f"{SKIPPING_MESSAGE}"
)
SAMPLES_ERROR_MESSAGE = (
f"{EXPERIMENT_MESSAGE_PREFIX}"
"At least one of augmentation_samples and output_samples must be 1. Got: "
"augmentation_samples={augs_samples}, "
"output_samples={output_samples}."
)
STARTED_GENERATION_TASK_MESSAGE = (
f"{EXPERIMENT_MODEL_MESSAGE_PREFIX}Started generation task."
)
STARTED_GENERATION_TASK_SPLIT_MESSAGE = (
f"{ALL_MESSAGE_PREFIX}Started generation task."
)
COMPLETED_GENERATION_TASK_MESSAGE = (
f"{EXPERIMENT_MODEL_MESSAGE_PREFIX}Completed generation task. "
"Started evaluation task..."
)
COMPLETED_GENERATION_TASK_SPLIT_MESSAGE = (
f"{ALL_MESSAGE_PREFIX}Completed generation task. Started evaluation task..."
)
COMPLETED_EVALUATION_MESSAGE = (
f"{ALL_MESSAGE_PREFIX}Completed evaluation task."
)
SUCCESS_RATE_MESSAGE = (
f"{ALL_MESSAGE_PREFIX}Success rate "
"(judge={judge_alias}, threshold="
"{threshold:.4f}): {success_rate:.4f}"
)
SAVED_RESULTS_MESSAGE = (
f"{ALL_MESSAGE_PREFIX}Saved results to "
"\"{save_path}\"."
)
COMPLETED_EVALUATIONS_MESSAGE = "Completed evaluations."
AVERAGE_INPUT_LENGTH = (
f"{ALL_MESSAGE_PREFIX}"
"Average input length: {average_length_chars:.2f} characters, "
"{average_length_tokens:.2f} tokens"
)
ERROR_MESSAGE = "{message}"
LOAD_EXPERIMENT_CONFIG_ERROR = (
"Error loading experiment configuration for \"{name}\" from "
"\"{config_path}\":\n\t{message}\n"
f"{SKIPPING_MESSAGE}"
)
LOAD_JUDGE_ERROR = (
f"{EXPERIMENT_MESSAGE_PREFIX}"
"Error loading judge configuration:\n\t{message}\n"
f"{SKIPPING_EXPERIMENT_MESSAGE}"
)
LOAD_DATASET_ERROR = (
f"{EXPERIMENT_MESSAGE_PREFIX}"
"Error loading dataset:\n\t{message}\n"
f"{SKIPPING_EXPERIMENT_MESSAGE}"
)
LOAD_AUGMENTATION_ERROR = (
f"{EXPERIMENT_MESSAGE_PREFIX}"
"Error loading augmentation configuration:\n\t{message}\n"
f"{SKIPPING_MESSAGE}"
)
LOAD_MODEL_ERROR = (
f"{EXPERIMENT_MESSAGE_PREFIX}"
"Error loading model configuration:\n\t{message}\n"
f"{SKIPPING_MESSAGE}"
)
OPENAI_FILE_RESPONSE_DELIMETER = "\n"
OPENAI_REQUEST_ERROR = "OpenAI API request {outcome}."
OPENAI_REQUEST_FAILED = f"{EXPERIMENT_MODEL_MESSAGE_PREFIX}" + \
OPENAI_REQUEST_ERROR.format(
outcome="failed"
)
OPENAI_REQUEST_EXPIRED = f"{EXPERIMENT_MODEL_MESSAGE_PREFIX}" + \
OPENAI_REQUEST_ERROR.format(
outcome="expired"
)
OPENAI_REQUEST_CANCELLED = f"{EXPERIMENT_MODEL_MESSAGE_PREFIX}" + \
OPENAI_REQUEST_ERROR.format(
outcome="cancelled"
)
PAIR_ATTACK_EXPERIMENTS_ERROR = (
"Only one experiment can be specified for the PAIR attack. Received "
"{num_experiments} experiments."
)
RESULTS_FILE_INDENT = 4
RESULTS_FILENAME = "{augmentation_name}.json"
SAVE_RESULTS_FILE_OPEN_MODE = "w"
LOOKUP_RESULTS_FILE_OPEN_MODE = "r"
DEFAULT_DEVICE = "cuda"
WARNINGS_LOGGER = "py.warnings"
LOGGER_FORMAT = (
"[%(levelname)s:%(filename)s:%(lineno)d] %(message)s"
)
WARNINGS_LOGGER_FORMAT = LOGGER_FORMAT
WARNINGS_FORMATTER_SPLIT_DELIMETER = ":"
WARNINGS_FORMATTER_SPLIT_MAXSPLIT = 3
WARNINGS_FORMATTER_FILENAME_SPLIT_DELIMETER = "/"
WARNINGS_FORMATTER_MESSAGE_SPLIT_DELIMETER = "warnings.warn("
class ComparisonType(StrEnum):
"""An enumeration of the types of comparisons that can be made."""
ELEMENTWISE = auto()
CARTESIAN = auto()
class AttackType(StrEnum):
"""An enumeration of the types of attacks that can be performed."""
STOCHASTIC_MONKEYS = auto()
PAIR = auto()
class WarningsFormatter(logging.Formatter):
"""A custom formatter for warnings."""
def format(
self,
record: logging.LogRecord,
):
"""Overrides the format method to apply custom formatting.
The filename, line number, and message are extracted from the record's
message in order to be used in the formatted message.
Args:
record: The log record to format.
"""
record_message_split = record.getMessage().split(
WARNINGS_FORMATTER_SPLIT_DELIMETER,
WARNINGS_FORMATTER_SPLIT_MAXSPLIT,
)
message_split = record_message_split[3].split(
WARNINGS_FORMATTER_MESSAGE_SPLIT_DELIMETER,
)
filename = record_message_split[0]
lineno = int(record_message_split[1])
message = "".join(
message_split[:-1]
).strip()
new_record = logging.LogRecord(
name=record.name,
level=record.levelno,
pathname=filename,
lineno=lineno,
msg=message,
args=record.args,
exc_info=record.exc_info,
)
return super().format(new_record)
def get_args() -> argparse.Namespace:
"""Returns the command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
"experiments",
help="Names of the experiments to run",
type=str,
nargs="+",
)
parser.add_argument(
"--experiment_config_path",
help="Path to the experiment configuration file",
type=str,
default="./config/experiments.toml",
)
parser.add_argument(
"--judge_config_path",
help="Path to the judge configuration file",
type=str,
default="./config/judges.toml",
)
parser.add_argument(
"--model_config_path",
help="Path to the model configuration file",
type=str,
default="./config/models.toml",
)
parser.add_argument(
"--results_dir",
help="Directory to save evaluation results",
type=str,
default="./results",
)
parser.add_argument(
"--log_path",
help="Path to the log file",
type=str,
default="./output.log",
)
parser.add_argument(
"--attack",
help="The type of attack to perform.",
type=str,
default=AttackType.STOCHASTIC_MONKEYS.value,
choices=[
attack.value for attack in AttackType
],
)
args = parser.parse_args()
return args
def get_logger(
log_path: str,
) -> logging.Logger:
"""Returns a logger for logging.
Args:
log_path: The path to the log file.
"""
logging.captureWarnings(True)
# Standard logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger_formatter = logging.Formatter(LOGGER_FORMAT)
logger_file_handler = logging.FileHandler(
log_path
)
logger_file_handler.setFormatter(logger_formatter)
logger.addHandler(logger_file_handler)
logger_stream_handler = logging.StreamHandler(sys.stdout)
logger_stream_handler.setFormatter(logger_formatter)
logger.addHandler(logger_stream_handler)
# Warnings logger
warnings_logger = logging.getLogger(WARNINGS_LOGGER)
warnings_logger_formatter = WarningsFormatter(WARNINGS_LOGGER_FORMAT)
warnings_logger_file_handler = logging.FileHandler(
log_path
)
warnings_logger_file_handler.setFormatter(warnings_logger_formatter)
warnings_logger.addHandler(warnings_logger_file_handler)
warnings_logger_stream_handler = logging.StreamHandler(sys.stdout)
warnings_logger_stream_handler.setFormatter(warnings_logger_formatter)
warnings_logger.addHandler(warnings_logger_stream_handler)
return logger
@ray.remote
def generate_outputs(
system_prompts: list,
prompts: list,
prompts_split: list,
output_samples: int,
greedy: bool,
temperature: float,
top_p: float,
model_alias: str,
model_config: Config,
judge: bool,
experiment_name: str,
experiment_config: dict,
chat_history: list = None,
prefill: str = "",
judge_alias: str = None,
compute_average_prompt_length: bool = True,
) -> dict:
"""Generates outputs from a model for the given prompts.
Args:
system_prompts: A list of system prompts to use for each prompt.
prompts: A list of the latest user prompts to generate outputs for.
prompts_split: A list of dictionaries describing how prompts is split.
Each dictionary contains the following keys:
- start: The starting index of the split.
- augmentation_name: The name of the augmentation.
- num_prompts: The number of base prompts in the split.
- augs_per_prompt: The number of augmentations per prompt.
output_samples: The number of output samples to generate per prompt.
greedy: Whether to use greedy decoding.
temperature: The temperature to use for sampling.
top_p: The top-p value to use for sampling.
prefill: A prefill string for the assistant response.
model_alias: The alias for the model being evaluated.
model_config: The configuration for the model to load.
judge: Whether the model is a judge model.
experiment_name: The name of the experiment.
experiment_config: The configuration for the experiment.
chat_history: The chat history so far preceding the user prompts
specified in the prompts argument.
judge_alias: The alias for the judge model, if the model is a judge.
compute_average_prompt_length: Whether to compute the average prompt
length.
Returns:
A dictionary containing the following keys:
- experiment_name: The name of the experiment.
- model_alias: The alias of the model.
- prompts_split: Passed from the prompts_split argument.
- outputs: The generated outputs.
"""
model = load_model(
name_or_path=model_config.name_or_path,
api=model_config.api,
**(model_config.model_kwargs),
)
tokenizer = load_tokenizer(
model_name_or_path=model_config.name_or_path,
**(model_config.tokenizer_kwargs),
)
apply_chat_template = model_config.apply_chat_template if judge else True
if chat_history is None:
chat_history = [[] for _ in range(len(prompts))]
inputs = get_generation_inputs(
system_prompts=system_prompts,
chat_history=chat_history,
prompts=prompts,
prefill=prefill,
tokenizer=tokenizer,
api=model_config.api,
apply_chat_template=apply_chat_template,
)
average_prompt_lengths = {}
if not judge and compute_average_prompt_length:
# Compute average prompt lengths
for split in prompts_split:
start = split["start"]
augmentation_name = split["augmentation_name"]
num_prompts = split["num_prompts"]
augs_per_prompt = split["augs_per_prompt"]
input_length_chars = []
input_length_tokens = []
average_input_length_chars = None
average_input_length_tokens = None
for i in range(num_prompts):
inputs_start = start + i * augs_per_prompt
inputs_end = inputs_start + augs_per_prompt
chars = prompts[inputs_start:inputs_end]
tokens = inputs[inputs_start:inputs_end]
input_length_chars.extend([len(prompt) for prompt in chars])
input_length_tokens.extend([len(prompt) for prompt in tokens])
if len(input_length_chars) > 0:
average_input_length_chars = sum(input_length_chars) / \
len(input_length_chars)
if len(input_length_tokens) > 0:
average_input_length_tokens = sum(input_length_tokens) / \
len(input_length_tokens)
average_prompt_lengths[augmentation_name] = {
"chars": average_input_length_chars,
"tokens": average_input_length_tokens,
}
max_new_tokens = experiment_config.judge_max_new_tokens if judge else \
experiment_config.max_new_tokens
outputs = get_generation_outputs(
model=model,
tokenizer=tokenizer,
inputs=inputs,
output_samples=output_samples,
max_new_tokens=max_new_tokens,
greedy=greedy,
temperature=temperature,
top_p=top_p,
random_seed=experiment_config.seed,
vllm_use_tqdm=experiment_config.vllm_use_tqdm,
)
results = {
"loaded": False,
"experiment_name": experiment_name,
"model_alias": model_alias,
"prompts_split": prompts_split,
"prompts": prompts,
"outputs": outputs,
}
if judge:
results["judge_alias"] = judge_alias
elif compute_average_prompt_length:
results["average_prompt_lengths"] = average_prompt_lengths
return results
@ray.remote
def generate_outputs_openai(
prompts: list,
prompts_split: list,
model_alias: str,
model_config: Config,
experiment_name: str,
experiment_config: dict,
results_dir: str,
) -> dict:
"""Generates outputs from an OpenAI model for the given prompts.
Args:
prompts: A list of prompts to generate outputs for.
prompts_split: A list of dictionaries describing how prompts is split.
Each dictionary contains the following keys:
- start: The starting index of the split.
- augmentation_name: The name of the augmentation.
- num_prompts: The number of base prompts in the split.
- augs_per_prompt: The number of augmentations per prompt.
model_alias: The alias for the model being evaluated.
model_config: The configuration for the model to load.
experiment_name: The name of the experiment.
experiment_config: The configuration for the experiment.
results_dir: The directory to save results to. Used to save the input
file.
logger: The logger to use for logging.
Returns:
A dictionary containing the following keys:
- experiment_name: The name of the experiment.
- model_alias: The alias of the model.
- prompts_split: Passed from the prompts_split argument.
- outputs: The generated outputs.
"""
client = OpenAI(
api_key=os.environ[model_config.api_key_location]
)
input_file_name = create_openai_input_file(
model_name=model_config.name_or_path,
prompts=prompts,
results_dir=results_dir,
experiment_name=experiment_name,
experiment_config=experiment_config,
model_alias=model_alias,
)
# Upload input file
batch_input_file = client.files.create(
file=open(input_file_name, "rb"),
purpose="batch",
)
# Submit request for outputs
request = client.batches.create(
input_file_id=batch_input_file.id,
endpoint="/v1/chat/completions",
completion_window="24h",
metadata={
"description": \
f"llm-randomness-eval[{experiment_name}:{model_alias}]",
}
)
status = ""
# Wait for request to complete
while status != "completed":
status = client.batches.retrieve(request.id).status
if status == "failed":
raise Exception(
OPENAI_REQUEST_FAILED.format(
experiment_name=experiment_name,
model_alias=model_alias,
)
)
elif status == "expired":
raise Exception(
OPENAI_REQUEST_EXPIRED.format(
experiment_name=experiment_name,
model_alias=model_alias,
)
)
elif status == "cancelled":
raise Exception(
OPENAI_REQUEST_CANCELLED.format(
experiment_name=experiment_name,
model_alias=model_alias,
)
)
time.sleep(60)
# Retrieve results
file_response = client.files.content(
client.batches.retrieve(request.id).output_file_id
)
# Parse results
response_split = file_response.text.split(
OPENAI_FILE_RESPONSE_DELIMETER
)[:-1]
outputs = [None] * len(prompts)
for line in response_split:
prompt_id = int(json.loads(line)["custom_id"])
line_results = json.loads(line).get(
"response",
{},
).get(
"body",
{},
).get(
"choices",
[],
)[0].get(
"message",
{},
).get(
"content",
"",
)
outputs[prompt_id] = [line_results]
results = {
"loaded": False,
"experiment_name": experiment_name,
"model_alias": model_alias,
"prompts_split": prompts_split,
"prompts": prompts,
"outputs": outputs,
}
return results
def get_score(
output: str,
zero_label: str,
one_label: str,
) -> int | None:
"""Returns a score extracted from a judgment model output.
If the output does not match the zero or one label, None is returned.
Args:
output: The output to extract the score from.
zero_label: The label for a score of 0.
one_label: The label for a score of 1.
Returns:
The extracted score, or None if the output does not match the zero or
one label.
"""
output = output.strip().lower()
score = None
if output[:len(zero_label)] == zero_label.lower():
score = 0
elif output[:len(one_label)] == one_label.lower():
score = 1
return score
def get_augmentation_unique_name(
augmentation_config: Config,
output_samples: int,
) -> str:
"""Returns a unique ID for an augmentation.
Returns an ID that combines the augmentation name and its keyword arguments.
Args:
augmentation_config: The augmentation configuration.
output_samples: The number of output samples per prompt.
"""
def dict_to_str(
d: dict,
) -> str:
"""Returns a string representation of a dictionary.
Args:
d: The dictionary to convert to a string.
"""
str_representation = ""
for key, value in d.items():
if value is None:
continue
if isinstance(value, dict) and len(value) > 0:
value = dict_to_str(value)
else:
value = str(value)
str_representation += \
AUGMENTATION_UNIQUE_NAME_KEY_VALUE_PAIR.format(
key=key,
value=value,
)
return str_representation
unique_key = \
augmentation_config.name + \
dict_to_str(
augmentation_config.kwargs,
) + \
AUGMENTATION_UNIQUE_NAME_SUFFIX.format(
samples=str(
max(
augmentation_config.augmentation_samples,
output_samples,
)
),
)
for old, new in AUGMENTATION_UNIQUE_NAME_VALUE_REPLACEMENTS:
unique_key = unique_key.replace(old, new)
return unique_key
def safe_load_comparisons_config(
config_dict: dict,
config_idx: int,
experiment_name: str,
logger: logging.Logger,
) -> Config | None:
"""Safely loads a comparison configuration.
If an error occurs when loading the configuration, the error message is
logged and None is returned.
Args:
config_dict: The dictionary containing the configuration.
config_idx: The index of the configuration in the experiment
configuration.
experiment_name: The name of the current experiment.
logger: The logger to use for logging.
Returns:
The loaded comparison configuration, or None if an error occurred.
"""
comparison_config = None
try:
comparison_config = load_comparisons_config(
name=COMPARISONS_NAME.format(
experiment_name=experiment_name,
i=config_idx,
),
config_dict=config_dict,
)
except Exception as message:
logger.error(
EXPERIMENT_MESSAGE_PREFIX.format(
experiment_name=experiment_name,
) +
ERROR_MESSAGE.format(
message=message,
)
)
return comparison_config
def safe_load_experiment_config(
experiment_name: str,
config_path: str,
logger: logging.Logger,
log_config: bool = False,
) -> Config | None:
"""Safely loads an experiment configuration.
If an error occurs when loading the configuration, the error message is
logged and None is returned.
Args:
name: The name of the experiment.
config_path: The path to the experiment configuration file.
logger: The logger to use for logging.
log_config: Whether to log the configuration after loading.
Returns:
The loaded experiment configuration, or None if an error occurred.
"""
experiment_config = None
try:
experiment_config = load_experiment_config(
name=experiment_name,
config_path=config_path,
)
except Exception as message:
logger.error(
LOAD_EXPERIMENT_CONFIG_ERROR.format(
name=experiment_name,
config_path=config_path,
message=message,
)
)
if log_config and experiment_config is not None:
# Output experiment configuration
logger.info(
EXPERIMENT_CONFIG_MESSAGE.format(
experiment_name=experiment_name,
config=str(experiment_config),
)
)
return experiment_config
def safe_load_judge_config(
judge_alias: str,
config_path: str,
cache: dict,
experiment_name: str,
logger: logging.Logger,
log_config: bool = False,
) -> Config | None:
"""Safely loads a judge configuration.
If an error occurs when loading the configuration, the error message is
logged and None is returned. If the judge name is already in the cache, the
cached configuration is returned. Otherwise, the configuration is loaded
and cached.
Args:
judge_alias: The alias of the judge model.
config_path: The path to the judge configuration file.
cache: A dictionary mapping judge names to their cached configurations.
experiment_name: The name of the current experiment.
logger: The logger to use for logging.
log_config: Whether to log the configuration after loading.
Returns:
The loaded judge configuration, or None if an error occurred.
"""
judge_config = None
try:
if judge_alias in cache:
# Use cached config if available
judge_config = cache[judge_alias]
if log_config:
logger.info(
JUDGE_CONFIG_PREVIOUSLY_LOADED_MESSAGE.format(
experiment_name=experiment_name,
judge_alias=judge_alias,
)
)
else:
judge_config = load_judge_config(
name=judge_alias,
config_path=config_path,
)
# Cache judge config
cache[judge_alias] = judge_config
if log_config:
# Output judge configuration
logger.info(
JUDGE_CONFIG_MESSAGE.format(
experiment_name=experiment_name,
judge_alias=judge_alias,
config=str(judge_config),
)
)
except Exception as message:
logger.error(
LOAD_JUDGE_ERROR.format(
experiment_name=experiment_name,
message=message,
)
)
return judge_config
def safe_load_dataset(
dataset_name: str,
dataset_path: str,
experiment_name: str,
logger: logging.Logger,
) -> Dataset | None:
"""Safely loads a dataset.
If an error occurs when loading the dataset, the error message is logged and
None is returned.
Args:
dataset_name: The name of the dataset.
dataset_path: The path to the dataset.
experiment_name: The name of the current experiment.
logger: The logger to use for logging.
Returns:
The loaded dataset, or None if an error occurred.
"""
dataset = None
try:
dataset_class = get_dataset_class(
dataset_name=dataset_name,
)
dataset = dataset_class(
dataset_path=dataset_path,
)
except Exception as message:
logger.error(
LOAD_DATASET_ERROR.format(
experiment_name=experiment_name,
message=message,
)
)
return dataset
def safe_load_augmentation(
config_dict: dict,
augmentation_index: int,
experiment_name: str,
logger: logging.Logger,
) -> tuple[Augmentation, Config] | None:
"""Safely loads an augmentation configuration.
If an error occurs when loading the configuration, the error message is
logged and None is returned.
Args:
config_dict: The dictionary containing the configuration.
augmentation_index: The index of the augmentation in the experiment
configuration.
experiment_name: The name of the current experiment.
logger: The logger to use for logging.
Returns:
The loaded augmentation and its configuration, or None if an error
occurred.
"""
loaded_augmentation = None
load_config_name = LOAD_AUGMENTATION_CONFIG_NAME.format(
experiment_name=experiment_name,
i=augmentation_index,
)