-
Notifications
You must be signed in to change notification settings - Fork 310
/
train_weak_to_strong.py
348 lines (325 loc) · 12 KB
/
train_weak_to_strong.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
import json
import os
from typing import Dict, List, Optional, Sequence, Union
import fire
import numpy as np
import torch
import weak_to_strong.logger as logger
from weak_to_strong.common import get_tokenizer
from weak_to_strong.datasets import (VALID_DATASETS, load_dataset,
tokenize_dataset)
from weak_to_strong.loss import logconf_loss_fn, product_loss_fn, xent_loss
from weak_to_strong.train import ModelConfig, train_and_save_model
# NOTE learning rates are not particularly tuned, work somewhat reasonably at train batch size 32
MODEL_CONFIGS = [
ModelConfig(
name="gpt2",
default_lr=5e-5,
eval_batch_size=32,
custom_kwargs={
"torch_dtype": torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32,
},
),
ModelConfig(
name="gpt2-medium",
default_lr=5e-5,
eval_batch_size=32,
custom_kwargs={
"torch_dtype": torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32,
},
),
ModelConfig(
name="gpt2-large",
default_lr=1e-5,
eval_batch_size=32,
custom_kwargs={
"torch_dtype": torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32,
},
),
ModelConfig(
name="gpt2-xl",
default_lr=1e-5,
eval_batch_size=2,
gradient_checkpointing=True,
model_parallel=True,
custom_kwargs={
"torch_dtype": torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32,
},
),
ModelConfig(
name="Qwen/Qwen-1_8B",
default_lr=1e-5,
eval_batch_size=2,
gradient_checkpointing=True,
model_parallel=True,
custom_kwargs={
"trust_remote_code": True,
"torch_dtype": torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32,
},
),
ModelConfig(
name="Qwen/Qwen-7B",
default_lr=1e-5,
eval_batch_size=2,
gradient_checkpointing=True,
model_parallel=True,
# note: you will probably not be able to run this without many gpus
custom_kwargs={
"trust_remote_code": True,
"torch_dtype": torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32,
},
),
ModelConfig(
name="Qwen/Qwen-14B",
default_lr=1e-5,
eval_batch_size=2,
gradient_checkpointing=True,
model_parallel=True,
# note: you will probably not be able to run this without bf16 support and many gpus
custom_kwargs={
"trust_remote_code": True,
"torch_dtype": torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32,
},
),
ModelConfig(
name="Qwen/Qwen-72B",
default_lr=1e-5,
eval_batch_size=1,
gradient_checkpointing=True,
model_parallel=True,
# note: you will probably not be able to run this without bf16 support and many gpus
custom_kwargs={
"trust_remote_code": True,
"torch_dtype": torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32,
},
# This model is really big, save space by using adafactor.
# Note that even then it will take up ~60GB per GPU on an 8-GPU machine.
default_optimizer="adafactor",
),
]
MODELS_DICT: Dict[str, ModelConfig] = {
model_config.name: model_config for model_config in MODEL_CONFIGS
}
loss_dict = {
"logconf": logconf_loss_fn(),
"product": product_loss_fn(),
"xent": xent_loss(),
}
VALID_LOSSES: List[str] = list(loss_dict.keys())
def main(
batch_size: int = 32,
max_ctx: int = 1024,
ds_name: str = "sciq",
transfer_loss: Union[str, Sequence[str]] = "xent,logconf",
n_docs: int = 10000,
n_test_docs: int = 200,
weak_model_size: str = "gpt2",
weak_lr: Optional[float] = None,
strong_model_size: str = "gpt2-xl",
strong_lr: Optional[float] = None,
# Defaults to strong_lr
transfer_lr: Optional[float] = None,
# Optims default to default_optimizer in the model definitions
weak_optim: Optional[str] = None,
strong_optim: Optional[str] = None,
transfer_optim: Optional[str] = None,
gt_epochs: int = 2,
# defaults to gt_epochs
transfer_epochs: Optional[int] = None,
force_retrain: bool = False,
seed: int = 0,
minibatch_size_per_device: Optional[int] = None,
train_with_dropout: bool = False,
results_folder: str = "/tmp/results",
linear_probe: bool = False,
lr_schedule: str = "cosine_anneal",
log_prefix: str = "",
# Set to an absurdly high value so we don't do intermediate evals by default.
eval_every: int = 100000000,
):
# this is per device!
if minibatch_size_per_device is None:
minibatch_size_per_device = 1
assert ds_name in VALID_DATASETS, f"Unknown dataset {ds_name} not in {VALID_DATASETS}"
if isinstance(transfer_loss, str):
transfer_losses = transfer_loss.split(",")
else:
transfer_losses = transfer_loss
del transfer_loss
for tloss in transfer_losses:
assert tloss in VALID_LOSSES, f"Unknown loss {tloss} not in {VALID_LOSSES}"
assert (
weak_model_size in MODELS_DICT
), f"Unknown model size {weak_model_size} not in {MODELS_DICT}"
weak_model_config = MODELS_DICT[weak_model_size]
assert (
strong_model_size in MODELS_DICT
), f"Unknown model size {strong_model_size} not in {MODELS_DICT}"
strong_model_config = MODELS_DICT[strong_model_size]
if weak_lr is None:
assert batch_size == 32
weak_lr = weak_model_config.default_lr
if strong_lr is None:
assert batch_size == 32
strong_lr = strong_model_config.default_lr
if transfer_lr is None:
transfer_lr = strong_lr
if transfer_epochs is None:
transfer_epochs = gt_epochs
if weak_optim is None:
weak_optim = weak_model_config.default_optimizer
if strong_optim is None:
strong_optim = strong_model_config.default_optimizer
if transfer_optim is None:
transfer_optim = strong_optim
weak_eval_batch_size = weak_model_config.eval_batch_size
strong_eval_batch_size = strong_model_config.eval_batch_size
# Load dataset
dataset = load_dataset(ds_name, seed=seed, split_sizes=dict(train=n_docs, test=n_test_docs))
# Split the training dataset in half
train_dataset, test_ds = dataset["train"], dataset["test"]
split_data = train_dataset.train_test_split(test_size=0.5, seed=seed)
train1_ds, train2_ds = split_data["train"], split_data["test"]
print("len(train1):", len(train1_ds), "len(train2):", len(train2_ds))
def train_model(
model_config: ModelConfig,
train_ds: torch.utils.data.Dataset,
test_ds: torch.utils.data.Dataset,
*,
loss_type: str,
label: str,
subpath,
lr,
eval_batch_size,
epochs=1,
inference_ds: Optional[torch.utils.data.Dataset] = None,
linear_probe: bool = False,
optimizer_name: str = "adam",
):
save_path = os.path.join(results_folder, subpath)
linprobe_str = "_linprobe" if linear_probe else ""
logger.configure(
name="{log_prefix}{label}_{base_model_name}_{ds_name}_{loss_type}_{optimizer_name}_{lr}_{lr_schedule}{linprobe_str}_{datetime_now}",
label=label,
ds_name=ds_name,
truncation_max_len=n_docs or "none",
loss_type=loss_type,
lr=lr,
batch_size=batch_size,
eval_batch_size=eval_batch_size,
minibatch_size_per_device=minibatch_size_per_device,
save_path=save_path,
base_model_name=model_config.name,
epochs=epochs,
linprobe_str=linprobe_str,
lr_schedule=lr_schedule,
log_prefix=log_prefix,
optimizer_name=optimizer_name,
)
# Tokenize datasets
tokenizer = get_tokenizer(model_config.name)
train_ds = tokenize_dataset(train_ds, tokenizer, max_ctx)
test_ds = tokenize_dataset(test_ds, tokenizer, max_ctx)
if inference_ds:
inference_ds = tokenize_dataset(inference_ds, tokenizer, max_ctx)
loss_fn = loss_dict[loss_type]
return train_and_save_model(
model_config,
train_ds,
test_ds,
inference_ds=inference_ds,
batch_size=batch_size,
save_path=save_path,
loss_fn=loss_fn,
lr=lr,
epochs=epochs,
force_retrain=force_retrain,
eval_batch_size=eval_batch_size,
minibatch_size_per_device=minibatch_size_per_device,
train_with_dropout=train_with_dropout,
linear_probe=linear_probe,
lr_schedule=lr_schedule,
optimizer_name=optimizer_name,
eval_every=eval_every,
)
# Train the weak model on the first half of the training data
print(f"Training weak model, size {weak_model_size}")
weak_test_results, weak_ds = train_model(
weak_model_config,
train1_ds,
test_ds,
loss_type="xent",
label="weak",
subpath=os.path.join("weak_model_gt", weak_model_size.replace("/", "_")),
lr=weak_lr,
eval_batch_size=weak_eval_batch_size,
inference_ds=train2_ds,
epochs=gt_epochs,
linear_probe=linear_probe,
optimizer_name=weak_optim,
)
# Train the strong model on the second half of the training data
print(f"Training strong model, size {strong_model_size}")
strong_test_results, _ = train_model(
strong_model_config,
train2_ds,
test_ds,
loss_type="xent",
label="strong",
subpath=os.path.join("strong_model_gt", strong_model_size.replace("/", "_")),
lr=strong_lr,
eval_batch_size=strong_eval_batch_size,
epochs=gt_epochs,
linear_probe=linear_probe,
optimizer_name=strong_optim,
)
# Train the strong model on the second half of the training data with labels generated by the weak model
all_transfer_test_results = {}
for tloss in transfer_losses:
print(
f"Training transfer model, size {strong_model_size} on labels from {weak_model_size}, with loss {tloss}"
)
transfer_test_results, _ = train_model(
strong_model_config,
weak_ds,
test_ds,
loss_type=tloss,
label="weak2strong",
subpath=os.path.join(
"strong_model_transfer",
f"{weak_model_size.replace('/', '_')}_{strong_model_size.replace('/', '_')}_{tloss}",
),
lr=transfer_lr,
eval_batch_size=strong_eval_batch_size,
epochs=transfer_epochs,
linear_probe=linear_probe,
optimizer_name=transfer_optim,
)
all_transfer_test_results[tloss] = transfer_test_results
del transfer_test_results
weak_acc = np.mean([x["acc"] for x in weak_test_results])
strong_acc = np.mean([x["acc"] for x in strong_test_results])
res_dict = {
"weak_acc": weak_acc,
"strong_acc": strong_acc,
}
print("weak acc:", weak_acc)
print("strong acc:", strong_acc)
for tloss, transfer_test_results in all_transfer_test_results.items():
transfer_acc = np.mean([x["acc"] for x in transfer_test_results])
res_dict[f"transfer_acc_{tloss}"] = transfer_acc
print(f"transfer acc ({tloss}):", transfer_acc)
with open(
os.path.join(
results_folder,
f"{weak_model_size.replace('/', '_')}_{strong_model_size.replace('/', '_')}.results_summary.json",
),
"w",
) as f:
json.dump(
res_dict,
f,
)
# python train_weak_to_strong.py --batch_size 32 --max_ctx 512 --ds_name "sciq" --transfer_loss "logconf" --n_docs 1000 --n_test_docs 100 --weak_model_size "gpt2-medium" --strong_model_size "gpt2-large" --seed 42
if __name__ == "__main__":
fire.Fire(main)