-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathtest_bco_trainer.py
More file actions
441 lines (357 loc) · 16.8 KB
/
test_bco_trainer.py
File metadata and controls
441 lines (357 loc) · 16.8 KB
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
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from functools import partial
import pytest
import torch
from accelerate import Accelerator
from datasets import load_dataset
from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer
from transformers.utils import is_peft_available
from trl.experimental.bco import BCOConfig, BCOTrainer
from trl.experimental.bco.bco_trainer import _process_tokens, _tokenize
from ..testing_utils import TrlTestCase, require_no_wandb, require_peft, require_sklearn
if is_peft_available():
from peft import LoraConfig
@pytest.mark.low_priority
class TestBCOTrainer(TrlTestCase):
@pytest.mark.parametrize(
"config_name",
[
"standard_preference",
"standard_implicit_prompt_preference",
"standard_unpaired_preference",
"conversational_preference",
"conversational_implicit_prompt_preference",
"conversational_unpaired_preference",
],
)
@require_sklearn
def test_train(self, config_name):
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
ref_model = AutoModelForCausalLM.from_pretrained(model_id)
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset("trl-internal-testing/zen", config_name, split="train")
training_args = BCOConfig(
output_dir=self.tmp_dir,
remove_unused_columns=False, # warning raised if not set to False
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
report_to="none",
)
trainer = BCOTrainer(
model=model,
ref_model=ref_model,
args=training_args,
processing_class=tokenizer,
train_dataset=dataset,
)
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
trainer.train()
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check that the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
if param.sum() != 0: # ignore 0 biases
assert not torch.equal(param.cpu(), new_param.cpu())
@require_sklearn
def test_train_with_precompute(self):
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
ref_model = AutoModelForCausalLM.from_pretrained(model_id)
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference", split="train")
training_args = BCOConfig(
output_dir=self.tmp_dir,
remove_unused_columns=False, # warning raised if not set to False
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
precompute_ref_log_probs=True,
report_to="none",
)
trainer = BCOTrainer(
model=model,
ref_model=ref_model,
args=training_args,
processing_class=tokenizer,
train_dataset=dataset,
)
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
trainer.train()
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check that the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
if param.sum() != 0: # ignore 0 biases
assert not torch.equal(param.cpu(), new_param.cpu())
@require_sklearn
def test_train_eval(self):
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
ref_model = AutoModelForCausalLM.from_pretrained(model_id)
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference")
training_args = BCOConfig(
output_dir=self.tmp_dir,
remove_unused_columns=False, # warning raised if not set to False
eval_strategy="steps",
eval_steps=3,
report_to="none",
)
trainer = BCOTrainer(
model=model,
ref_model=ref_model,
args=training_args,
processing_class=tokenizer,
train_dataset=dataset["train"],
eval_dataset=dataset["test"],
)
trainer.train()
@require_sklearn
def test_init_with_ref_model_is_model(self):
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference", split="train")
training_args = BCOConfig(
output_dir=self.tmp_dir,
remove_unused_columns=False, # warning raised if not set to False
report_to="none",
)
with pytest.raises(ValueError):
BCOTrainer(
model=model,
ref_model=model, # ref_model can't be the same as model
args=training_args,
processing_class=tokenizer,
train_dataset=dataset,
)
@require_sklearn
def test_tokenize_and_process_tokens(self):
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
ref_model = AutoModelForCausalLM.from_pretrained(model_id)
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference", split="train")
training_args = BCOConfig(
output_dir=self.tmp_dir,
remove_unused_columns=False, # warning raised if not set to False
report_to="none",
)
trainer = BCOTrainer(
model=model,
ref_model=ref_model,
args=training_args,
processing_class=tokenizer,
train_dataset=dataset,
)
tokenized_dataset = dataset.map(
_tokenize,
fn_kwargs={"tokenizer": trainer.processing_class},
batched=True,
batch_size=2,
)
assert tokenized_dataset["prompt"][:] == dataset["prompt"][:]
assert tokenized_dataset["completion"][:] == dataset["completion"][:]
assert tokenized_dataset["label"][:] == dataset["label"][:]
assert tokenized_dataset["prompt_input_ids"][0] == [46518, 374, 2664, 1091]
assert tokenized_dataset["prompt_attention_mask"][0] == [1, 1, 1, 1]
assert tokenized_dataset["answer_input_ids"][0] == [27261, 13]
assert tokenized_dataset["answer_attention_mask"][0] == [1, 1]
fn_kwargs = {
"prefix": "",
"is_encoder_decoder": trainer.is_encoder_decoder,
"tokenizer": trainer.processing_class,
"max_length": trainer.max_length,
}
processed_dataset = tokenized_dataset.map(_process_tokens, fn_kwargs=fn_kwargs)
assert processed_dataset["prompt"][:] == dataset["prompt"][:]
assert processed_dataset["completion"][:] == dataset["completion"][:]
assert processed_dataset["label"][:] == dataset["label"][:]
assert processed_dataset["prompt_input_ids"][0] == [46518, 374, 2664, 1091]
assert processed_dataset["prompt_attention_mask"][0] == [1, 1, 1, 1]
assert processed_dataset["completion_input_ids"][0] == [46518, 374, 2664, 1091, 27261, 13, 151645]
assert processed_dataset["completion_attention_mask"][0] == [1, 1, 1, 1, 1, 1, 1]
assert processed_dataset["completion_labels"][0] == [-100, -100, -100, -100, 27261, 13, 151645]
@require_sklearn
def test_train_without_providing_ref_model(self):
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference", split="train")
training_args = BCOConfig(
output_dir=self.tmp_dir,
remove_unused_columns=False, # warning raised if not set to False
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
report_to="none",
)
trainer = BCOTrainer(
model=model,
args=training_args,
processing_class=tokenizer,
train_dataset=dataset,
)
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
trainer.train()
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check that the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
if param.sum() != 0: # ignore 0 biases
assert not torch.equal(param.cpu(), new_param.cpu())
@require_sklearn
def test_train_udm(self):
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
tokenizer = AutoTokenizer.from_pretrained(model_id)
# Get embedding model
embedding_model_id = "trl-internal-testing/tiny-BartModel"
embedding_model = AutoModel.from_pretrained(embedding_model_id)
embedding_tokenizer = AutoTokenizer.from_pretrained(embedding_model_id)
def embed_prompt(input_ids, attention_mask, model):
outputs = model(input_ids=input_ids, attention_mask=attention_mask)
return outputs.last_hidden_state.mean(dim=1)
embedding_model = Accelerator().prepare_model(embedding_model)
embedding_func = partial(embed_prompt, model=embedding_model)
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference", split="train")
training_args = BCOConfig(
output_dir=self.tmp_dir,
remove_unused_columns=False, # warning raised if not set to False
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
report_to="none",
)
trainer = BCOTrainer(
model=model,
args=training_args,
processing_class=tokenizer,
train_dataset=dataset,
embedding_func=embedding_func,
embedding_tokenizer=embedding_tokenizer,
)
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
trainer.train()
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check that the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
if param.sum() != 0: # ignore 0 biases
assert not torch.equal(param.cpu(), new_param.cpu())
@require_sklearn
@require_peft
def test_train_without_providing_ref_model_with_lora(self):
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, task_type="CAUSAL_LM")
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference", split="train")
training_args = BCOConfig(
output_dir=self.tmp_dir,
remove_unused_columns=False, # warning raised if not set to False
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
report_to="none",
)
trainer = BCOTrainer(
model=model,
args=training_args,
processing_class=tokenizer,
train_dataset=dataset,
peft_config=lora_config,
)
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
trainer.train()
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check that the params have changed
for n, param in previous_trainable_params.items():
if "lora" in n:
new_param = trainer.model.get_parameter(n)
if param.sum() != 0: # ignore 0 biases
assert not torch.equal(param.cpu(), new_param.cpu())
@require_sklearn
@require_no_wandb
def test_generate_during_eval_no_wandb(self):
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference")
training_args = BCOConfig(
output_dir=self.tmp_dir,
remove_unused_columns=False, # warning raised if not set to False
eval_strategy="steps",
eval_steps=3,
generate_during_eval=True,
report_to="none",
)
with pytest.raises(
ValueError,
match="`generate_during_eval=True` requires Weights and Biases or Comet to be installed."
" Please install `wandb` or `comet-ml` to resolve.",
):
BCOTrainer(
model=model,
args=training_args,
processing_class=tokenizer,
train_dataset=dataset["train"],
eval_dataset=dataset["test"],
)
@require_sklearn
@require_peft
def test_lora_train_and_save(self):
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, task_type="CAUSAL_LM")
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference", split="train")
training_args = BCOConfig(
output_dir=self.tmp_dir,
remove_unused_columns=False, # warning raised if not set to False
report_to="none",
)
trainer = BCOTrainer(
model=model,
args=training_args,
processing_class=tokenizer,
train_dataset=dataset,
peft_config=lora_config,
)
# train the model
trainer.train()
# save peft adapter
trainer.save_model()
# assert that the model is loaded without giving OSError
AutoModelForCausalLM.from_pretrained(self.tmp_dir)
@require_sklearn
def test_compute_metrics(self):
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
ref_model = AutoModelForCausalLM.from_pretrained(model_id)
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference")
def dummy_compute_metrics(*args, **kwargs):
return {"test": 0.0}
training_args = BCOConfig(
output_dir=self.tmp_dir,
remove_unused_columns=False, # warning raised if not set to False
eval_strategy="steps",
eval_steps=3,
report_to="none",
)
trainer = BCOTrainer(
model=model,
ref_model=ref_model,
args=training_args,
processing_class=tokenizer,
train_dataset=dataset["train"],
eval_dataset=dataset["test"],
compute_metrics=dummy_compute_metrics,
)
trainer.train()
assert trainer.state.log_history[-2]["eval_test"] == 0.0