-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_survey.py
211 lines (170 loc) · 5.83 KB
/
run_survey.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
import argparse
import json
import os
from pathlib import Path
import typing
import numpy as np
from tqdm import tqdm
from lm_survey.samplers import AutoSampler
from lm_survey.survey import DependentVariableSample, Survey
def parse_model_name(model_name: str) -> str:
if model_name.startswith("/") and model_name.endswith("/"):
model_name = model_name.split("/")[-2]
elif model_name.startswith("/"):
model_name = model_name.split("/")[-1]
else:
model_name = model_name.replace("/", "-")
return model_name
def get_commit_hash():
commit_hash = os.popen("git rev-parse HEAD").read().strip()
return commit_hash
def save_experiment(
model_name: str,
experiment_dir: Path,
dependent_variable_samples: typing.List[DependentVariableSample],
prompt_name: str,
n_samples_per_dependent_variable: typing.Optional[int] = None,
):
parsed_model_name = parse_model_name(model_name)
results = [
question_sample.to_dict() for question_sample in dependent_variable_samples
]
metadata = {
"model_name": model_name,
"n_samples_per_dependent_variable": n_samples_per_dependent_variable,
"commit_hash": get_commit_hash(),
"prompt_name": prompt_name,
}
experiment_metadata_dir = experiment_dir / parsed_model_name
if not experiment_metadata_dir.exists():
experiment_metadata_dir.mkdir(parents=True)
with open(experiment_metadata_dir / "metadata.json", "w") as file:
json.dump(
metadata,
file,
indent=4,
)
with open(experiment_metadata_dir / "results.json", "w") as file:
json.dump(
results,
file,
indent=4,
)
def calculate_accuracy(
dependent_variable_samples: typing.List[DependentVariableSample],
) -> float:
scores = [
dependent_variable_sample.completion.is_completion_correct
for dependent_variable_sample in dependent_variable_samples
if dependent_variable_sample.completion.are_completion_log_probs_set()
]
return np.mean(scores)
def calculate_baseline(
dependent_variable_samples: typing.List[DependentVariableSample],
) -> float:
scores = [
1 / len(dependent_variable_sample.completion.possible_completions)
for dependent_variable_sample in dependent_variable_samples
if dependent_variable_sample.completion.are_completion_log_probs_set()
]
return np.mean(scores)
def main(
model_name: str,
survey_name: str,
experiment_name: str,
prompt_name: str,
n_samples_per_dependent_variable: typing.Optional[int] = None,
) -> None:
data_dir = Path("data", survey_name)
experiment_dir = Path("experiments", experiment_name, survey_name)
with open(Path(experiment_dir, "config.json"), "r") as file:
config = json.load(file)
# If there is a variables file in the experiment directory, use that.
variables_filename = experiment_dir / "variables.json"
# Otherwise, use the default variables file for the survey.
if not variables_filename.exists():
variables_filename = Path("variables", survey_name, "variables.json")
survey = Survey(
name=survey_name,
data_filename=Path(data_dir, "data.csv"),
variables_filename=variables_filename,
independent_variable_names=config["independent_variable_names"],
dependent_variable_names=config["dependent_variable_names"],
)
sampler = AutoSampler(model_name=model_name)
dependent_variable_samples = list(
survey.iterate(
n_samples_per_dependent_variable=n_samples_per_dependent_variable,
prompt_name=prompt_name,
)
)
loop = tqdm(dependent_variable_samples)
accuracy = 0.0
for dependent_variable_sample in loop:
completion_log_probs = sampler.rank_completions(
prompt=dependent_variable_sample.prompt,
completions=dependent_variable_sample.completion.possible_completions,
)
dependent_variable_sample.completion.set_completion_log_probs(
completion_log_probs
)
accuracy = calculate_accuracy(dependent_variable_samples)
baseline = calculate_baseline(dependent_variable_samples)
loop.set_description(
f"Accuracy: {accuracy * 100:.2f}%, Baseline: {baseline * 100:.2f}%"
)
print(
f"Accuracy: {accuracy * 100:.2f}% ({len(dependent_variable_samples)} samples)"
)
save_experiment(
model_name=model_name,
experiment_dir=experiment_dir,
dependent_variable_samples=dependent_variable_samples,
prompt_name=prompt_name,
n_samples_per_dependent_variable=n_samples_per_dependent_variable,
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-m",
"--model_name",
type=str,
required=True,
)
parser.add_argument(
"-s",
"--survey_name",
type=str,
default="roper",
)
parser.add_argument(
"-n",
"--n_samples_per_dependent_variable",
type=int,
)
parser.add_argument(
"-e",
"--experiment_name",
type=str,
default="default",
)
parser.add_argument(
"-p",
"--prompt_name",
type=str,
default="first_person_natural_language_context",
)
args = parser.parse_args()
# To prevent overbilling OpenAI.
if (
args.model_name.startswith("gpt3")
and args.n_samples_per_dependent_variable is None
):
args.n_samples_per_dependent_variable = 100
main(
model_name=args.model_name,
survey_name=args.survey_name,
experiment_name=args.experiment_name,
n_samples_per_dependent_variable=args.n_samples_per_dependent_variable,
prompt_name=args.prompt_name,
)