Master-Shi commited on
Commit
a573f47
·
verified ·
1 Parent(s): e37cb83

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/environment/__init__.py +3 -0
  2. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/environment/base_environment.py +463 -0
  3. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/extras/__init__.py +16 -0
  4. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/extras/best_of_n_sampler.py +113 -0
  5. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/extras/dataset_formatting.py +86 -0
  6. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/models/modeling_base.py +640 -0
  7. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/models/utils.py +83 -0
  8. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/__init__.py +46 -0
  9. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/base.py +46 -0
  10. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/ddpo_config.py +115 -0
  11. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/ddpo_trainer.py +604 -0
  12. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/dpo_trainer.py +1186 -0
  13. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/iterative_sft_trainer.py +334 -0
  14. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/model_config.py +71 -0
  15. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/ppo_config.py +175 -0
  16. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/ppo_trainer.py +1397 -0
  17. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/reward_config.py +38 -0
  18. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/reward_trainer.py +257 -0
  19. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/sft_trainer.py +480 -0
  20. 之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/utils.py +703 -0
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/environment/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ from .base_environment import TextEnvironment, TextHistory
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/environment/base_environment.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import re
16
+ import warnings
17
+
18
+ import torch
19
+ from accelerate.utils import extract_model_from_parallel
20
+ from transformers import StoppingCriteria, StoppingCriteriaList
21
+
22
+ from ..import_utils import is_rich_available
23
+
24
+
25
+ if is_rich_available():
26
+ from rich import print
27
+ from rich.text import Text
28
+
29
+
30
+ class StringStoppingCriteria(StoppingCriteria):
31
+ """Custom `StoppingCriteria` which checks if all generations in the batch are completed."""
32
+
33
+ def __init__(self, stop_strings, tokenizer):
34
+ self.stop_strings = stop_strings
35
+ self.tokenizer = tokenizer
36
+ self.first_call = True
37
+
38
+ def __call__(self, input_ids, scores, **kwargs):
39
+ """Returns true if all generated sequences contain any of the stop strings."""
40
+ if self.first_call:
41
+ self.generated_tokens = [1 for _ in range(input_ids.shape[0])]
42
+ self.start_length = input_ids.shape[-1] - 1
43
+ self.first_call = False
44
+ decoded_generations = self.tokenizer.batch_decode(input_ids[:, self.start_length :])
45
+ done = []
46
+
47
+ for i, decoded_generation in enumerate(decoded_generations):
48
+ sequence_complete = any([stop_string in decoded_generation for stop_string in self.stop_strings])
49
+ done.append(sequence_complete)
50
+ if not sequence_complete:
51
+ self.generated_tokens[i] += 1
52
+
53
+ if all(done):
54
+ self.first_call = True
55
+
56
+ return all(done)
57
+
58
+
59
+ class TextHistory:
60
+ """The TextHistory class keeps track of the history of an interaction between the language model and the environment."""
61
+
62
+ def __init__(self, text, tokens, system=True):
63
+ """
64
+ Initialize TextHistory.
65
+
66
+ args:
67
+ text (`str`): The text of the first segment.
68
+ tokens (`torch.LongTensor`): The tokens of the first segment.
69
+ system (`bool`, *optional*): Whether the first segment is a system or user segment.
70
+ """
71
+ self.system_spans = []
72
+ self.text_spans = []
73
+ self.token_spans = []
74
+ self.token_masks = torch.tensor([], dtype=torch.long).to(tokens.device)
75
+ self.text = ""
76
+ self.tokens = torch.tensor([], dtype=torch.long).to(tokens.device)
77
+ self.completed = False
78
+ self.truncated = False
79
+ self.reward = 0.0
80
+
81
+ self.prompt_color = "black on grey85"
82
+ self.system_color = "black on cyan3"
83
+ self.model_color = "black on deep_sky_blue1"
84
+ self.reward_color = "black on plum1"
85
+
86
+ self.append_segment(text, tokens, system=system)
87
+
88
+ def append_segment(self, text, tokens, system=True):
89
+ """
90
+ Append a new segment to the history.
91
+
92
+ args:
93
+ text (`str`): The text of the new segment.
94
+ tokens (`torch.LongTensor`): The tokens of the new segment.
95
+ system (`bool`, *optional*): Whether the new segment is a system or user segment.
96
+ """
97
+
98
+ if len(text) == 0 or len(tokens) == 0:
99
+ raise ValueError("Can't append empty text or token list to history.")
100
+
101
+ original_text_length = len(self.text)
102
+
103
+ self.text += text
104
+ self.text_spans.append((original_text_length, len(self.text)))
105
+ self.system_spans.append(system)
106
+
107
+ original_token_length = len(self.tokens)
108
+
109
+ self.tokens = torch.cat((self.tokens, tokens))
110
+ if system:
111
+ self.token_masks = torch.cat((self.token_masks, torch.zeros_like(tokens)))
112
+ else:
113
+ self.token_masks = torch.cat((self.token_masks, torch.ones_like(tokens)))
114
+ self.token_spans.append((original_token_length, len(self.tokens)))
115
+
116
+ def complete(self, truncated=False):
117
+ """
118
+ Mark the history as completed.
119
+ """
120
+ self.completed = True
121
+ self.truncated = truncated
122
+
123
+ @property
124
+ def last_text_segment(self):
125
+ """
126
+ Get the last text segment.
127
+ """
128
+ start, end = self.text_spans[-1]
129
+ return self.text[start:end]
130
+
131
+ def split_query_response_tokens(self):
132
+ """
133
+ Split the tokens into query and response tokens.
134
+ """
135
+ split_index = self.token_spans[0][1]
136
+ query = self.tokens[:split_index]
137
+ response = self.tokens[split_index:]
138
+ mask = self.token_masks[split_index:]
139
+
140
+ return query, response, mask
141
+
142
+ def show_text(self, show_legend=False):
143
+ """
144
+ Print the text history.
145
+ """
146
+ if not is_rich_available():
147
+ warnings.warn("install rich to display text")
148
+ return
149
+
150
+ text = Text(self.text)
151
+ text.stylize(self.prompt_color, self.text_spans[0][0], self.text_spans[1][0])
152
+ for i, (start, end) in enumerate(self.text_spans[1:]):
153
+ if self.system_spans[i + 1]:
154
+ text.stylize(self.system_color, start, end)
155
+ else:
156
+ text.stylize(self.model_color, start, end)
157
+
158
+ text.append(f"\n\nReward: {self.reward}", style=self.reward_color)
159
+ print(text)
160
+
161
+ if show_legend:
162
+ self.show_colour_legend()
163
+
164
+ def show_tokens(self, tokenizer, show_legend=False):
165
+ """
166
+ Print the history tokens.
167
+ """
168
+ if not is_rich_available():
169
+ warnings.warn("install rich to display tokens")
170
+ return
171
+
172
+ text = Text()
173
+ prompt_end = self.token_spans[0][1]
174
+ for i, (token, mask) in enumerate(zip(self.tokens, self.token_masks)):
175
+ if i < prompt_end:
176
+ text.append(tokenizer.convert_ids_to_tokens(token.item()), style=self.prompt_color)
177
+ text.append(" ")
178
+ elif mask == 0:
179
+ text.append(tokenizer.convert_ids_to_tokens(token.item()), style=self.system_color)
180
+ text.append(" ")
181
+ else:
182
+ text.append(tokenizer.convert_ids_to_tokens(token.item()), style=self.model_color)
183
+ text.append(" ")
184
+ text.append(f"\n\nReward: {self.reward}", style=self.reward_color)
185
+ print(text)
186
+ if show_legend:
187
+ self.show_colour_legend()
188
+
189
+ def show_colour_legend(self):
190
+ """
191
+ Print the colour legend.
192
+ """
193
+ if not is_rich_available():
194
+ warnings.warn("install rich to display colour legend")
195
+ return
196
+ text = Text("\n\n(Colour Legend: ")
197
+ text.append("Prompt", style=self.prompt_color)
198
+ text.append("|")
199
+ text.append("System", style=self.system_color)
200
+ text.append("|")
201
+ text.append("Model", style=self.model_color)
202
+ text.append("|")
203
+ text.append("Reward", style=self.reward_color)
204
+ text.append(")")
205
+ print(text)
206
+
207
+
208
+ class TextEnvironment:
209
+ """
210
+ The TextEnvironment enables interaction of a LLM with an environment using tools.
211
+ """
212
+
213
+ def __init__(
214
+ self,
215
+ model=None,
216
+ tokenizer=None,
217
+ tools=None,
218
+ reward_fn=None,
219
+ prompt=None,
220
+ max_turns=4,
221
+ max_tool_reponse=100,
222
+ max_length=None,
223
+ generation_kwargs=None,
224
+ ):
225
+ """
226
+ Initialize TextEnvironment.
227
+
228
+ Args:
229
+ model (`PreTrainedModelWrapper`): The model to use for generation.
230
+ tokenizer (`transformers.PreTrainedTokenizer`): The tokenizer to use for generation.
231
+ tools (list): A list of tools to use for interaction.
232
+ reward_fn (function): A function that takes a string and returns a reward.
233
+ prompt (str): The base prompt to use for generation. Is prepended to the tasks.
234
+ max_turns (Optional[int]): The maximum number of turns to allow.
235
+ max_tool_response (Optional[int]): The maximum number of characters to allow in a tool response.
236
+ max_length (Optional[int]): The maximum number of tokens to allow in an episode.
237
+ generation_kwargs (Optional[dict]): A dictionary of keyword arguments to pass to the model's generate method.
238
+ """
239
+ self.model = model
240
+ self.tokenizer = tokenizer
241
+ self.prompt = prompt
242
+ if isinstance(tools, dict):
243
+ self.tools = tools
244
+ else:
245
+ self.tools = dict([(tool.__class__.__name__, tool) for tool in tools])
246
+ self.reward_fn = reward_fn
247
+ self.max_length = max_length
248
+ self.request_token = "<request>"
249
+ self.call_token = "<call>"
250
+ self.response_token = "<response>"
251
+ self.submit_token = "<submit>"
252
+ self.max_turns = max_turns
253
+ self.max_tool_response = max_tool_reponse
254
+
255
+ if generation_kwargs is None:
256
+ self.generation_kwargs = dict()
257
+ else:
258
+ self.generation_kwargs = generation_kwargs
259
+
260
+ self.is_encoder_decoder = hasattr(self.model, "is_encoder_decoder")
261
+ self.current_device = extract_model_from_parallel(self.model).pretrained_model.device
262
+
263
+ def run(self, queries, **rewards_kwargs):
264
+ """
265
+ Run the environment on a list of queries.
266
+
267
+ Args:
268
+ queries (list[str]): A list of queries to run the model in the environment on.
269
+ """
270
+ turns = 0
271
+
272
+ queries = [self.prompt + task for task in queries]
273
+ queries_tokens = [self.tokenizer(query, return_tensors="pt").input_ids[0].to(self.model.pretrained_model.device) for query in queries]
274
+
275
+ histories = [TextHistory(q, qt, system=True) for q, qt in zip(queries, queries_tokens)]
276
+
277
+ while any([not history.completed for history in histories]) and turns < self.max_turns:
278
+ histories = self.generate(histories)
279
+ histories = self.tasks_end_check(histories)
280
+ # TODO: make this parallel rather than for-loop
281
+ for i in range(len(histories)):
282
+ histories[i] = self.step(histories[i])
283
+ histories = self.tasks_end_check(histories, model_turn=False)
284
+ turns += 1
285
+ self.compute_reward(histories, **rewards_kwargs)
286
+
287
+ # convert a list of (q, r, m) tuples to lists of all qs, rs, and ms respectively
288
+ queries, responses, masks = map(list, zip(*[history.split_query_response_tokens() for history in histories]))
289
+
290
+ rewards = [history.reward for history in histories]
291
+ return queries, responses, masks, rewards, histories
292
+
293
+ def step(self, history):
294
+ """
295
+ Step the environment forward one turn.
296
+
297
+ Args:
298
+ history (`TextHistory`): The history to step forward.
299
+ """
300
+ truncated, ended = self.task_end_check(history)
301
+ if ended:
302
+ history.complete(truncated=truncated)
303
+ if history.completed:
304
+ return history
305
+
306
+ tool, query = self.parse_tool_call(history.last_text_segment)
307
+ if tool is None or query is None:
308
+ response = f"Unknown tool call: {history.last_text_segment}"
309
+ else:
310
+ if tool not in self.tools:
311
+ response = f"Unknown tool {tool}."
312
+ try:
313
+ response = self.tools[tool](query)
314
+ except Exception as error:
315
+ response = f"Tool error: {str(error)}"
316
+
317
+ if len(response) > self.max_tool_response:
318
+ response = response[: (self.max_tool_response - 3)] + "..."
319
+
320
+ history.append_segment(
321
+ response + self.response_token,
322
+ self.tokenizer(response + self.response_token, return_tensors="pt").input_ids[0].to(self.model.pretrained_model.device),
323
+ system=True,
324
+ )
325
+
326
+ return history
327
+
328
+ def parse_tool_call(self, text):
329
+ """
330
+ Parse request string. Expected format: <request><tool_name>query<call>
331
+ """
332
+ result = re.search(f"(?<={self.request_token}).*?(?={self.call_token})", text, re.DOTALL)
333
+
334
+ # if we can't find a <request>/<call> span we return none
335
+ if result is None:
336
+ return None, None
337
+ else:
338
+ extracted_text = result.group()
339
+
340
+ result = re.search(r"<(.*?)>", extracted_text)
341
+
342
+ # if we can't find a tool name we return none
343
+ if result is None:
344
+ return None, None
345
+ else:
346
+ tool = result.group(1)
347
+
348
+ # split off the tool name
349
+ query = ">".join(extracted_text.split(">")[1:])
350
+
351
+ return tool, query
352
+
353
+ def compute_reward(self, histories, **reward_kwargs):
354
+ """
355
+ Compute the reward for a list of histories.
356
+ """
357
+ rewards = self.reward_fn([history.last_text_segment for history in histories], **reward_kwargs)
358
+ for history, reward in zip(histories, rewards):
359
+ history.reward = reward
360
+ return histories
361
+
362
+ def generate(self, histories):
363
+ """
364
+ Generate responses for a list of histories.
365
+ """
366
+ active_histories = [i for i, history in enumerate(histories) if not history.completed]
367
+
368
+ query_tensors = [histories[i].tokens for i in active_histories]
369
+ response_tensors = self._generate_batched(query_tensors)
370
+ response_texts = self.tokenizer.batch_decode(response_tensors)
371
+
372
+ for i, response_text, response_tensor in zip(active_histories, response_texts, response_tensors):
373
+ histories[i].append_segment(response_text, response_tensor, system=False)
374
+
375
+ return histories
376
+
377
+ def tasks_end_check(self, histories, model_turn=True):
378
+ """
379
+ Check if the current generation sequences have finished.
380
+ """
381
+ for history in histories:
382
+ if not history.completed:
383
+ truncated, ended = self.task_end_check(history, model_turn=model_turn)
384
+ if ended:
385
+ history.complete(truncated=truncated)
386
+ return histories
387
+
388
+ def task_end_check(self, history, model_turn=True):
389
+ """
390
+ Check if the current generation sequence has finished.
391
+ """
392
+ truncated = False
393
+ ended = False
394
+ if history.completed:
395
+ return truncated, ended
396
+ if self.max_length is not None and len(self.tokenizer(history.text).input_ids[0]) > self.max_length:
397
+ truncated = True
398
+ ended = True
399
+ elif self.tokenizer.eos_token in history.text:
400
+ ended = True
401
+ elif model_turn and not ((self.request_token in history.last_text_segment and self.call_token in history.last_text_segment) or self.submit_token in history.last_text_segment):
402
+ ended = True
403
+ elif self.submit_token in history.last_text_segment:
404
+ ended = True
405
+ return truncated, ended
406
+
407
+ def _generate_batched(
408
+ self,
409
+ query_tensors,
410
+ batch_size: int = 16,
411
+ pad_to_multiple_of: int = None,
412
+ ):
413
+ """
414
+ Generate responses for a list of query tensors.
415
+
416
+ args:
417
+ query_tensors (list[torch.Tensor]): A list of query tensors to generate responses for.
418
+ batch_size (int): The batch size to use for generation.
419
+ pad_to_multiple_of (int): The padding length to use for generation.
420
+ """
421
+ outputs = []
422
+ padding_side_default = self.tokenizer.padding_side
423
+ if not self.is_encoder_decoder:
424
+ self.tokenizer.padding_side = "left"
425
+
426
+ # in case we have fewer examples than bs
427
+ batch_size = min(len(query_tensors), batch_size)
428
+
429
+ for i in range(0, len(query_tensors), batch_size):
430
+ # prevent overflow if query tensors are not even multiple of bs
431
+ end_index = min(len(query_tensors), i + batch_size)
432
+
433
+ batch = query_tensors[i:end_index]
434
+ batch_mask = [torch.ones_like(element) for element in batch]
435
+ inputs = {"input_ids": batch, "attention_mask": batch_mask}
436
+
437
+ padded_inputs = self.tokenizer.pad(
438
+ inputs,
439
+ padding=True,
440
+ max_length=None,
441
+ pad_to_multiple_of=pad_to_multiple_of,
442
+ return_tensors="pt",
443
+ ).to(self.current_device)
444
+
445
+ stopping_criteria = StringStoppingCriteria([self.call_token, self.submit_token], self.tokenizer)
446
+
447
+ self.generation_kwargs["stopping_criteria"] = StoppingCriteriaList([stopping_criteria])
448
+
449
+ generations = extract_model_from_parallel(self.model).generate(**padded_inputs, **self.generation_kwargs)
450
+
451
+ for generation, mask, generated_tokens in zip(generations, padded_inputs["attention_mask"], stopping_criteria.generated_tokens):
452
+ if not self.is_encoder_decoder:
453
+ output = generation[(1 - mask).sum() :] # remove padding
454
+ else:
455
+ output = generation
456
+
457
+ if not self.is_encoder_decoder:
458
+ output = output[(mask).sum() :] # remove prompt
459
+
460
+ # remove chunk generated after stopping criteria in batch mode
461
+ outputs.append(output[:generated_tokens])
462
+ self.tokenizer.padding_side = padding_side_default
463
+ return outputs
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/extras/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ from .best_of_n_sampler import BestOfNSampler
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/extras/best_of_n_sampler.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, List, Optional, Union
2
+
3
+ import torch
4
+ from transformers import GenerationConfig, PreTrainedTokenizer, PreTrainedTokenizerFast
5
+
6
+ from ..core import set_seed
7
+ from ..models import SUPPORTED_ARCHITECTURES, PreTrainedModelWrapper
8
+
9
+
10
+ class BestOfNSampler(object):
11
+ def __init__(
12
+ self,
13
+ model: PreTrainedModelWrapper,
14
+ tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast],
15
+ queries_to_scores: Callable[[List[str]], List[float]],
16
+ length_sampler: Any,
17
+ sample_size: int = 4,
18
+ seed: Optional[int] = None,
19
+ n_candidates: int = 1,
20
+ generation_config: Optional[GenerationConfig] = None,
21
+ ) -> None:
22
+ r"""
23
+ Initialize the sampler for best-of-n generation
24
+
25
+ Args:
26
+ model (`PreTrainedModelWrapper`):
27
+ The pretrained model to use for generation
28
+ tokenizer (`PreTrainedTokenizer` or `PreTrainedTokenizerFast`):
29
+ Tokenizer associated with the pretrained model
30
+ queries_to_scores (`Callable[[List[str]], List[float]]`):
31
+ Callable that takes a list of generated texts and returns the associated reward scores
32
+ length_sampler (`Any`):
33
+ Sampler used to sample the length of the generated text
34
+ sample_size (`int`):
35
+ Number of samples to generate for each query
36
+ seed (`int`, *optional*):
37
+ Random seed used to control generation
38
+ n_candidates (`int`):
39
+ Number of candidates to return for each query
40
+ generation_config (`GenerationConfig`, *optional*):
41
+ Generation config passed to the underlying model's `generate` method.
42
+ See `GenerationConfig` (https://huggingface.co/docs/transformers/v4.29.1/en/main_classes/text_generation#transformers.GenerationConfig) for more details
43
+ """
44
+ if seed is not None:
45
+ set_seed(seed)
46
+
47
+ if not isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)):
48
+ raise ValueError(f"tokenizer must be a PreTrainedTokenizer or PreTrainedTokenizerFast, got {type(tokenizer)}")
49
+ if not isinstance(model, (SUPPORTED_ARCHITECTURES)):
50
+ raise ValueError(f"model must be a PreTrainedModelWrapper, got {type(model)} - supported architectures are: {SUPPORTED_ARCHITECTURES}")
51
+
52
+ self.model = model
53
+ self.tokenizer = tokenizer
54
+
55
+ self.queries_to_scores = queries_to_scores
56
+ self.length_sampler = length_sampler
57
+ self.gen_config = generation_config
58
+ self.sample_size = sample_size
59
+ self.n_candidates = n_candidates
60
+
61
+ def generate(
62
+ self,
63
+ tokenized_query: Union[List[int], torch.Tensor, List[torch.Tensor], List[List[int]]],
64
+ skip_special_tokens: bool = True,
65
+ device: Optional[Union[str, torch.device]] = None,
66
+ **generation_kwargs,
67
+ ) -> List[List[str]]:
68
+ r"""
69
+ Generate the best of n samples for input queries
70
+
71
+ Args:
72
+ tokenized_query (`List[int]` or `torch.Tensor` or `List[torch.Tensor]` or `List[int]`):
73
+ represents either a single tokenized query (a single tensor or a list of integers) or a batch of tokenized queries (a list of tensors or a list of lists of integers)
74
+ skip_special_tokens (`bool`):
75
+ Whether to remove the special tokens from the output
76
+ device (`str` or `torch.device`, *optional*):
77
+ The device on which the model will be loaded
78
+ **generation_kwargs (`dict`, *optional*):
79
+ Additional keyword arguments passed along to the underlying model's `generate` method.
80
+ This is used to override generation config
81
+
82
+ Returns:
83
+ List[List[str]]: A list of lists of generated texts
84
+ """
85
+ queries = None
86
+
87
+ if isinstance(tokenized_query, torch.Tensor) and tokenized_query.ndim == 1:
88
+ queries = tokenized_query.unsqueeze(0)
89
+ elif isinstance(tokenized_query, List):
90
+ element_type = type(tokenized_query[0])
91
+ if element_type == int:
92
+ queries = torch.tensor(tokenized_query).unsqueeze(0)
93
+ elif element_type == torch.Tensor:
94
+ queries = [tensor.reshape((1, -1)) for tensor in tokenized_query]
95
+ else:
96
+ queries = [torch.tensor(query).reshape((1, -1)) for query in tokenized_query]
97
+
98
+ result = []
99
+
100
+ for query in queries:
101
+ queries = query.repeat((self.sample_size, 1))
102
+ output = self.model.generate(
103
+ queries.to(device),
104
+ max_new_tokens=self.length_sampler(),
105
+ generation_config=self.gen_config,
106
+ **generation_kwargs,
107
+ ).squeeze()
108
+ output = self.tokenizer.batch_decode(output, skip_special_tokens=skip_special_tokens)
109
+ scores = torch.tensor(self.queries_to_scores(output))
110
+ output = [output[i] for i in scores.topk(self.n_candidates).indices]
111
+ result.append(output)
112
+
113
+ return result
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/extras/dataset_formatting.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Callable, Literal, Optional, Union
3
+
4
+ from datasets import Dataset, Value
5
+ from transformers import AutoTokenizer
6
+
7
+ from ..trainer.utils import ConstantLengthDataset
8
+
9
+
10
+ FORMAT_MAPPING = {
11
+ "chatml": [{"content": Value(dtype="string", id=None), "role": Value(dtype="string", id=None)}],
12
+ "instruction": {"completion": Value(dtype="string", id=None), "prompt": Value(dtype="string", id=None)},
13
+ }
14
+
15
+
16
+ def conversations_formatting_function(tokenizer: AutoTokenizer, messages_field: Literal["messages", "conversations"]):
17
+ r"""
18
+ return a callable function that takes in a "messages" dataset and returns a formatted dataset, based on the tokenizer
19
+ apply chat template to the dataset
20
+ """
21
+
22
+ def format_dataset(examples):
23
+ if isinstance(examples[messages_field][0], list):
24
+ output_texts = []
25
+ for i in range(len(examples[messages_field])):
26
+ output_texts.append(tokenizer.apply_chat_template(examples[messages_field][i], tokenize=False))
27
+ return output_texts
28
+ else:
29
+ return tokenizer.apply_chat_template(examples[messages_field], tokenize=False)
30
+
31
+ return format_dataset
32
+
33
+
34
+ def instructions_formatting_function(tokenizer: AutoTokenizer):
35
+ r"""
36
+ return a callable function that takes in an "instructions" dataset and returns a formatted dataset, based on the tokenizer
37
+ apply chat template to the dataset
38
+ """
39
+
40
+ def format_dataset(examples):
41
+ if isinstance(examples["prompt"], list):
42
+ output_texts = []
43
+ for i in range(len(examples["prompt"])):
44
+ converted_sample = [
45
+ {"role": "user", "content": examples["prompt"][i]},
46
+ {"role": "assistant", "content": examples["completion"][i]},
47
+ ]
48
+ output_texts.append(tokenizer.apply_chat_template(converted_sample, tokenize=False))
49
+ return output_texts
50
+ else:
51
+ converted_sample = [
52
+ {"role": "user", "content": examples["prompt"]},
53
+ {"role": "assistant", "content": examples["completion"]},
54
+ ]
55
+ return tokenizer.apply_chat_template(converted_sample, tokenize=False)
56
+
57
+ return format_dataset
58
+
59
+
60
+ def get_formatting_func_from_dataset(dataset: Union[Dataset, ConstantLengthDataset], tokenizer: AutoTokenizer) -> Optional[Callable]:
61
+ r"""
62
+ Finds the correct formatting function based on the dataset structure. Currently supported datasets are:
63
+ - `ChatML` with [{"role": str, "content": str}]
64
+ - `instruction` with [{"prompt": str, "completion": str}]
65
+
66
+ Args:
67
+ dataset (Dataset): User dataset
68
+ tokenizer (AutoTokenizer): Tokenizer used for formatting
69
+
70
+ Returns:
71
+ Callable: Formatting function if the dataset format is supported else None
72
+ """
73
+ if isinstance(dataset, Dataset):
74
+ if "messages" in dataset.features:
75
+ if dataset.features["messages"] == FORMAT_MAPPING["chatml"]:
76
+ logging.info("Formatting dataset with chatml format")
77
+ return conversations_formatting_function(tokenizer, "messages")
78
+ if "conversations" in dataset.features:
79
+ if dataset.features["conversations"] == FORMAT_MAPPING["chatml"]:
80
+ logging.info("Formatting dataset with chatml format")
81
+ return conversations_formatting_function(tokenizer, "conversations")
82
+ elif dataset.features == FORMAT_MAPPING["instruction"]:
83
+ logging.info("Formatting dataset with instruction format")
84
+ return instructions_formatting_function(tokenizer)
85
+
86
+ return None
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/models/modeling_base.py ADDED
@@ -0,0 +1,640 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import json
15
+ import logging
16
+ import os
17
+ from copy import deepcopy
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ from accelerate import PartialState
22
+ from huggingface_hub import hf_hub_download
23
+ from huggingface_hub.utils import (
24
+ EntryNotFoundError,
25
+ HFValidationError,
26
+ LocalEntryNotFoundError,
27
+ RepositoryNotFoundError,
28
+ )
29
+ from safetensors.torch import load_file as safe_load_file
30
+ from transformers import PreTrainedModel
31
+
32
+ from ..import_utils import is_npu_available, is_peft_available, is_transformers_greater_than, is_xpu_available
33
+
34
+
35
+ if is_peft_available():
36
+ from peft import (
37
+ PeftConfig,
38
+ PeftModel,
39
+ PeftModelForCausalLM,
40
+ PeftModelForSeq2SeqLM,
41
+ PromptLearningConfig,
42
+ get_peft_model,
43
+ prepare_model_for_kbit_training,
44
+ )
45
+
46
+ if is_transformers_greater_than("4.33.0"):
47
+ from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
48
+ else:
49
+ from transformers.deepspeed import is_deepspeed_zero3_enabled
50
+
51
+ LAYER_PATTERNS = [
52
+ "transformer.h.{layer}",
53
+ "model.decoder.layers.{layer}",
54
+ "gpt_neox.layers.{layer}",
55
+ "model.layers.{layer}",
56
+ ]
57
+
58
+
59
+ class PreTrainedModelWrapper(nn.Module):
60
+ r"""
61
+ A wrapper class around a (`transformers.PreTrainedModel`) to be compatible with the
62
+ (`~transformers.PreTrained`) class in order to keep some attributes and methods of the
63
+ (`~transformers.PreTrainedModel`) class.
64
+
65
+ Attributes:
66
+ pretrained_model: (`transformers.PreTrainedModel`)
67
+ The model to be wrapped.
68
+ parent_class: (`transformers.PreTrainedModel`)
69
+ The parent class of the model to be wrapped.
70
+ supported_args: (`list`)
71
+ The list of arguments that are supported by the wrapper class.
72
+ """
73
+
74
+ transformers_parent_class = None
75
+ supported_args = None
76
+ supported_modules = ("v_head",)
77
+ supported_rm_modules = ("score",)
78
+ supported_pretrained_model_architectures = (PreTrainedModel) if not is_peft_available() else (PreTrainedModel, PeftModelForCausalLM, PeftModelForSeq2SeqLM)
79
+
80
+ def __init__(self, pretrained_model=None, score_module=None, supports_rm_adapter=False, rm_adapter_name=None, **kwargs):
81
+ super().__init__()
82
+ self.pretrained_model = pretrained_model
83
+
84
+ self.config = pretrained_model.config
85
+ self.prepare_inputs_for_generation = pretrained_model.prepare_inputs_for_generation
86
+ self.is_loaded_in_8bit = getattr(pretrained_model, "is_loaded_in_8bit", False)
87
+ self.is_loaded_in_4bit = getattr(pretrained_model, "is_loaded_in_4bit", False)
88
+ self.is_sequential_parallel = False
89
+
90
+ if hasattr(pretrained_model, "gradient_checkpointing_disable"):
91
+ self.gradient_checkpointing_disable = pretrained_model.gradient_checkpointing_disable
92
+
93
+ if hasattr(pretrained_model, "gradient_checkpointing_enable"):
94
+ self.gradient_checkpointing_enable = pretrained_model.gradient_checkpointing_enable
95
+
96
+ self.supports_rm_adapter = supports_rm_adapter
97
+ self.rm_adapter_name = rm_adapter_name
98
+ self.policy_adapter_name = "default"
99
+ if score_module is not None:
100
+ self.score = score_module
101
+
102
+ @classmethod
103
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
104
+ r"""
105
+ Instantiates a new model from a pretrained model from `transformers`. The
106
+ pretrained model is loaded using the `from_pretrained` method of the
107
+ `transformers.PreTrainedModel` class. The arguments that are specific to the
108
+ `transformers.PreTrainedModel` class are passed along this method and filtered
109
+ out from the `kwargs` argument.
110
+
111
+
112
+ Args:
113
+ pretrained_model_name_or_path (`str` or `transformers.PreTrainedModel`):
114
+ The path to the pretrained model or its name.
115
+ *model_args (`list`, *optional*)):
116
+ Additional positional arguments passed along to the underlying model's
117
+ `from_pretrained` method.
118
+ **kwargs (`dict`, *optional*):
119
+ Additional keyword arguments passed along to the underlying model's
120
+ `from_pretrained` method. We also pre-process the kwargs to extract
121
+ the arguments that are specific to the `transformers.PreTrainedModel`
122
+ class and the arguments that are specific to trl models. The kwargs
123
+ also support `prepare_model_for_kbit_training` arguments from
124
+ `peft` library.
125
+ """
126
+ if kwargs is not None:
127
+ peft_config = kwargs.pop("peft_config", None)
128
+ reward_adapter = kwargs.pop("reward_adapter", None)
129
+ reward_adapter_name = kwargs.pop("reward_adapter_name", "reward_adapter")
130
+ is_trainable = kwargs.pop("is_trainable", False)
131
+ trl_model_args, pretrained_kwargs, peft_quantization_kwargs = cls._split_kwargs(kwargs)
132
+ token = pretrained_kwargs.get("token", None)
133
+ else:
134
+ peft_config = None
135
+ is_trainable = False
136
+ trl_model_args = {}
137
+ pretrained_kwargs = {}
138
+ peft_quantization_kwargs = {}
139
+ token = None
140
+
141
+ if reward_adapter is not None and not isinstance(reward_adapter, str):
142
+ raise ValueError("The `reward_adapter` argument should be a string representing the name of local path or the Hub id to the Reward Modeling adapter.")
143
+
144
+ is_peft_model = False
145
+
146
+ current_device = cls._get_current_device()
147
+ if isinstance(pretrained_model_name_or_path, str):
148
+ is_loaded_in_8bit = pretrained_kwargs["load_in_8bit"] if "load_in_8bit" in pretrained_kwargs else False
149
+ is_loaded_in_4bit = pretrained_kwargs["load_in_4bit"] if "load_in_4bit" in pretrained_kwargs else False
150
+ else:
151
+ is_loaded_in_8bit = getattr(pretrained_model_name_or_path, "is_loaded_in_8bit", False)
152
+ is_loaded_in_4bit = getattr(pretrained_model_name_or_path, "is_loaded_in_4bit", False)
153
+
154
+ if (is_loaded_in_8bit or is_loaded_in_4bit) and "device_map" not in pretrained_kwargs:
155
+ # warn users
156
+ logging.warning(
157
+ "The `device_map` argument is not provided. We will override the device_map argument."
158
+ " to set the entire"
159
+ " model on the current device. If you want to set the model on multiple devices, please provide"
160
+ " a custom `device_map` argument."
161
+ )
162
+ pretrained_kwargs["device_map"] = {"": current_device}
163
+
164
+ if is_peft_available() and peft_config is not None and not isinstance(peft_config, PeftConfig):
165
+ raise ValueError("The `peft_config` argument should be an instance of `peft.PeftConfig` class.")
166
+
167
+ # First, load the pre-trained model using the parent-class
168
+ # either `AutoModelForCausalLM` or `AutoModelForSeq2SeqLM`
169
+ if isinstance(pretrained_model_name_or_path, str):
170
+ if is_peft_available():
171
+ try:
172
+ # If there is a trained peft adapter in the hub, load its config.
173
+ remote_adapter_config = hf_hub_download(
174
+ pretrained_model_name_or_path,
175
+ "adapter_config.json",
176
+ token=token,
177
+ )
178
+ except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError):
179
+ remote_adapter_config = None
180
+ else:
181
+ remote_adapter_config = None
182
+
183
+ local_adapter_present = os.path.exists(os.path.join(pretrained_model_name_or_path, "adapter_config.json"))
184
+
185
+ if (local_adapter_present or remote_adapter_config is not None) and is_peft_available():
186
+ if peft_config is not None:
187
+ logging.warning("`peft_config` argument ignored since a peft config file was found in " f"{pretrained_model_name_or_path}")
188
+
189
+ # Load the trained peft adapter config
190
+ if local_adapter_present:
191
+ trained_adapter_config = PeftConfig.from_pretrained(pretrained_model_name_or_path)
192
+ else:
193
+ remote_adapter_dir = os.path.dirname(remote_adapter_config)
194
+ trained_adapter_config = PeftConfig.from_pretrained(remote_adapter_dir)
195
+
196
+ # Load the pretrained base model
197
+ pretrained_model = cls.transformers_parent_class.from_pretrained(trained_adapter_config.base_model_name_or_path, *model_args, **pretrained_kwargs)
198
+
199
+ # Wrap the pretrained model with the trained peft adapter
200
+ pretrained_model = PeftModel.from_pretrained(pretrained_model, pretrained_model_name_or_path, is_trainable=is_trainable)
201
+ logging.info("Trained peft adapter loaded")
202
+ else:
203
+ pretrained_model = cls.transformers_parent_class.from_pretrained(pretrained_model_name_or_path, *model_args, **pretrained_kwargs)
204
+
205
+ if peft_config is not None:
206
+ # Initialize a new peft adapter with the given config
207
+ if is_loaded_in_8bit or is_loaded_in_4bit:
208
+ pretrained_model = prepare_model_for_kbit_training(
209
+ pretrained_model,
210
+ **peft_quantization_kwargs,
211
+ )
212
+ pretrained_model = get_peft_model(pretrained_model, peft_config)
213
+ logging.info("peft adapter initialised")
214
+
215
+ elif isinstance(pretrained_model_name_or_path, cls.supported_pretrained_model_architectures):
216
+ pretrained_model = pretrained_model_name_or_path
217
+
218
+ if peft_config is not None and isinstance(pretrained_model, PreTrainedModel):
219
+ # Initialize a new peft adapter with the given config
220
+ if is_loaded_in_8bit or is_loaded_in_4bit:
221
+ pretrained_model = prepare_model_for_kbit_training(
222
+ pretrained_model,
223
+ **peft_quantization_kwargs,
224
+ )
225
+ pretrained_model = get_peft_model(pretrained_model, peft_config)
226
+ logging.info("peft adapter initialised")
227
+ else:
228
+ raise ValueError("pretrained_model_name_or_path should be a string or a PreTrainedModel, " f"but is {type(pretrained_model_name_or_path)}")
229
+
230
+ if is_peft_available():
231
+ if isinstance(pretrained_model, PeftModel):
232
+ is_peft_model = True
233
+ # for backward compatibility
234
+ if hasattr(pretrained_model, "active_peft_config") and isinstance(pretrained_model.active_peft_config, PromptLearningConfig):
235
+ raise ValueError("PromptLearningConfig is not supported for PPO training.")
236
+
237
+ # Add reward modeling adapter if specified
238
+ if not is_peft_model and reward_adapter is not None:
239
+ raise ValueError("reward_adapter can only be used with a PeftModel. ")
240
+ elif is_peft_model and reward_adapter is not None:
241
+ score_module = cls.add_and_load_reward_modeling_adapter(pretrained_model, reward_adapter, reward_adapter_name, token=token)
242
+ multi_adapter_args = {
243
+ "score_module": score_module,
244
+ "supports_rm_adapter": True,
245
+ "rm_adapter_name": reward_adapter_name,
246
+ }
247
+ else:
248
+ multi_adapter_args = {"supports_rm_adapter": False}
249
+
250
+ # Then, create the full model by instantiating the wrapper class
251
+ model = cls(pretrained_model, **multi_adapter_args, **trl_model_args)
252
+
253
+ # if resume_training, load the state_dict again - this is ok since the
254
+ # state_dict is removed from the model after loading it.
255
+ is_resuming_training = True
256
+ if isinstance(pretrained_model_name_or_path, str):
257
+ safe_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors")
258
+ filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin")
259
+
260
+ sharded_index_filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin.index.json")
261
+ safe_sharded_index_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors.index.json")
262
+ is_sharded = False
263
+ use_safe = os.path.exists(safe_filename)
264
+
265
+ if not (os.path.exists(filename) or os.path.exists(safe_filename)):
266
+ # Try with `pytorch_model.bin`
267
+ filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub(
268
+ pretrained_model,
269
+ pretrained_model_name_or_path,
270
+ sharded_index_filename,
271
+ token=token,
272
+ )
273
+ # Try with safetensors
274
+ if filename is None and files_to_download is None:
275
+ safe_filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub(
276
+ pretrained_model,
277
+ pretrained_model_name_or_path,
278
+ safe_sharded_index_filename,
279
+ token=token,
280
+ model_name="model.safetensors",
281
+ model_index_name="model.safetensors.index.json",
282
+ )
283
+ use_safe = True
284
+ else:
285
+ use_safe = False
286
+
287
+ loading_func = safe_load_file if use_safe else torch.load
288
+ load_kwargs = {} if use_safe else {"map_location": "cpu"}
289
+
290
+ if is_resuming_training:
291
+ if is_sharded:
292
+ # download each file and add it to the state_dict
293
+ state_dict = {}
294
+
295
+ for shard_file in files_to_download:
296
+ filename = hf_hub_download(
297
+ pretrained_model_name_or_path,
298
+ shard_file,
299
+ token=token,
300
+ )
301
+ state_dict.update(loading_func(filename, **load_kwargs))
302
+ else:
303
+ state_dict = loading_func(filename if not use_safe else safe_filename, **load_kwargs)
304
+
305
+ else:
306
+ state_dict = pretrained_model_name_or_path.state_dict()
307
+
308
+ model.is_peft_model = is_peft_model
309
+ model.current_device = current_device
310
+
311
+ if is_resuming_training:
312
+ model.post_init(state_dict=state_dict)
313
+
314
+ return model
315
+
316
+ @classmethod
317
+ def _get_checkpoint_from_hub(
318
+ cls,
319
+ pretrained_model,
320
+ pretrained_model_name_or_path,
321
+ index_filename,
322
+ token=None,
323
+ model_name="pytorch_model.bin",
324
+ model_index_name="pytorch_model.bin.index.json",
325
+ ):
326
+ files_to_download = None
327
+ filename = None
328
+ is_resuming_training = True
329
+ is_sharded = False
330
+
331
+ try:
332
+ filename = hf_hub_download(
333
+ pretrained_model_name_or_path,
334
+ model_name,
335
+ token=token,
336
+ )
337
+ # sharded
338
+ except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError):
339
+ if os.path.exists(index_filename):
340
+ index_file_name = index_filename
341
+ else:
342
+ try:
343
+ index_file_name = hf_hub_download(
344
+ pretrained_model_name_or_path,
345
+ model_index_name,
346
+ token=token,
347
+ )
348
+ except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError):
349
+ # not continue training, do not have v_head weight
350
+ is_resuming_training = False
351
+ logging.warning(f"A {type(pretrained_model)} model is loaded from '{pretrained_model_name_or_path}', " f"and no v_head weight is found. This IS expected if you are not resuming PPO training.")
352
+ # load json
353
+ if is_resuming_training:
354
+ with open(index_file_name, "r") as f:
355
+ index = json.load(f)
356
+ # check filename with `v_head` or any known extra module:
357
+ files_to_download = set()
358
+ for k, v in index["weight_map"].items():
359
+ if any([module in k for module in cls.supported_modules]):
360
+ files_to_download.add(v)
361
+ is_sharded = True
362
+
363
+ return filename, files_to_download, is_sharded, is_resuming_training
364
+
365
+ @classmethod
366
+ def _get_current_device(cls):
367
+ r"""
368
+ Get the current device. For GPU, we return the local process index using the `accelerate.PartialState`
369
+ object to handle corner cases when running scripts in distributed environments.
370
+
371
+ Returns:
372
+ current_device (`Union[int, str]`):
373
+ The current device.
374
+ """
375
+ state = PartialState()
376
+ if is_xpu_available():
377
+ return f"xpu:{state.local_process_index}"
378
+ elif is_npu_available():
379
+ return f"npu:{state.local_process_index}"
380
+ else:
381
+ return state.local_process_index if torch.cuda.is_available() else "cpu"
382
+
383
+ @classmethod
384
+ def _split_kwargs(cls, kwargs):
385
+ """
386
+ Separate the kwargs from the arguments that we support inside
387
+ `supported_args` and the ones that we don't.
388
+ """
389
+ check_peft_kwargs = False
390
+
391
+ if is_peft_available():
392
+ from peft import prepare_model_for_kbit_training
393
+
394
+ check_peft_kwargs = True
395
+
396
+ supported_kwargs = {}
397
+ unsupported_kwargs = {}
398
+ peft_kwargs = {}
399
+
400
+ for key, value in kwargs.items():
401
+ if key in cls.supported_args:
402
+ supported_kwargs[key] = value
403
+ else:
404
+ unsupported_kwargs[key] = value
405
+
406
+ if check_peft_kwargs:
407
+ if key in prepare_model_for_kbit_training.__code__.co_varnames:
408
+ peft_kwargs[key] = value
409
+ if key in unsupported_kwargs:
410
+ unsupported_kwargs.pop(key)
411
+
412
+ return supported_kwargs, unsupported_kwargs, peft_kwargs
413
+
414
+ @classmethod
415
+ def add_and_load_reward_modeling_adapter(cls, pretrained_model, adapter_model_id, adapter_name="reward_model_adapter", token=None):
416
+ r"""
417
+ Add and load a reward modeling adapter. This method can only be used if the
418
+ model is a `PeftModel` and if you have initialized the model with the `reward_modeling_adapter_id`
419
+ argument, pointing to the id of the reward modeling adapter. The latest needs also to contain the
420
+ score head in order to produce the reward.
421
+ """
422
+ pretrained_model.load_adapter(adapter_model_id, adapter_name, is_trainable=False)
423
+ pretrained_model.train()
424
+
425
+ filename = os.path.join(adapter_model_id, "adapter_model.bin")
426
+ safe_loading = False
427
+ if not os.path.exists(filename):
428
+ try:
429
+ local_filename = hf_hub_download(
430
+ adapter_model_id,
431
+ "adapter_model.bin",
432
+ token=token,
433
+ )
434
+ except: # noqa
435
+ filename = os.path.join(adapter_model_id, "adapter_model.safetensors")
436
+ safe_loading = True
437
+ if not os.path.exists(filename):
438
+ try:
439
+ local_filename = hf_hub_download(
440
+ adapter_model_id,
441
+ "adapter_model.safetensors",
442
+ token=token,
443
+ )
444
+ except: # noqa
445
+ raise ValueError("Could not find adapter model in the Hub, make sure you have the correct adapter model id.")
446
+ else:
447
+ local_filename = filename
448
+ else:
449
+ local_filename = filename
450
+
451
+ loading_func = safe_load_file if safe_loading else torch.load
452
+ load_kwargs = {} if safe_loading else {"map_location": "cpu"}
453
+
454
+ adapter_state_dict = loading_func(local_filename, **load_kwargs)
455
+
456
+ for score_name_candidate in cls.supported_rm_modules:
457
+ if any([score_name_candidate in name for name in adapter_state_dict.keys()]):
458
+ score_name = score_name_candidate
459
+ # we have found the correct head name and can break
460
+ break
461
+
462
+ score_dict = {}
463
+
464
+ for name, param in adapter_state_dict.items():
465
+ if score_name in name:
466
+ key_name = ".".join(name.split(".")[-1:])
467
+ score_dict[key_name] = param.to(cls._get_current_device())
468
+
469
+ num_labels, hidden_dim = score_dict["weight"].shape
470
+ has_bias = any(["bias" in name for name in adapter_state_dict.keys()])
471
+
472
+ score = nn.Linear(hidden_dim, num_labels, bias=has_bias).to(
473
+ device=cls._get_current_device(),
474
+ dtype=pretrained_model.dtype,
475
+ )
476
+ score.load_state_dict(score_dict)
477
+ for param in score.parameters():
478
+ param.requires_grad = False
479
+
480
+ return score
481
+
482
+ def push_to_hub(self, *args, **kwargs):
483
+ r"""
484
+ Push the pretrained model to the hub. This method is a wrapper around
485
+ `transformers.PreTrainedModel.push_to_hub`. Please refer to the documentation
486
+ of `transformers.PreTrainedModel.push_to_hub` for more information.
487
+
488
+ Args:
489
+ *args (`list`, *optional*):
490
+ Positional arguments passed along to the underlying model's
491
+ `push_to_hub` method.
492
+ **kwargs (`dict`, *optional*):
493
+ Keyword arguments passed along to the underlying model's
494
+ `push_to_hub` method.
495
+ """
496
+ raise NotImplementedError
497
+
498
+ def save_pretrained(self, *args, **kwargs):
499
+ r"""
500
+ Save the pretrained model to a directory. This method is a wrapper around
501
+ `transformers.PreTrainedModel.save_pretrained`. Please refer to the documentation
502
+ of `transformers.PreTrainedModel.save_pretrained` for more information.
503
+
504
+ Args:
505
+ *args (`list`, *optional*):
506
+ Positional arguments passed along to the underlying model's
507
+ `save_pretrained` method.
508
+ **kwargs (`dict`, *optional*):
509
+ Keyword arguments passed along to the underlying model's
510
+ `save_pretrained` method.
511
+ """
512
+ state_dict = kwargs.get("state_dict")
513
+ if state_dict is None:
514
+ state_dict = self.state_dict()
515
+ kwargs["state_dict"] = state_dict
516
+
517
+ # if it is a peft model only save the `v_head` state_dict and
518
+ # pop the `state_dict` from the kwargs to avoid slient bugs with `peft`
519
+ if self.is_peft_model:
520
+ save_path = args[0]
521
+ save_path = os.path.join(save_path, "pytorch_model.bin")
522
+ torch.save(state_dict, save_path)
523
+ _ = kwargs.pop("state_dict", None)
524
+
525
+ return self.pretrained_model.save_pretrained(*args, **kwargs)
526
+
527
+ def state_dict(self, *args, **kwargs):
528
+ r"""
529
+ Return the state_dict of the pretrained model.
530
+ """
531
+ raise NotImplementedError
532
+
533
+ def post_init(self, *args, **kwargs):
534
+ r"""
535
+ Post initialization method. This method is called after the model is
536
+ instantiated and loaded from a checkpoint. It can be used to perform
537
+ additional operations such as loading the state_dict.
538
+ """
539
+ raise NotImplementedError
540
+
541
+ def compute_reward_score(self, input_ids, attention_mask=None, **kwargs):
542
+ r"""
543
+ Computes the reward score for a given input. The method has first to enable the adapter
544
+ and then compute the reward score. After that the model disables the reward modeling
545
+ adapter and enables the default ppo adapter again.
546
+ """
547
+ if not self.supports_rm_adapter:
548
+ raise ValueError("This model does not support reward modeling adapter.")
549
+
550
+ # enable rm adapter
551
+ self.pretrained_model.set_adapter(self.rm_adapter_name)
552
+ self.pretrained_model.eval()
553
+
554
+ with torch.no_grad():
555
+ base_model_output = self.pretrained_model(
556
+ input_ids=input_ids,
557
+ attention_mask=attention_mask,
558
+ output_hidden_states=True,
559
+ return_dict=True,
560
+ **kwargs,
561
+ )
562
+
563
+ last_hidden_states = base_model_output.hidden_states[-1]
564
+ scores = self.score(last_hidden_states)
565
+
566
+ self.pretrained_model.set_adapter(self.policy_adapter_name)
567
+ self.pretrained_model.eval()
568
+
569
+ return scores
570
+
571
+
572
+ def create_reference_model(model: PreTrainedModelWrapper, num_shared_layers: int = None, pattern: str = None) -> PreTrainedModelWrapper:
573
+ """
574
+ Creates a static reference copy of a model. Note that model will be in `.eval()` mode.
575
+
576
+ Args:
577
+ model (`PreTrainedModelWrapper`): The model to be copied.
578
+ num_shared_layers (`int`, *optional*): The number of initial layers that are shared between both models and kept frozen.
579
+ pattern (`str`, *optional*): The shared layers are selected with a string pattern
580
+ (e.g. "transformer.h.{layer}" for GPT2) and if a custom pattern is necessary it can be passed here.
581
+
582
+ Returns
583
+ `PreTrainedModelWrapper`
584
+ """
585
+ if is_deepspeed_zero3_enabled():
586
+ raise ValueError("DeepSpeed ZeRO-3 is enabled and is not compatible with `create_reference_model()`. Please instantiate your reference model directly with `AutoCausalLM.from_pretrained()`.")
587
+
588
+ parameter_names = [n for n, _ in model.named_parameters()]
589
+ ref_model = deepcopy(model)
590
+
591
+ # if no layers are shared, return copy of model
592
+ if num_shared_layers is None:
593
+ for param_name in parameter_names:
594
+ param = ref_model.get_parameter(param_name)
595
+ param.requires_grad = False
596
+ return ref_model.eval()
597
+
598
+ # identify layer name pattern
599
+ if pattern is not None:
600
+ pattern = pattern.format(layer=num_shared_layers)
601
+ else:
602
+ for pattern_candidate in LAYER_PATTERNS:
603
+ pattern_candidate = pattern_candidate.format(layer=num_shared_layers)
604
+ if any([pattern_candidate in name for name in parameter_names]):
605
+ pattern = pattern_candidate
606
+ break
607
+
608
+ if pattern is None:
609
+ raise ValueError("Layer pattern could not be matched.")
610
+
611
+ # divide parameters in shared and unshared parameter lists
612
+ shared_param_list = []
613
+ unshared_param_list = []
614
+
615
+ shared_parameter = True
616
+ for name, param in model.named_parameters():
617
+ if pattern in name:
618
+ shared_parameter = False
619
+ if shared_parameter:
620
+ shared_param_list.append(name)
621
+ else:
622
+ unshared_param_list.append(name)
623
+
624
+ # create reference of the original parameter if they are shared
625
+ for param_name in shared_param_list:
626
+ param = model.get_parameter(param_name)
627
+ param.requires_grad = False
628
+
629
+ ref_param = ref_model.get_parameter(param_name) # noqa
630
+ ref_param = param # noqa
631
+
632
+ # for all other parameters just make sure they don't use gradients
633
+ for param_name in unshared_param_list:
634
+ param = ref_model.get_parameter(param_name)
635
+ param.requires_grad = False
636
+
637
+ if pattern is not None and len(unshared_param_list) == 0:
638
+ logging.warning("Pattern passed or found, but no layers matched in the model. Check for a typo.")
639
+
640
+ return ref_model.eval()
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/models/utils.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Literal, Optional, Tuple
3
+
4
+ from transformers import PreTrainedModel, PreTrainedTokenizer
5
+
6
+
7
+ # TODO: Add Abstract Base Class if more formats are added
8
+ @dataclass
9
+ class ChatMlSpecialTokens:
10
+ """Dataclass for special tokens used in ChatML, including system, user, assistant, bos, eos, and pad tokens."""
11
+
12
+ bos_token: str = "<|im_start|>"
13
+ eos_token: str = "<|im_end|>"
14
+ pad_token: str = "<|im_end|>"
15
+
16
+ @property
17
+ def system(self):
18
+ return f"{self.bos_token}system"
19
+
20
+ @property
21
+ def user(self):
22
+ return f"{self.bos_token}user"
23
+
24
+ @property
25
+ def assistant(self):
26
+ return f"{self.bos_token}assistant"
27
+
28
+ @property
29
+ def chat_template(self):
30
+ return (
31
+ "{% for message in messages %}"
32
+ f"{{{{'{self.bos_token}' + message['role'] + '\n' + message['content'] + '{self.eos_token}' + '\n'}}}}"
33
+ "{% endfor %}"
34
+ "{% if add_generation_prompt %}"
35
+ f"{{{{ '{self.assistant}\n' }}}}"
36
+ "{% endif %}"
37
+ )
38
+
39
+
40
+ FORMAT_MAPPING = {"chatml": ChatMlSpecialTokens}
41
+
42
+
43
+ def setup_chat_format(
44
+ model: PreTrainedModel,
45
+ tokenizer: PreTrainedTokenizer,
46
+ format: Optional[Literal["chatml"]] = "chatml",
47
+ resize_to_multiple_of: Optional[int] = None,
48
+ ) -> Tuple[PreTrainedModel, PreTrainedTokenizer]:
49
+ """
50
+ Setup chat format by adding special tokens to the tokenizer, setting the correct format, and extending the embedding layer of the model based on the new special tokens.
51
+
52
+ Args:
53
+ model (`~transformers.PreTrainedModel`): The model to be modified.
54
+ tokenizer (`~transformers.PreTrainedTokenizer`): The tokenizer to be modified.
55
+ format (`Optional[Literal["chatml"]]`): The format to be set. Defaults to "chatml".
56
+ resize_to_multiple_of (`Optional[int]`): Number to resize the embedding layer to. Defaults to None.
57
+ Returns:
58
+ model (`~transformers.PreTrainedModel`): The modified model.
59
+ tokenizer (`~transformers.PreTrainedTokenizer`): The modified tokenizer.
60
+ """
61
+ # check if format available and retrieve
62
+ if format not in FORMAT_MAPPING:
63
+ raise ValueError(f"Format {format} not available. Please use one of {FORMAT_MAPPING.keys()}")
64
+
65
+ chat_format = FORMAT_MAPPING[format]()
66
+
67
+ # set special tokens and them
68
+ tokenizer.eos_token = chat_format.eos_token
69
+ tokenizer.pad_token = chat_format.pad_token
70
+ tokenizer.bos_token = chat_format.bos_token
71
+ tokenizer.add_special_tokens({"additional_special_tokens": [chat_format.bos_token, chat_format.eos_token]})
72
+ # set chat format for tokenizer
73
+ tokenizer.chat_template = chat_format.chat_template
74
+
75
+ # resize embedding layer to a multiple of 64, https://x.com/karpathy/status/1621578354024677377
76
+ model.resize_token_embeddings(len(tokenizer), pad_to_multiple_of=resize_to_multiple_of if resize_to_multiple_of is not None else None)
77
+ # Make sure to update the generation config to use the new eos & bos token
78
+ if getattr(model, "generation_config", None) is not None:
79
+ model.generation_config.bos_token_id = tokenizer.bos_token_id
80
+ model.generation_config.eos_token_id = tokenizer.eos_token_id
81
+ model.generation_config.pad_token_id = tokenizer.pad_token_id
82
+
83
+ return model, tokenizer
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/__init__.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ # There is a circular import in the PPOTrainer if we let isort sort these
18
+ # isort: off
19
+ from .utils import (
20
+ AdaptiveKLController,
21
+ FixedKLController,
22
+ ConstantLengthDataset,
23
+ DataCollatorForCompletionOnlyLM,
24
+ RunningMoments,
25
+ disable_dropout_in_model,
26
+ peft_module_casting_to_bf16,
27
+ )
28
+
29
+ # isort: on
30
+
31
+ from ..import_utils import is_diffusers_available
32
+ from .base import BaseTrainer
33
+ from .ddpo_config import DDPOConfig
34
+
35
+
36
+ if is_diffusers_available():
37
+ from .ddpo_trainer import DDPOTrainer
38
+
39
+ from .dpo_trainer import DPOTrainer
40
+ from .iterative_sft_trainer import IterativeSFTTrainer
41
+ from .model_config import ModelConfig
42
+ from .ppo_config import PPOConfig
43
+ from .ppo_trainer import PPOTrainer
44
+ from .reward_config import RewardConfig
45
+ from .reward_trainer import RewardTrainer, compute_accuracy
46
+ from .sft_trainer import SFTTrainer
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/base.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from huggingface_hub import PyTorchModelHubMixin
16
+
17
+
18
+ class BaseTrainer(PyTorchModelHubMixin):
19
+ r"""
20
+ Base class for all trainers - this base class implements the basic functions that we
21
+ need for a trainer.
22
+
23
+ The trainer needs to have the following functions:
24
+ - step: takes in a batch of data and performs a step of training
25
+ - loss: takes in a batch of data and returns the loss
26
+ - compute_rewards: takes in a batch of data and returns the rewards
27
+ - _build_models_and_tokenizer: builds the models and tokenizer
28
+ - _build_dataset: builds the dataset
29
+ Each user is expected to implement their own trainer class that inherits from this base
30
+ if they want to use a new training algorithm.
31
+ """
32
+
33
+ def __init__(self, config):
34
+ self.config = config
35
+
36
+ def step(self, *args):
37
+ raise NotImplementedError("Not implemented")
38
+
39
+ def loss(self, *args):
40
+ raise NotImplementedError("Not implemented")
41
+
42
+ def compute_rewards(self, *args):
43
+ raise NotImplementedError("Not implemented")
44
+
45
+ def _save_pretrained(self, save_directory):
46
+ raise NotImplementedError("Not implemented")
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/ddpo_config.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import warnings
4
+ from dataclasses import dataclass, field
5
+ from typing import Literal, Optional
6
+
7
+ from ..core import flatten_dict
8
+ from ..import_utils import is_bitsandbytes_available, is_torchvision_available
9
+
10
+
11
+ @dataclass
12
+ class DDPOConfig:
13
+ """
14
+ Configuration class for DDPOTrainer
15
+ """
16
+
17
+ # common parameters
18
+ exp_name: str = os.path.basename(sys.argv[0])[: -len(".py")]
19
+ """the name of this experiment (by default is the file name without the extension name)"""
20
+ run_name: Optional[str] = ""
21
+ """Run name for wandb logging and checkpoint saving."""
22
+ seed: int = 0
23
+ """Seed value for random generations"""
24
+ log_with: Optional[Literal["wandb", "tensorboard"]] = None
25
+ """Log with either 'wandb' or 'tensorboard', check https://huggingface.co/docs/accelerate/usage_guides/tracking for more details"""
26
+ tracker_kwargs: dict = field(default_factory=dict)
27
+ """Keyword arguments for the tracker (e.g. wandb_project)"""
28
+ accelerator_kwargs: dict = field(default_factory=dict)
29
+ """Keyword arguments for the accelerator"""
30
+ project_kwargs: dict = field(default_factory=dict)
31
+ """Keyword arguments for the accelerator project config (e.g. `logging_dir`)"""
32
+ tracker_project_name: str = "trl"
33
+ """Name of project to use for tracking"""
34
+ logdir: str = "logs"
35
+ """Top-level logging directory for checkpoint saving."""
36
+
37
+ # hyperparameters
38
+ num_epochs: int = 100
39
+ """Number of epochs to train."""
40
+ save_freq: int = 1
41
+ """Number of epochs between saving model checkpoints."""
42
+ num_checkpoint_limit: int = 5
43
+ """Number of checkpoints to keep before overwriting old ones."""
44
+ mixed_precision: str = "fp16"
45
+ """Mixed precision training."""
46
+ allow_tf32: bool = True
47
+ """Allow tf32 on Ampere GPUs."""
48
+ resume_from: Optional[str] = ""
49
+ """Resume training from a checkpoint."""
50
+ sample_num_steps: int = 50
51
+ """Number of sampler inference steps."""
52
+ sample_eta: float = 1.0
53
+ """Eta parameter for the DDIM sampler."""
54
+ sample_guidance_scale: float = 5.0
55
+ """Classifier-free guidance weight."""
56
+ sample_batch_size: int = 1
57
+ """Batch size (per GPU!) to use for sampling."""
58
+ sample_num_batches_per_epoch: int = 2
59
+ """Number of batches to sample per epoch."""
60
+ train_batch_size: int = 1
61
+ """Batch size (per GPU!) to use for training."""
62
+ train_use_8bit_adam: bool = False
63
+ """Whether to use the 8bit Adam optimizer from bitsandbytes."""
64
+ train_learning_rate: float = 3e-4
65
+ """Learning rate."""
66
+ train_adam_beta1: float = 0.9
67
+ """Adam beta1."""
68
+ train_adam_beta2: float = 0.999
69
+ """Adam beta2."""
70
+ train_adam_weight_decay: float = 1e-4
71
+ """Adam weight decay."""
72
+ train_adam_epsilon: float = 1e-8
73
+ """Adam epsilon."""
74
+ train_gradient_accumulation_steps: int = 1
75
+ """Number of gradient accumulation steps."""
76
+ train_max_grad_norm: float = 1.0
77
+ """Maximum gradient norm for gradient clipping."""
78
+ train_num_inner_epochs: int = 1
79
+ """Number of inner epochs per outer epoch."""
80
+ train_cfg: bool = True
81
+ """Whether or not to use classifier-free guidance during training."""
82
+ train_adv_clip_max: float = 5
83
+ """Clip advantages to the range."""
84
+ train_clip_range: float = 1e-4
85
+ """The PPO clip range."""
86
+ train_timestep_fraction: float = 1.0
87
+ """The fraction of timesteps to train on."""
88
+ per_prompt_stat_tracking: bool = False
89
+ """Whether to track statistics for each prompt separately."""
90
+ per_prompt_stat_tracking_buffer_size: int = 16
91
+ """Number of reward values to store in the buffer for each prompt."""
92
+ per_prompt_stat_tracking_min_count: int = 16
93
+ """The minimum number of reward values to store in the buffer."""
94
+ async_reward_computation: bool = False
95
+ """Whether to compute rewards asynchronously."""
96
+ max_workers: int = 2
97
+ """The maximum number of workers to use for async reward computation."""
98
+ negative_prompts: Optional[str] = ""
99
+ """Comma-separated list of prompts to use as negative examples."""
100
+
101
+ def to_dict(self):
102
+ output_dict = {}
103
+ for key, value in self.__dict__.items():
104
+ output_dict[key] = value
105
+ return flatten_dict(output_dict)
106
+
107
+ def __post_init__(self):
108
+ if self.log_with not in ["wandb", "tensorboard"]:
109
+ warnings.warn(("Accelerator tracking only supports image logging if `log_with` is set to 'wandb' or 'tensorboard'."))
110
+
111
+ if self.log_with == "wandb" and not is_torchvision_available():
112
+ warnings.warn("Wandb image logging requires torchvision to be installed")
113
+
114
+ if self.train_use_8bit_adam and not is_bitsandbytes_available():
115
+ raise ImportError("You need to install bitsandbytes to use 8bit Adam. " "You can install it with `pip install bitsandbytes`.")
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/ddpo_trainer.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 DDPO-pytorch authors (Kevin Black), metric-space, The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import warnings
17
+ from collections import defaultdict
18
+ from concurrent import futures
19
+ from typing import Any, Callable, Optional, Tuple
20
+ from warnings import warn
21
+
22
+ import torch
23
+ from accelerate import Accelerator
24
+ from accelerate.logging import get_logger
25
+ from accelerate.utils import ProjectConfiguration, set_seed
26
+ from huggingface_hub import whoami
27
+
28
+ from ..models import DDPOStableDiffusionPipeline
29
+ from . import BaseTrainer, DDPOConfig
30
+ from .utils import PerPromptStatTracker
31
+
32
+
33
+ logger = get_logger(__name__)
34
+
35
+
36
+ MODEL_CARD_TEMPLATE = """---
37
+ license: apache-2.0
38
+ tags:
39
+ - trl
40
+ - ddpo
41
+ - diffusers
42
+ - reinforcement-learning
43
+ - text-to-image
44
+ - stable-diffusion
45
+ ---
46
+
47
+ # {model_name}
48
+
49
+ This is a diffusion model that has been fine-tuned with reinforcement learning to
50
+ guide the model outputs according to a value, function, or human feedback. The model can be used for image generation conditioned with text.
51
+
52
+ """
53
+
54
+
55
+ class DDPOTrainer(BaseTrainer):
56
+ """
57
+ The DDPOTrainer uses Deep Diffusion Policy Optimization to optimise diffusion models.
58
+ Note, this trainer is heavily inspired by the work here: https://github.com/kvablack/ddpo-pytorch
59
+ As of now only Stable Diffusion based pipelines are supported
60
+
61
+ Attributes:
62
+ **config** (`DDPOConfig`) -- Configuration object for DDPOTrainer. Check the documentation of `PPOConfig` for more
63
+ details.
64
+ **reward_function** (Callable[[torch.Tensor, Tuple[str], Tuple[Any]], torch.Tensor]) -- Reward function to be used
65
+ **prompt_function** (Callable[[], Tuple[str, Any]]) -- Function to generate prompts to guide model
66
+ **sd_pipeline** (`DDPOStableDiffusionPipeline`) -- Stable Diffusion pipeline to be used for training.
67
+ **image_samples_hook** (Optional[Callable[[Any, Any, Any], Any]]) -- Hook to be called to log images
68
+ """
69
+
70
+ _tag_names = ["trl", "ddpo"]
71
+
72
+ def __init__(
73
+ self,
74
+ config: DDPOConfig,
75
+ reward_function: Callable[[torch.Tensor, Tuple[str], Tuple[Any]], torch.Tensor],
76
+ prompt_function: Callable[[], Tuple[str, Any]],
77
+ sd_pipeline: DDPOStableDiffusionPipeline,
78
+ image_samples_hook: Optional[Callable[[Any, Any, Any], Any]] = None,
79
+ ):
80
+ if image_samples_hook is None:
81
+ warn("No image_samples_hook provided; no images will be logged")
82
+
83
+ self.prompt_fn = prompt_function
84
+ self.reward_fn = reward_function
85
+ self.config = config
86
+ self.image_samples_callback = image_samples_hook
87
+
88
+ accelerator_project_config = ProjectConfiguration(**self.config.project_kwargs)
89
+
90
+ if self.config.resume_from:
91
+ self.config.resume_from = os.path.normpath(os.path.expanduser(self.config.resume_from))
92
+ if "checkpoint_" not in os.path.basename(self.config.resume_from):
93
+ # get the most recent checkpoint in this directory
94
+ checkpoints = list(
95
+ filter(
96
+ lambda x: "checkpoint_" in x,
97
+ os.listdir(self.config.resume_from),
98
+ )
99
+ )
100
+ if len(checkpoints) == 0:
101
+ raise ValueError(f"No checkpoints found in {self.config.resume_from}")
102
+ checkpoint_numbers = sorted([int(x.split("_")[-1]) for x in checkpoints])
103
+ self.config.resume_from = os.path.join(
104
+ self.config.resume_from,
105
+ f"checkpoint_{checkpoint_numbers[-1]}",
106
+ )
107
+
108
+ accelerator_project_config.iteration = checkpoint_numbers[-1] + 1
109
+
110
+ # number of timesteps within each trajectory to train on
111
+ self.num_train_timesteps = int(self.config.sample_num_steps * self.config.train_timestep_fraction)
112
+
113
+ self.accelerator = Accelerator(
114
+ log_with=self.config.log_with,
115
+ mixed_precision=self.config.mixed_precision,
116
+ project_config=accelerator_project_config,
117
+ # we always accumulate gradients across timesteps; we want config.train.gradient_accumulation_steps to be the
118
+ # number of *samples* we accumulate across, so we need to multiply by the number of training timesteps to get
119
+ # the total number of optimizer steps to accumulate across.
120
+ gradient_accumulation_steps=self.config.train_gradient_accumulation_steps * self.num_train_timesteps,
121
+ **self.config.accelerator_kwargs,
122
+ )
123
+
124
+ is_okay, message = self._config_check()
125
+ if not is_okay:
126
+ raise ValueError(message)
127
+
128
+ is_using_tensorboard = config.log_with is not None and config.log_with == "tensorboard"
129
+
130
+ if self.accelerator.is_main_process:
131
+ self.accelerator.init_trackers(
132
+ self.config.tracker_project_name,
133
+ config=dict(ddpo_trainer_config=config.to_dict()) if not is_using_tensorboard else config.to_dict(),
134
+ init_kwargs=self.config.tracker_kwargs,
135
+ )
136
+
137
+ logger.info(f"\n{config}")
138
+
139
+ set_seed(self.config.seed, device_specific=True)
140
+
141
+ self.sd_pipeline = sd_pipeline
142
+
143
+ self.sd_pipeline.set_progress_bar_config(
144
+ position=1,
145
+ disable=not self.accelerator.is_local_main_process,
146
+ leave=False,
147
+ desc="Timestep",
148
+ dynamic_ncols=True,
149
+ )
150
+
151
+ # For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
152
+ # as these weights are only used for inference, keeping weights in full precision is not required.
153
+ if self.accelerator.mixed_precision == "fp16":
154
+ inference_dtype = torch.float16
155
+ elif self.accelerator.mixed_precision == "bf16":
156
+ inference_dtype = torch.bfloat16
157
+ else:
158
+ inference_dtype = torch.float32
159
+
160
+ self.sd_pipeline.vae.to(self.accelerator.device, dtype=inference_dtype)
161
+ self.sd_pipeline.text_encoder.to(self.accelerator.device, dtype=inference_dtype)
162
+ self.sd_pipeline.unet.to(self.accelerator.device, dtype=inference_dtype)
163
+
164
+ trainable_layers = self.sd_pipeline.get_trainable_layers()
165
+
166
+ self.accelerator.register_save_state_pre_hook(self._save_model_hook)
167
+ self.accelerator.register_load_state_pre_hook(self._load_model_hook)
168
+
169
+ # Enable TF32 for faster training on Ampere GPUs,
170
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
171
+ if self.config.allow_tf32:
172
+ torch.backends.cuda.matmul.allow_tf32 = True
173
+
174
+ self.optimizer = self._setup_optimizer(trainable_layers.parameters() if not isinstance(trainable_layers, list) else trainable_layers)
175
+
176
+ self.neg_prompt_embed = self.sd_pipeline.text_encoder(
177
+ self.sd_pipeline.tokenizer(
178
+ [""] if self.config.negative_prompts is None else self.config.negative_prompts,
179
+ return_tensors="pt",
180
+ padding="max_length",
181
+ truncation=True,
182
+ max_length=self.sd_pipeline.tokenizer.model_max_length,
183
+ ).input_ids.to(self.accelerator.device)
184
+ )[0]
185
+
186
+ if config.per_prompt_stat_tracking:
187
+ self.stat_tracker = PerPromptStatTracker(
188
+ config.per_prompt_stat_tracking_buffer_size,
189
+ config.per_prompt_stat_tracking_min_count,
190
+ )
191
+
192
+ # NOTE: for some reason, autocast is necessary for non-lora training but for lora training it isn't necessary and it uses
193
+ # more memory
194
+ self.autocast = self.sd_pipeline.autocast or self.accelerator.autocast
195
+
196
+ if hasattr(self.sd_pipeline, "use_lora") and self.sd_pipeline.use_lora:
197
+ unet, self.optimizer = self.accelerator.prepare(trainable_layers, self.optimizer)
198
+ self.trainable_layers = list(filter(lambda p: p.requires_grad, unet.parameters()))
199
+ else:
200
+ self.trainable_layers, self.optimizer = self.accelerator.prepare(trainable_layers, self.optimizer)
201
+
202
+ if self.config.async_reward_computation:
203
+ self.executor = futures.ThreadPoolExecutor(max_workers=config.max_workers)
204
+
205
+ if config.resume_from:
206
+ logger.info(f"Resuming from {config.resume_from}")
207
+ self.accelerator.load_state(config.resume_from)
208
+ self.first_epoch = int(config.resume_from.split("_")[-1]) + 1
209
+ else:
210
+ self.first_epoch = 0
211
+
212
+ def compute_rewards(self, prompt_image_pairs, is_async=False):
213
+ if not is_async:
214
+ rewards = []
215
+ for images, prompts, prompt_metadata in prompt_image_pairs:
216
+ reward, reward_metadata = self.reward_fn(images, prompts, prompt_metadata)
217
+ rewards.append(
218
+ (
219
+ torch.as_tensor(reward, device=self.accelerator.device),
220
+ reward_metadata,
221
+ )
222
+ )
223
+ else:
224
+ rewards = self.executor.map(lambda x: self.reward_fn(*x), prompt_image_pairs)
225
+ rewards = [(torch.as_tensor(reward.result(), device=self.accelerator.device), reward_metadata.result()) for reward, reward_metadata in rewards]
226
+
227
+ return zip(*rewards)
228
+
229
+ def step(self, epoch: int, global_step: int):
230
+ """
231
+ Perform a single step of training.
232
+
233
+ Args:
234
+ epoch (int): The current epoch.
235
+ global_step (int): The current global step.
236
+
237
+ Side Effects:
238
+ - Model weights are updated
239
+ - Logs the statistics to the accelerator trackers.
240
+ - If `self.image_samples_callback` is not None, it will be called with the prompt_image_pairs, global_step, and the accelerator tracker.
241
+
242
+ Returns:
243
+ global_step (int): The updated global step.
244
+
245
+ """
246
+ samples, prompt_image_data = self._generate_samples(
247
+ iterations=self.config.sample_num_batches_per_epoch,
248
+ batch_size=self.config.sample_batch_size,
249
+ )
250
+
251
+ # collate samples into dict where each entry has shape (num_batches_per_epoch * sample.batch_size, ...)
252
+ samples = {k: torch.cat([s[k] for s in samples]) for k in samples[0].keys()}
253
+ rewards, rewards_metadata = self.compute_rewards(prompt_image_data, is_async=self.config.async_reward_computation)
254
+
255
+ for i, image_data in enumerate(prompt_image_data):
256
+ image_data.extend([rewards[i], rewards_metadata[i]])
257
+
258
+ if self.image_samples_callback is not None:
259
+ self.image_samples_callback(prompt_image_data, global_step, self.accelerator.trackers[0])
260
+
261
+ rewards = torch.cat(rewards)
262
+ rewards = self.accelerator.gather(rewards).cpu().numpy()
263
+
264
+ self.accelerator.log(
265
+ {
266
+ "reward": rewards,
267
+ "epoch": epoch,
268
+ "reward_mean": rewards.mean(),
269
+ "reward_std": rewards.std(),
270
+ },
271
+ step=global_step,
272
+ )
273
+
274
+ if self.config.per_prompt_stat_tracking:
275
+ # gather the prompts across processes
276
+ prompt_ids = self.accelerator.gather(samples["prompt_ids"]).cpu().numpy()
277
+ prompts = self.sd_pipeline.tokenizer.batch_decode(prompt_ids, skip_special_tokens=True)
278
+ advantages = self.stat_tracker.update(prompts, rewards)
279
+ else:
280
+ advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-8)
281
+
282
+ # ungather advantages; keep the entries corresponding to the samples on this process
283
+ samples["advantages"] = torch.as_tensor(advantages).reshape(self.accelerator.num_processes, -1)[self.accelerator.process_index].to(self.accelerator.device)
284
+
285
+ del samples["prompt_ids"]
286
+
287
+ total_batch_size, num_timesteps = samples["timesteps"].shape
288
+
289
+ for inner_epoch in range(self.config.train_num_inner_epochs):
290
+ # shuffle samples along batch dimension
291
+ perm = torch.randperm(total_batch_size, device=self.accelerator.device)
292
+ samples = {k: v[perm] for k, v in samples.items()}
293
+
294
+ # shuffle along time dimension independently for each sample
295
+ # still trying to understand the code below
296
+ perms = torch.stack([torch.randperm(num_timesteps, device=self.accelerator.device) for _ in range(total_batch_size)])
297
+
298
+ for key in ["timesteps", "latents", "next_latents", "log_probs"]:
299
+ samples[key] = samples[key][
300
+ torch.arange(total_batch_size, device=self.accelerator.device)[:, None],
301
+ perms,
302
+ ]
303
+
304
+ original_keys = samples.keys()
305
+ original_values = samples.values()
306
+ # rebatch them as user defined train_batch_size is different from sample_batch_size
307
+ reshaped_values = [v.reshape(-1, self.config.train_batch_size, *v.shape[1:]) for v in original_values]
308
+
309
+ # Transpose the list of original values
310
+ transposed_values = zip(*reshaped_values)
311
+ # Create new dictionaries for each row of transposed values
312
+ samples_batched = [dict(zip(original_keys, row_values)) for row_values in transposed_values]
313
+
314
+ self.sd_pipeline.unet.train()
315
+ global_step = self._train_batched_samples(inner_epoch, epoch, global_step, samples_batched)
316
+ # ensure optimization step at the end of the inner epoch
317
+ if not self.accelerator.sync_gradients:
318
+ raise ValueError("Optimization step should have been performed by this point. Please check calculated gradient accumulation settings.")
319
+
320
+ if epoch != 0 and epoch % self.config.save_freq == 0 and self.accelerator.is_main_process:
321
+ self.accelerator.save_state()
322
+
323
+ return global_step
324
+
325
+ def calculate_loss(self, latents, timesteps, next_latents, log_probs, advantages, embeds):
326
+ """
327
+ Calculate the loss for a batch of an unpacked sample
328
+
329
+ Args:
330
+ latents (torch.Tensor):
331
+ The latents sampled from the diffusion model, shape: [batch_size, num_channels_latents, height, width]
332
+ timesteps (torch.Tensor):
333
+ The timesteps sampled from the diffusion model, shape: [batch_size]
334
+ next_latents (torch.Tensor):
335
+ The next latents sampled from the diffusion model, shape: [batch_size, num_channels_latents, height, width]
336
+ log_probs (torch.Tensor):
337
+ The log probabilities of the latents, shape: [batch_size]
338
+ advantages (torch.Tensor):
339
+ The advantages of the latents, shape: [batch_size]
340
+ embeds (torch.Tensor):
341
+ The embeddings of the prompts, shape: [2*batch_size or batch_size, ...]
342
+ Note: the "or" is because if train_cfg is True, the expectation is that negative prompts are concatenated to the embeds
343
+
344
+ Returns:
345
+ loss (torch.Tensor), approx_kl (torch.Tensor), clipfrac (torch.Tensor)
346
+ (all of these are of shape (1,))
347
+ """
348
+ with self.autocast():
349
+ if self.config.train_cfg:
350
+ noise_pred = self.sd_pipeline.unet(
351
+ torch.cat([latents] * 2),
352
+ torch.cat([timesteps] * 2),
353
+ embeds,
354
+ ).sample
355
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
356
+ noise_pred = noise_pred_uncond + self.config.sample_guidance_scale * (noise_pred_text - noise_pred_uncond)
357
+ else:
358
+ noise_pred = self.sd_pipeline.unet(
359
+ latents,
360
+ timesteps,
361
+ embeds,
362
+ ).sample
363
+ # compute the log prob of next_latents given latents under the current model
364
+
365
+ scheduler_step_output = self.sd_pipeline.scheduler_step(
366
+ noise_pred,
367
+ timesteps,
368
+ latents,
369
+ eta=self.config.sample_eta,
370
+ prev_sample=next_latents,
371
+ )
372
+
373
+ log_prob = scheduler_step_output.log_probs
374
+
375
+ advantages = torch.clamp(
376
+ advantages,
377
+ -self.config.train_adv_clip_max,
378
+ self.config.train_adv_clip_max,
379
+ )
380
+
381
+ ratio = torch.exp(log_prob - log_probs)
382
+
383
+ loss = self.loss(advantages, self.config.train_clip_range, ratio)
384
+
385
+ approx_kl = 0.5 * torch.mean((log_prob - log_probs) ** 2)
386
+
387
+ clipfrac = torch.mean((torch.abs(ratio - 1.0) > self.config.train_clip_range).float())
388
+
389
+ return loss, approx_kl, clipfrac
390
+
391
+ def loss(
392
+ self,
393
+ advantages: torch.Tensor,
394
+ clip_range: float,
395
+ ratio: torch.Tensor,
396
+ ):
397
+ unclipped_loss = -advantages * ratio
398
+ clipped_loss = -advantages * torch.clamp(
399
+ ratio,
400
+ 1.0 - clip_range,
401
+ 1.0 + clip_range,
402
+ )
403
+ return torch.mean(torch.maximum(unclipped_loss, clipped_loss))
404
+
405
+ def _setup_optimizer(self, trainable_layers_parameters):
406
+ if self.config.train_use_8bit_adam:
407
+ import bitsandbytes
408
+
409
+ optimizer_cls = bitsandbytes.optim.AdamW8bit
410
+ else:
411
+ optimizer_cls = torch.optim.AdamW
412
+
413
+ return optimizer_cls(
414
+ trainable_layers_parameters,
415
+ lr=self.config.train_learning_rate,
416
+ betas=(self.config.train_adam_beta1, self.config.train_adam_beta2),
417
+ weight_decay=self.config.train_adam_weight_decay,
418
+ eps=self.config.train_adam_epsilon,
419
+ )
420
+
421
+ def _save_model_hook(self, models, weights, output_dir):
422
+ self.sd_pipeline.save_checkpoint(models, weights, output_dir)
423
+ weights.pop() # ensures that accelerate doesn't try to handle saving of the model
424
+
425
+ def _load_model_hook(self, models, input_dir):
426
+ self.sd_pipeline.load_checkpoint(models, input_dir)
427
+ models.pop() # ensures that accelerate doesn't try to handle loading of the model
428
+
429
+ def _generate_samples(self, iterations, batch_size):
430
+ """
431
+ Generate samples from the model
432
+
433
+ Args:
434
+ iterations (int): Number of iterations to generate samples for
435
+ batch_size (int): Batch size to use for sampling
436
+
437
+ Returns:
438
+ samples (List[Dict[str, torch.Tensor]]), prompt_image_pairs (List[List[Any]])
439
+ """
440
+ samples = []
441
+ prompt_image_pairs = []
442
+ self.sd_pipeline.unet.eval()
443
+
444
+ sample_neg_prompt_embeds = self.neg_prompt_embed.repeat(batch_size, 1, 1)
445
+
446
+ for _ in range(iterations):
447
+ prompts, prompt_metadata = zip(*[self.prompt_fn() for _ in range(batch_size)])
448
+
449
+ prompt_ids = self.sd_pipeline.tokenizer(
450
+ prompts,
451
+ return_tensors="pt",
452
+ padding="max_length",
453
+ truncation=True,
454
+ max_length=self.sd_pipeline.tokenizer.model_max_length,
455
+ ).input_ids.to(self.accelerator.device)
456
+ prompt_embeds = self.sd_pipeline.text_encoder(prompt_ids)[0]
457
+
458
+ with self.autocast():
459
+ sd_output = self.sd_pipeline(
460
+ prompt_embeds=prompt_embeds,
461
+ negative_prompt_embeds=sample_neg_prompt_embeds,
462
+ num_inference_steps=self.config.sample_num_steps,
463
+ guidance_scale=self.config.sample_guidance_scale,
464
+ eta=self.config.sample_eta,
465
+ output_type="pt",
466
+ )
467
+
468
+ images = sd_output.images
469
+ latents = sd_output.latents
470
+ log_probs = sd_output.log_probs
471
+
472
+ latents = torch.stack(latents, dim=1) # (batch_size, num_steps + 1, ...)
473
+ log_probs = torch.stack(log_probs, dim=1) # (batch_size, num_steps, 1)
474
+ timesteps = self.sd_pipeline.scheduler.timesteps.repeat(batch_size, 1) # (batch_size, num_steps)
475
+
476
+ samples.append(
477
+ {
478
+ "prompt_ids": prompt_ids,
479
+ "prompt_embeds": prompt_embeds,
480
+ "timesteps": timesteps,
481
+ "latents": latents[:, :-1], # each entry is the latent before timestep t
482
+ "next_latents": latents[:, 1:], # each entry is the latent after timestep t
483
+ "log_probs": log_probs,
484
+ "negative_prompt_embeds": sample_neg_prompt_embeds,
485
+ }
486
+ )
487
+ prompt_image_pairs.append([images, prompts, prompt_metadata])
488
+
489
+ return samples, prompt_image_pairs
490
+
491
+ def _train_batched_samples(self, inner_epoch, epoch, global_step, batched_samples):
492
+ """
493
+ Train on a batch of samples. Main training segment
494
+
495
+ Args:
496
+ inner_epoch (int): The current inner epoch
497
+ epoch (int): The current epoch
498
+ global_step (int): The current global step
499
+ batched_samples (List[Dict[str, torch.Tensor]]): The batched samples to train on
500
+
501
+ Side Effects:
502
+ - Model weights are updated
503
+ - Logs the statistics to the accelerator trackers.
504
+
505
+ Returns:
506
+ global_step (int): The updated global step
507
+ """
508
+ info = defaultdict(list)
509
+ for i, sample in enumerate(batched_samples):
510
+ if self.config.train_cfg:
511
+ # concat negative prompts to sample prompts to avoid two forward passes
512
+ embeds = torch.cat([sample["negative_prompt_embeds"], sample["prompt_embeds"]])
513
+ else:
514
+ embeds = sample["prompt_embeds"]
515
+
516
+ for j in range(self.num_train_timesteps):
517
+ with self.accelerator.accumulate(self.sd_pipeline.unet):
518
+ loss, approx_kl, clipfrac = self.calculate_loss(
519
+ sample["latents"][:, j],
520
+ sample["timesteps"][:, j],
521
+ sample["next_latents"][:, j],
522
+ sample["log_probs"][:, j],
523
+ sample["advantages"],
524
+ embeds,
525
+ )
526
+ info["approx_kl"].append(approx_kl)
527
+ info["clipfrac"].append(clipfrac)
528
+ info["loss"].append(loss)
529
+
530
+ self.accelerator.backward(loss)
531
+ if self.accelerator.sync_gradients:
532
+ self.accelerator.clip_grad_norm_(
533
+ self.trainable_layers.parameters() if not isinstance(self.trainable_layers, list) else self.trainable_layers,
534
+ self.config.train_max_grad_norm,
535
+ )
536
+ self.optimizer.step()
537
+ self.optimizer.zero_grad()
538
+
539
+ # Checks if the accelerator has performed an optimization step behind the scenes
540
+ if self.accelerator.sync_gradients:
541
+ # log training-related stuff
542
+ info = {k: torch.mean(torch.stack(v)) for k, v in info.items()}
543
+ info = self.accelerator.reduce(info, reduction="mean")
544
+ info.update({"epoch": epoch, "inner_epoch": inner_epoch})
545
+ self.accelerator.log(info, step=global_step)
546
+ global_step += 1
547
+ info = defaultdict(list)
548
+ return global_step
549
+
550
+ def _config_check(self) -> Tuple[bool, str]:
551
+ samples_per_epoch = self.config.sample_batch_size * self.accelerator.num_processes * self.config.sample_num_batches_per_epoch
552
+ total_train_batch_size = self.config.train_batch_size * self.accelerator.num_processes * self.config.train_gradient_accumulation_steps
553
+
554
+ if not self.config.sample_batch_size >= self.config.train_batch_size:
555
+ return (
556
+ False,
557
+ f"Sample batch size ({self.config.sample_batch_size}) must be greater than or equal to the train batch size ({self.config.train_batch_size})",
558
+ )
559
+ if not self.config.sample_batch_size % self.config.train_batch_size == 0:
560
+ return (
561
+ False,
562
+ f"Sample batch size ({self.config.sample_batch_size}) must be divisible by the train batch size ({self.config.train_batch_size})",
563
+ )
564
+ if not samples_per_epoch % total_train_batch_size == 0:
565
+ return (
566
+ False,
567
+ f"Number of samples per epoch ({samples_per_epoch}) must be divisible by the total train batch size ({total_train_batch_size})",
568
+ )
569
+ return True, ""
570
+
571
+ def train(self, epochs: Optional[int] = None):
572
+ """
573
+ Train the model for a given number of epochs
574
+ """
575
+ global_step = 0
576
+ if epochs is None:
577
+ epochs = self.config.num_epochs
578
+ for epoch in range(self.first_epoch, epochs):
579
+ global_step = self.step(epoch, global_step)
580
+
581
+ def create_model_card(self, path: str, model_name: Optional[str] = "TRL DDPO Model") -> None:
582
+ """Creates and saves a model card for a TRL model.
583
+
584
+ Args:
585
+ path (`str`): The path to save the model card to.
586
+ model_name (`str`, *optional*): The name of the model, defaults to `TRL DDPO Model`.
587
+ """
588
+ try:
589
+ user = whoami()["name"]
590
+ # handle the offline case
591
+ except: # noqa
592
+ warnings.warn("Cannot retrieve user information assuming you are running in offline mode.")
593
+ return
594
+
595
+ if not os.path.exists(path):
596
+ os.makedirs(path)
597
+
598
+ model_card_content = MODEL_CARD_TEMPLATE.format(model_name=model_name, model_id=f"{user}/{path}")
599
+ with open(os.path.join(path, "README.md"), "w", encoding="utf-8") as f:
600
+ f.write(model_card_content)
601
+
602
+ def _save_pretrained(self, save_directory):
603
+ self.sd_pipeline.save_pretrained(save_directory)
604
+ self.create_model_card(save_directory)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/dpo_trainer.py ADDED
@@ -0,0 +1,1186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DPO Authors: Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning, and Chelsea Finn 2023
2
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import inspect
16
+ import random
17
+ import warnings
18
+ from collections import defaultdict
19
+ from contextlib import contextmanager, nullcontext
20
+ from copy import deepcopy
21
+ from functools import wraps
22
+ from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union
23
+
24
+ import numpy as np
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+ from accelerate import PartialState
29
+ from accelerate.utils import is_deepspeed_available, tqdm
30
+ from datasets import Dataset
31
+ from torch.utils.data import DataLoader
32
+ from transformers import (
33
+ AutoModelForCausalLM,
34
+ DataCollator,
35
+ PreTrainedModel,
36
+ PreTrainedTokenizerBase,
37
+ Trainer,
38
+ TrainingArguments,
39
+ )
40
+ from transformers.trainer_callback import TrainerCallback
41
+ from transformers.trainer_utils import EvalLoopOutput
42
+
43
+ from ..import_utils import is_peft_available, is_wandb_available
44
+ from ..models import PreTrainedModelWrapper, create_reference_model
45
+ from .utils import (
46
+ DPODataCollatorWithPadding,
47
+ disable_dropout_in_model,
48
+ pad_to_length,
49
+ peft_module_casting_to_bf16,
50
+ trl_sanitze_kwargs_for_tagging,
51
+ )
52
+
53
+
54
+ if is_peft_available():
55
+ from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training
56
+
57
+
58
+ if is_wandb_available():
59
+ import wandb
60
+
61
+ if is_deepspeed_available():
62
+ import deepspeed
63
+
64
+ from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
65
+
66
+
67
+ class DPOTrainer(Trainer):
68
+ r"""
69
+ Initialize DPOTrainer.
70
+
71
+ Args:
72
+ model (`transformers.PreTrainedModel`):
73
+ The model to train, preferably an `AutoModelForSequenceClassification`.
74
+ ref_model (`PreTrainedModelWrapper`):
75
+ Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no
76
+ reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized.
77
+ beta (`float`, defaults to 0.1):
78
+ The beta factor in DPO loss. Higher beta means less divergence from the initial policy. For the IPO loss, beta is the regularization parameter denoted by tau in the paper.
79
+ label_smoothing (`float`, defaults to 0):
80
+ The robust DPO label smoothing parameter from the [cDPO](https://ericmitchell.ai/cdpo.pdf) report that should be between 0 and 0.5.
81
+ loss_type (`str`, defaults to `"sigmoid"`):
82
+ The type of DPO loss to use. Either `"sigmoid"` the default DPO loss,`"hinge"` loss from [SLiC](https://arxiv.org/abs/2305.10425) paper, `"ipo"` from [IPO](https://arxiv.org/abs/2310.12036) paper, or `"kto"` from the HALOs [report](https://github.com/ContextualAI/HALOs/blob/main/assets/report.pdf).
83
+ args (`transformers.TrainingArguments`):
84
+ The arguments to use for training.
85
+ data_collator (`transformers.DataCollator`):
86
+ The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used
87
+ which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.
88
+ label_pad_token_id (`int`, defaults to `-100`):
89
+ The label pad token id. This argument is required if you want to use the default data collator.
90
+ padding_value (`int`, defaults to `0`):
91
+ The padding value if it is different to the tokenizer's pad_token_id.
92
+ truncation_mode (`str`, defaults to `keep_end`):
93
+ The truncation mode to use, either `keep_end` or `keep_start`. This argument is required if you want to use the default data collator.
94
+ train_dataset (`datasets.Dataset`):
95
+ The dataset to use for training.
96
+ eval_dataset (`datasets.Dataset`):
97
+ The dataset to use for evaluation.
98
+ tokenizer (`transformers.PreTrainedTokenizerBase`):
99
+ The tokenizer to use for training. This argument is required if you want to use the default data collator.
100
+ model_init (`Callable[[], transformers.PreTrainedModel]`):
101
+ The model initializer to use for training. If None is specified, the default model initializer will be used.
102
+ callbacks (`List[transformers.TrainerCallback]`):
103
+ The callbacks to use for training.
104
+ optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
105
+ The optimizer and scheduler to use for training.
106
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
107
+ The function to use to preprocess the logits before computing the metrics.
108
+ max_length (`int`, defaults to `None`):
109
+ The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator.
110
+ max_prompt_length (`int`, defaults to `None`):
111
+ The maximum length of the prompt. This argument is required if you want to use the default data collator.
112
+ max_target_length (`int`, defaults to `None`):
113
+ The maximum length of the target. This argument is required if you want to use the default data collator and your model is an encoder-decoder.
114
+ peft_config (`Dict`, defaults to `None`):
115
+ The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.
116
+ is_encoder_decoder (`Optional[bool]`, `optional`, defaults to `None`):
117
+ If no model is provided, we need to know if the model_init returns an encoder-decoder.
118
+ disable_dropout (`bool`, defaults to `True`):
119
+ Whether or not to disable dropouts in `model` and `ref_model`.
120
+ generate_during_eval (`bool`, defaults to `False`):
121
+ Whether to sample and log generations during evaluation step.
122
+ compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*):
123
+ The function to use to compute the metrics. Must take a `EvalPrediction` and return
124
+ a dictionary string to metric values.
125
+ precompute_ref_log_probs (`bool`, defaults to `False`):
126
+ Flag to precompute reference model log probabilities and evaluation datasets. This is useful if you want to train
127
+ without the reference model and reduce the total GPU memory needed.
128
+ dataset_num_proc (`Optional[int]`, *optional*):
129
+ The number of workers to use to tokenize the data. Defaults to None.
130
+ model_init_kwargs (`Optional[Dict]`, *optional*):
131
+ Dict of Optional kwargs to pass when instantiating the model from a string
132
+ ref_model_init_kwargs (`Optional[Dict]`, *optional*):
133
+ Dict of Optional kwargs to pass when instantiating the ref model from a string
134
+ model_adapter_name (`str`, defaults to `None`):
135
+ Name of the train target PEFT adapter, when using LoRA with multiple adapters.
136
+ ref_adapter_name (`str`, defaults to `None`):
137
+ Name of the reference PEFT adapter, when using LoRA with multiple adapters.
138
+ reference_free (`bool`):
139
+ If True, we ignore the _provided_ reference model and implicitly use a reference model that assigns equal probability to all responses.
140
+ """
141
+
142
+ _tag_names = ["trl", "dpo"]
143
+
144
+ def __init__(
145
+ self,
146
+ model: Optional[Union[PreTrainedModel, nn.Module, str]] = None,
147
+ ref_model: Optional[Union[PreTrainedModel, nn.Module, str]] = None,
148
+ dpo_alpha: float = 1.0,
149
+ beta: float = 0.1,
150
+ gamma: float = 0.1,
151
+ label_smoothing: float = 0,
152
+ loss_type: Literal["sigmoid", "hinge", "ipo", "kto_pair"] = "sigmoid",
153
+ args: Optional[TrainingArguments] = None,
154
+ data_collator: Optional[DataCollator] = None,
155
+ label_pad_token_id: int = -100,
156
+ padding_value: Optional[int] = None,
157
+ truncation_mode: str = "keep_end",
158
+ train_dataset: Optional[Dataset] = None,
159
+ eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None,
160
+ tokenizer: Optional[PreTrainedTokenizerBase] = None,
161
+ model_init: Optional[Callable[[], PreTrainedModel]] = None,
162
+ callbacks: Optional[List[TrainerCallback]] = None,
163
+ optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
164
+ preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
165
+ max_length: Optional[int] = None,
166
+ max_prompt_length: Optional[int] = None,
167
+ max_target_length: Optional[int] = None,
168
+ peft_config: Optional[Dict] = None,
169
+ is_encoder_decoder: Optional[bool] = None,
170
+ disable_dropout: bool = True,
171
+ generate_during_eval: bool = False,
172
+ compute_metrics: Optional[Callable[[EvalLoopOutput], Dict]] = None,
173
+ precompute_ref_log_probs: bool = False,
174
+ dataset_num_proc: Optional[int] = None,
175
+ model_init_kwargs: Optional[Dict] = None,
176
+ ref_model_init_kwargs: Optional[Dict] = None,
177
+ model_adapter_name: Optional[str] = None,
178
+ ref_adapter_name: Optional[str] = None,
179
+ reference_free: bool = False,
180
+ ):
181
+ # import pdb;pdb.set_trace()
182
+ if model_init_kwargs is None:
183
+ model_init_kwargs = {}
184
+ elif not isinstance(model, str):
185
+ raise ValueError("You passed model_kwargs to the DPOTrainer. But your model is already instantiated.")
186
+
187
+ if ref_model_init_kwargs is None:
188
+ ref_model_init_kwargs = {}
189
+ elif not isinstance(ref_model, str):
190
+ raise ValueError("You passed ref_model_kwargs to the DPOTrainer. But your ref_model is already instantiated.")
191
+
192
+ if isinstance(model, str):
193
+ warnings.warn("You passed a model_id to the DPOTrainer. This will automatically create an " "`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you.")
194
+ model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
195
+
196
+ if isinstance(ref_model, str):
197
+ warnings.warn("You passed a ref model_id to the DPOTrainer. This will automatically create an " "`AutoModelForCausalLM`")
198
+ ref_model = AutoModelForCausalLM.from_pretrained(ref_model, **ref_model_init_kwargs)
199
+
200
+ # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16`
201
+ # has been called in order to properly call autocast if needed.
202
+ self._peft_has_been_casted_to_bf16 = False
203
+
204
+ if generate_during_eval and not is_wandb_available():
205
+ raise ValueError("`generate_during_eval=True` requires Weights and Biases to be installed." " Please install `wandb` to resolve.")
206
+
207
+ if model is not None:
208
+ self.is_encoder_decoder = model.config.is_encoder_decoder
209
+ elif is_encoder_decoder is None:
210
+ raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.")
211
+ else:
212
+ self.is_encoder_decoder = is_encoder_decoder
213
+
214
+ self.is_peft_model = is_peft_available() and isinstance(model, PeftModel)
215
+ self.model_adapter_name = model_adapter_name
216
+ self.ref_adapter_name = ref_adapter_name
217
+ self.reference_free = reference_free
218
+
219
+ if ref_model:
220
+ self.ref_model = ref_model
221
+ elif self.is_peft_model or precompute_ref_log_probs:
222
+ # The `model` with adapters turned off will be used as the reference model
223
+ self.ref_model = None
224
+ else:
225
+ if is_deepspeed_zero3_enabled():
226
+ self.ref_model = AutoModelForCausalLM.from_pretrained(model)
227
+ else:
228
+ self.ref_model = create_reference_model(model)
229
+
230
+ if tokenizer is None:
231
+ raise ValueError("tokenizer must be specified to tokenize a DPO dataset.")
232
+ if max_length is None:
233
+ warnings.warn(
234
+ "`max_length` is not set in the DPOTrainer's init" " it will default to `512` by default, but you should do it yourself in the future.",
235
+ UserWarning,
236
+ )
237
+ max_length = 512
238
+ if max_prompt_length is None:
239
+ warnings.warn(
240
+ "`max_prompt_length` is not set in the DPOTrainer's init" " it will default to `128` by default, but you should do it yourself in the future.",
241
+ UserWarning,
242
+ )
243
+ max_prompt_length = 128
244
+
245
+ if max_target_length is None and self.is_encoder_decoder:
246
+ warnings.warn(
247
+ "When using an encoder decoder architecture, you should set `max_target_length` in the DPOTrainer's init" " it will default to `128` by default, but you should do it yourself in the future.",
248
+ UserWarning,
249
+ )
250
+ max_target_length = 128
251
+
252
+ if data_collator is None:
253
+ data_collator = DPODataCollatorWithPadding(
254
+ pad_token_id=tokenizer.pad_token_id,
255
+ label_pad_token_id=label_pad_token_id,
256
+ is_encoder_decoder=self.is_encoder_decoder,
257
+ )
258
+
259
+ if args.remove_unused_columns:
260
+ args.remove_unused_columns = False
261
+ # warn users
262
+ warnings.warn(
263
+ "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments" " we have set it for you, but you should do it yourself in the future.",
264
+ UserWarning,
265
+ )
266
+
267
+ self.use_dpo_data_collator = True
268
+ else:
269
+ self.use_dpo_data_collator = False
270
+
271
+ if disable_dropout:
272
+ disable_dropout_in_model(model)
273
+ if self.ref_model is not None:
274
+ disable_dropout_in_model(self.ref_model)
275
+
276
+ self.max_length = max_length
277
+ self.generate_during_eval = generate_during_eval
278
+ self.label_pad_token_id = label_pad_token_id
279
+ self.padding_value = padding_value if padding_value is not None else tokenizer.pad_token_id
280
+ self.max_prompt_length = max_prompt_length
281
+ self.truncation_mode = truncation_mode
282
+ self.max_target_length = max_target_length
283
+ self.tokenizer = tokenizer
284
+ self.precompute_ref_log_probs = precompute_ref_log_probs
285
+
286
+ # Since ref_logs are precomputed on the first call to get_train/eval_dataloader
287
+ # keep track of first called to avoid computation of future calls
288
+ self._precomputed_train_ref_log_probs = False
289
+ self._precomputed_eval_ref_log_probs = False
290
+
291
+ if loss_type in ["hinge", "ipo", "kto_pair"] and label_smoothing > 0:
292
+ warnings.warn("You are using a loss type that does not support label smoothing. Ignoring label_smoothing parameter.")
293
+
294
+ self.dpo_alpha = dpo_alpha
295
+ self.beta = beta
296
+ self.gamma = gamma
297
+ self.label_smoothing = label_smoothing
298
+ self.loss_type = loss_type
299
+
300
+ self._stored_metrics = defaultdict(lambda: defaultdict(list))
301
+
302
+ self.dataset_num_proc = dataset_num_proc
303
+
304
+ # Compute that only on the main process for faster data processing.
305
+ # see: https://github.com/huggingface/trl/pull/1255
306
+ # with PartialState().local_main_process_first():
307
+ # # tokenize the dataset
308
+ # train_dataset = train_dataset.map(self.tokenize_row, num_proc=self.dataset_num_proc)
309
+ # if eval_dataset is not None:
310
+ # eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=self.dataset_num_proc)
311
+
312
+ super().__init__(
313
+ model=model,
314
+ args=args,
315
+ data_collator=data_collator,
316
+ train_dataset=train_dataset,
317
+ eval_dataset=eval_dataset,
318
+ tokenizer=tokenizer,
319
+ model_init=model_init,
320
+ compute_metrics=compute_metrics,
321
+ callbacks=callbacks,
322
+ optimizers=optimizers,
323
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
324
+ )
325
+
326
+ if not hasattr(self, "accelerator"):
327
+ raise AttributeError("Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`.")
328
+
329
+ # Deepspeed Zero-3 does not support precompute_ref_log_probs
330
+ if self.is_deepspeed_enabled:
331
+ if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs:
332
+ raise ValueError("You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`.")
333
+
334
+ if self.ref_model is None:
335
+ if not (self.is_peft_model or self.precompute_ref_log_probs):
336
+ raise ValueError("No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`")
337
+ else:
338
+ if self.is_deepspeed_enabled:
339
+ self.ref_model = self._prepare_deepspeed(self.ref_model)
340
+ else:
341
+ self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
342
+
343
+ def _prepare_deepspeed(self, model: PreTrainedModelWrapper):
344
+ # Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473
345
+ deepspeed_plugin = self.accelerator.state.deepspeed_plugin
346
+ config_kwargs = deepcopy(deepspeed_plugin.deepspeed_config)
347
+
348
+ if model is not None:
349
+ if hasattr(model, "config"):
350
+ hidden_size = max(model.config.hidden_sizes) if getattr(model.config, "hidden_sizes", None) else getattr(model.config, "hidden_size", None)
351
+ if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3:
352
+ # Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0`
353
+ # This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081
354
+ config_kwargs.update(
355
+ {
356
+ "zero_optimization.reduce_bucket_size": hidden_size * hidden_size,
357
+ "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size,
358
+ "zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size,
359
+ }
360
+ )
361
+
362
+ # If ZeRO-3 is used, we shard both the active and reference model.
363
+ # Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0)
364
+ if config_kwargs["zero_optimization"]["stage"] != 3:
365
+ config_kwargs["zero_optimization"]["stage"] = 0
366
+ model, *_ = deepspeed.initialize(model=model, config=config_kwargs)
367
+ model.eval()
368
+ return model
369
+
370
+ def get_train_dataloader(self) -> DataLoader:
371
+ """
372
+ Returns the training [`~torch.utils.data.DataLoader`].
373
+
374
+ Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`.
375
+ """
376
+
377
+ if self.precompute_ref_log_probs and not self._precomputed_train_ref_log_probs:
378
+ dataloader_params = {
379
+ "batch_size": self.args.per_device_train_batch_size,
380
+ "collate_fn": self.data_collator,
381
+ "num_workers": self.args.dataloader_num_workers,
382
+ "pin_memory": self.args.dataloader_pin_memory,
383
+ "shuffle": False,
384
+ }
385
+
386
+ # prepare dataloader
387
+ data_loader = self.accelerator.prepare(DataLoader(self.train_dataset, **dataloader_params))
388
+
389
+ reference_chosen_logps = []
390
+ reference_rejected_logps = []
391
+ for padded_batch in tqdm(iterable=data_loader, desc="Train dataset reference log probs"):
392
+ reference_chosen_logp, reference_rejected_logp = self.compute_reference_log_probs(padded_batch)
393
+ reference_chosen_logp, reference_rejected_logp = self.accelerator.gather_for_metrics((reference_chosen_logp, reference_rejected_logp))
394
+ reference_chosen_logps.append(reference_chosen_logp.cpu())
395
+ reference_rejected_logps.append(reference_rejected_logp.cpu())
396
+
397
+ all_reference_chosen_logps = torch.cat(reference_chosen_logps).float().numpy()
398
+ all_reference_rejected_logps = torch.cat(reference_rejected_logps).float().numpy()
399
+
400
+ self.train_dataset = self.train_dataset.add_column(name="reference_chosen_logps", column=all_reference_chosen_logps)
401
+ self.train_dataset = self.train_dataset.add_column(name="reference_rejected_logps", column=all_reference_rejected_logps)
402
+
403
+ self._precomputed_train_ref_log_probs = True
404
+
405
+ return super().get_train_dataloader()
406
+
407
+ def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader:
408
+ """
409
+ Returns the evaluation [`~torch.utils.data.DataLoader`].
410
+
411
+ Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`.
412
+
413
+ Args:
414
+ eval_dataset (`torch.utils.data.Dataset`, *optional*):
415
+ If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted
416
+ by the `model.forward()` method are automatically removed. It must implement `__len__`.
417
+ """
418
+ if eval_dataset is None and self.eval_dataset is None:
419
+ raise ValueError("Trainer: evaluation requires an eval_dataset.")
420
+ eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset
421
+
422
+ if self.precompute_ref_log_probs and not self._precomputed_eval_ref_log_probs:
423
+ dataloader_params = {
424
+ "batch_size": self.args.per_device_eval_batch_size,
425
+ "collate_fn": self.data_collator,
426
+ "num_workers": self.args.dataloader_num_workers,
427
+ "pin_memory": self.args.dataloader_pin_memory,
428
+ "shuffle": False,
429
+ }
430
+
431
+ # prepare dataloader
432
+ data_loader = self.accelerator.prepare(DataLoader(eval_dataset, **dataloader_params))
433
+
434
+ reference_chosen_logps = []
435
+ reference_rejected_logps = []
436
+ for padded_batch in tqdm(iterable=data_loader, desc="Eval dataset reference log probs"):
437
+ reference_chosen_logp, reference_rejected_logp = self.compute_reference_log_probs(padded_batch)
438
+ reference_chosen_logp, reference_rejected_logp = self.accelerator.gather_for_metrics((reference_chosen_logp, reference_rejected_logp))
439
+ reference_chosen_logps.append(reference_chosen_logp.cpu())
440
+ reference_rejected_logps.append(reference_rejected_logp.cpu())
441
+
442
+ all_reference_chosen_logps = torch.cat(reference_chosen_logps).float().numpy()
443
+ all_reference_rejected_logps = torch.cat(reference_rejected_logps).float().numpy()
444
+
445
+ eval_dataset = eval_dataset.add_column(name="reference_chosen_logps", column=all_reference_chosen_logps)
446
+ eval_dataset = eval_dataset.add_column(name="reference_rejected_logps", column=all_reference_rejected_logps)
447
+
448
+ # Save calculated reference_chosen_logps and reference_rejected_logps to the eval_dataset for subsequent runs
449
+ if self.eval_dataset is not None:
450
+ self.eval_dataset = eval_dataset
451
+ self._precomputed_eval_ref_log_probs = True
452
+
453
+ return super().get_eval_dataloader(eval_dataset=eval_dataset)
454
+
455
+ def build_tokenized_answer(self, prompt, answer):
456
+ """
457
+ Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`.
458
+ It does ensure `enc(a + b) = enc(a) + enc(a + b)[len(enc(a)):]`.
459
+ Reference:
460
+ https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
461
+ """
462
+
463
+ full_tokenized = self.tokenizer(prompt + answer, add_special_tokens=False)
464
+ prompt_input_ids = self.tokenizer(prompt, add_special_tokens=False)["input_ids"]
465
+
466
+ answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :]
467
+ answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :]
468
+
469
+ # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]`
470
+ full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids])
471
+
472
+ # Prepare input tokens for token by token comparison
473
+ full_input_ids = np.array(full_tokenized["input_ids"])
474
+
475
+ if len(full_input_ids) != len(full_concat_input_ids):
476
+ raise ValueError("Prompt input ids and answer input ids should have the same length.")
477
+
478
+ # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens
479
+ # can be merged together when tokenizing prompt+answer. This could result
480
+ # on the last token from the prompt being different when tokenized on its own
481
+ # vs when done as prompt+answer.
482
+ response_token_ids_start_idx = len(prompt_input_ids)
483
+
484
+ # If tokenized prompt is different than both prompt+answer, then it means the
485
+ # last token has changed due to merging.
486
+ if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]:
487
+ response_token_ids_start_idx -= 1
488
+
489
+ prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx]
490
+ prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx]
491
+
492
+ if len(prompt_input_ids) != len(prompt_attention_mask):
493
+ raise ValueError("Prompt input ids and attention mask should have the same length.")
494
+
495
+ answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:]
496
+ answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:]
497
+
498
+ return dict(
499
+ prompt_input_ids=prompt_input_ids,
500
+ prompt_attention_mask=prompt_attention_mask,
501
+ input_ids=answer_input_ids,
502
+ attention_mask=answer_attention_mask,
503
+ )
504
+
505
+ def tokenize_row(self, feature, model: Optional[Union[PreTrainedModel, nn.Module]] = None) -> Dict:
506
+ """Tokenize a single row from a DPO specific dataset.
507
+
508
+ At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation
509
+ in case the prompt + chosen or prompt + rejected responses is/are too long. First
510
+ we truncate the prompt; if we're still too long, we truncate the chosen/rejected.
511
+
512
+ We also create the labels for the chosen/rejected responses, which are of length equal to
513
+ the sum of the length of the prompt and the chosen/rejected response, with
514
+ label_pad_token_id for the prompt tokens.
515
+ """
516
+ batch = {}
517
+ prompt = feature["prompt"]
518
+ chosen = feature["chosen"]
519
+ rejected = feature["rejected"]
520
+
521
+ if not self.is_encoder_decoder:
522
+ # Check issues below for more details
523
+ # 1. https://github.com/huggingface/trl/issues/907
524
+ # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
525
+ # 3. https://github.com/LianjiaTech/BELLE/issues/337
526
+
527
+ if not isinstance(prompt, str):
528
+ raise ValueError(f"prompt should be an str but got {type(prompt)}")
529
+ prompt_tokens = self.tokenizer(prompt, add_special_tokens=False)
530
+ prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()}
531
+
532
+ if not isinstance(chosen, str):
533
+ raise ValueError(f"chosen should be an str but got {type(chosen)}")
534
+ chosen_tokens = self.build_tokenized_answer(prompt, chosen)
535
+
536
+ if not isinstance(rejected, str):
537
+ raise ValueError(f"rejected should be an str but got {type(rejected)}")
538
+ rejected_tokens = self.build_tokenized_answer(prompt, rejected)
539
+
540
+ # Last prompt token might get merged by tokenizer and
541
+ # it should not be included for generation if that happens
542
+ prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"])
543
+
544
+ chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"])
545
+ rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"])
546
+ prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids)
547
+
548
+ for k, v in prompt_tokens.items():
549
+ prompt_tokens[k] = v[:prompt_len_input_ids]
550
+
551
+ # Make sure prompts only have one different token at most an
552
+ # and length only differs by 1 at most
553
+ num_diff_tokens = sum([a != b for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"])])
554
+ num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids)
555
+ if num_diff_tokens > 1 or num_diff_len > 1:
556
+ raise ValueError("Chosen and rejected prompt_input_ids might only differ on the " "last token due to tokenizer merge ops.")
557
+
558
+ # add BOS token to head of prompt
559
+ prompt_tokens["prompt_input_ids"] = [self.tokenizer.bos_token_id] + prompt_tokens["prompt_input_ids"]
560
+ chosen_tokens["prompt_input_ids"] = [self.tokenizer.bos_token_id] + chosen_tokens["prompt_input_ids"]
561
+ rejected_tokens["prompt_input_ids"] = [self.tokenizer.bos_token_id] + rejected_tokens["prompt_input_ids"]
562
+
563
+ prompt_tokens["prompt_attention_mask"] = [1] + prompt_tokens["prompt_attention_mask"]
564
+ chosen_tokens["prompt_attention_mask"] = [1] + chosen_tokens["prompt_attention_mask"]
565
+ rejected_tokens["prompt_attention_mask"] = [1] + rejected_tokens["prompt_attention_mask"]
566
+
567
+ # add EOS token to end of answer
568
+ chosen_tokens["input_ids"].append(self.tokenizer.eos_token_id)
569
+ chosen_tokens["attention_mask"].append(1)
570
+
571
+ rejected_tokens["input_ids"].append(self.tokenizer.eos_token_id)
572
+ rejected_tokens["attention_mask"].append(1)
573
+
574
+ longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"]))
575
+
576
+ # if combined sequence is too long, truncate the prompt
577
+ for answer_tokens in [chosen_tokens, rejected_tokens, prompt_tokens]:
578
+ if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length:
579
+ if self.truncation_mode == "keep_start":
580
+ for k in ["prompt_input_ids", "prompt_attention_mask"]:
581
+ answer_tokens[k] = answer_tokens[k][: self.max_prompt_length]
582
+ elif self.truncation_mode == "keep_end":
583
+ for k in ["prompt_input_ids", "prompt_attention_mask"]:
584
+ answer_tokens[k] = answer_tokens[k][-self.max_prompt_length :]
585
+ else:
586
+ raise ValueError(f"Unknown truncation mode: {self.truncation_mode}")
587
+
588
+ # if that's still too long, truncate the response
589
+ for answer_tokens in [chosen_tokens, rejected_tokens]:
590
+ if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length:
591
+ for k in ["input_ids", "attention_mask"]:
592
+ answer_tokens[k] = answer_tokens[k][: self.max_length - self.max_prompt_length]
593
+
594
+ # Create labels
595
+ chosen_sequence_tokens = {k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"]}
596
+ rejected_sequence_tokens = {k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"]}
597
+ chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:]
598
+ chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [self.label_pad_token_id] * len(chosen_tokens["prompt_input_ids"])
599
+ rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:]
600
+ rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [self.label_pad_token_id] * len(rejected_tokens["prompt_input_ids"])
601
+
602
+ for k, toks in {
603
+ "chosen_": chosen_sequence_tokens,
604
+ "rejected_": rejected_sequence_tokens,
605
+ "": prompt_tokens,
606
+ }.items():
607
+ for type_key, tokens in toks.items():
608
+ if type_key == "token_type_ids":
609
+ continue
610
+ batch[f"{k}{type_key}"] = tokens
611
+
612
+ else:
613
+ chosen_tokens = self.tokenizer(chosen, truncation=True, max_length=self.max_target_length, add_special_tokens=True)
614
+ rejected_tokens = self.tokenizer(rejected, truncation=True, max_length=self.max_target_length, add_special_tokens=True)
615
+ prompt_tokens = self.tokenizer(prompt, truncation=True, max_length=self.max_prompt_length, add_special_tokens=True)
616
+
617
+ batch["chosen_labels"] = chosen_tokens["input_ids"]
618
+ batch["rejected_labels"] = rejected_tokens["input_ids"]
619
+ batch["prompt_input_ids"] = prompt_tokens["input_ids"]
620
+ batch["prompt_attention_mask"] = prompt_tokens["attention_mask"]
621
+
622
+ if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"):
623
+ batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(labels=batch["rejected_labels"])
624
+ batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(labels=batch["chosen_labels"])
625
+
626
+ return batch
627
+
628
+ @contextmanager
629
+ def null_ref_context(self):
630
+ """Context manager for handling null reference model (that is, peft adapter manipulation)."""
631
+ with self.accelerator.unwrap_model(self.model).disable_adapter() if self.is_peft_model and not self.ref_adapter_name else nullcontext():
632
+ if self.ref_adapter_name:
633
+ self.model.set_adapter(self.ref_adapter_name)
634
+ yield
635
+ if self.ref_adapter_name:
636
+ self.model.set_adapter(self.model_adapter_name or "default")
637
+
638
+ def compute_reference_log_probs(self, padded_batch: Dict) -> Dict:
639
+ """Computes log probabilities of the reference model for a single padded batch of a DPO specific dataset."""
640
+ compte_ref_context_manager = torch.cuda.amp.autocast if self._peft_has_been_casted_to_bf16 else nullcontext
641
+
642
+ # compute reference logps
643
+ with torch.no_grad(), compte_ref_context_manager():
644
+ if self.ref_model is None:
645
+ with self.null_ref_context():
646
+ (
647
+ reference_chosen_logps,
648
+ reference_rejected_logps,
649
+ _,
650
+ _,
651
+ ) = self.concatenated_forward(self.model, padded_batch)
652
+ else:
653
+ (
654
+ reference_chosen_logps,
655
+ reference_rejected_logps,
656
+ _,
657
+ _,
658
+ ) = self.concatenated_forward(self.ref_model, padded_batch)
659
+
660
+ return reference_chosen_logps, reference_rejected_logps
661
+
662
+ @staticmethod
663
+ def concatenated_inputs(
664
+ batch: Dict[str, Union[List, torch.LongTensor]],
665
+ is_encoder_decoder: bool = False,
666
+ label_pad_token_id: int = -100,
667
+ padding_value: int = 0,
668
+ device: Optional[torch.device] = None,
669
+ ) -> Dict[str, torch.LongTensor]:
670
+ """Concatenate the chosen and rejected inputs into a single tensor.
671
+
672
+ Args:
673
+ batch: A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors of shape (batch_size, sequence_length).
674
+ is_encoder_decoder: Whether the model is an encoder-decoder model.
675
+ label_pad_token_id: The label pad token id.
676
+ padding_value: The padding value to use for the concatenated inputs_ids.
677
+ device: The device for the concatenated inputs.
678
+
679
+ Returns:
680
+ A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'.
681
+ """
682
+ concatenated_batch = {}
683
+
684
+ if is_encoder_decoder:
685
+ max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1])
686
+ else:
687
+ max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1])
688
+
689
+ for k in batch:
690
+ # import pdb; pdb.set_trace()
691
+ if k.startswith("chosen") and isinstance(batch[k], torch.Tensor):
692
+ if "labels" in k or is_encoder_decoder:
693
+ pad_value = label_pad_token_id
694
+ elif k.endswith("_input_ids"):
695
+ pad_value = padding_value
696
+ elif k.endswith("_attention_mask"):
697
+ pad_value = 0
698
+ concatenated_key = k.replace("chosen", "concatenated")
699
+ concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value)
700
+ for k in batch:
701
+ if k.startswith("rejected") and isinstance(batch[k], torch.Tensor):
702
+ if "labels" in k or is_encoder_decoder:
703
+ pad_value = label_pad_token_id
704
+ elif k.endswith("_input_ids"):
705
+ pad_value = padding_value
706
+ elif k.endswith("_attention_mask"):
707
+ pad_value = 0
708
+ concatenated_key = k.replace("rejected", "concatenated")
709
+ concatenated_batch[concatenated_key] = torch.cat(
710
+ (
711
+ concatenated_batch[concatenated_key],
712
+ pad_to_length(batch[k], max_length, pad_value=pad_value),
713
+ ),
714
+ dim=0,
715
+ ).to(device=device)
716
+
717
+ if is_encoder_decoder:
718
+ concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device)
719
+ concatenated_batch["concatenated_attention_mask"] = batch["prompt_attention_mask"].repeat(2, 1).to(device=device)
720
+ # import pdb; pdb.set_trace()
721
+ # repeated_list = [
722
+ # batch['images'][0] * 2,
723
+ # batch['images'][1] * 2
724
+ # ]
725
+ concatenated_batch["concatenated_images"] = batch["images"] * 2
726
+ concatenated_batch["image_sizes"] = batch["image_sizes"] * 2
727
+ concatenated_batch["modalities"] = batch["modalities"] * 2
728
+ return concatenated_batch
729
+
730
+ def dpo_loss(
731
+ self,
732
+ policy_chosen_logps: torch.FloatTensor,
733
+ policy_rejected_logps: torch.FloatTensor,
734
+ reference_chosen_logps: torch.FloatTensor,
735
+ reference_rejected_logps: torch.FloatTensor,
736
+ ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
737
+ """Compute the DPO loss for a batch of policy and reference model log probabilities.
738
+
739
+ Args:
740
+ policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (batch_size,)
741
+ policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shape: (batch_size,)
742
+ reference_chosen_logps: Log probabilities of the reference model for the chosen responses. Shape: (batch_size,)
743
+ reference_rejected_logps: Log probabilities of the reference model for the rejected responses. Shape: (batch_size,)
744
+
745
+ Returns:
746
+ A tuple of three tensors: (losses, chosen_rewards, rejected_rewards).
747
+ The losses tensor contains the DPO loss for each example in the batch.
748
+ The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively.
749
+ """
750
+ pi_logratios = policy_chosen_logps - policy_rejected_logps
751
+ if self.reference_free:
752
+ ref_logratios = torch.tensor([0], dtype=pi_logratios.dtype, device=pi_logratios.device)
753
+ else:
754
+ ref_logratios = reference_chosen_logps - reference_rejected_logps
755
+
756
+ pi_logratios = pi_logratios.to(self.accelerator.device)
757
+ ref_logratios = ref_logratios.to(self.accelerator.device)
758
+ logits = pi_logratios - ref_logratios
759
+ # print(f"pi log ratios: {pi_logratios}")
760
+ # print(f"ref log ratios: {ref_logratios}")
761
+ # print(f"logits: {logits}")
762
+ # The beta is a temperature parameter for the DPO loss, typically something in the range of 0.1 to 0.5.
763
+ # We ignore the reference model as beta -> 0. The label_smoothing parameter encodes our uncertainty about the labels and
764
+ # calculates a conservative DPO loss.
765
+ if self.loss_type == "sigmoid":
766
+ losses = -F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing) - F.logsigmoid(-self.beta * logits) * self.label_smoothing
767
+ elif self.loss_type == "hinge":
768
+ losses = torch.relu(1 - self.beta * logits)
769
+ elif self.loss_type == "ipo":
770
+ # eqn (17) of the paper where beta is the regularization parameter for the IPO loss, denoted by tau in the paper.
771
+ losses = (logits - 1 / (2 * self.beta)) ** 2
772
+ elif self.loss_type == "kto_pair":
773
+ # eqn (7) of the HALOs paper
774
+ chosen_KL = (policy_chosen_logps - reference_chosen_logps).mean().clamp(min=0)
775
+ rejected_KL = (policy_rejected_logps - reference_rejected_logps).mean().clamp(min=0)
776
+
777
+ chosen_logratios = policy_chosen_logps - reference_chosen_logps
778
+ rejected_logratios = policy_rejected_logps - reference_rejected_logps
779
+ # As described in the KTO report, the KL term for chosen (rejected) is estimated using the rejected (chosen) half.
780
+ losses = torch.cat(
781
+ (
782
+ 1 - F.sigmoid(self.beta * (chosen_logratios - rejected_KL)),
783
+ 1 - F.sigmoid(self.beta * (chosen_KL - rejected_logratios)),
784
+ ),
785
+ 0,
786
+ )
787
+ else:
788
+ raise ValueError(f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'kto_pair']")
789
+
790
+ chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device) - reference_chosen_logps.to(self.accelerator.device)).detach()
791
+ rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device) - reference_rejected_logps.to(self.accelerator.device)).detach()
792
+
793
+ return losses, chosen_rewards, rejected_rewards
794
+
795
+ @staticmethod
796
+ def get_batch_logps(
797
+ logits: torch.FloatTensor,
798
+ labels: torch.LongTensor,
799
+ average_log_prob: bool = False,
800
+ label_pad_token_id: int = -100,
801
+ is_encoder_decoder: bool = False,
802
+ ) -> torch.FloatTensor:
803
+ """Compute the log probabilities of the given labels under the given logits.
804
+
805
+ Args:
806
+ logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size)
807
+ labels: Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are ignored. Shape: (batch_size, sequence_length)
808
+ average_log_prob: If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the log probabilities of the (non-masked) tokens.
809
+ label_pad_token_id: The label pad token id.
810
+ is_encoder_decoder: Whether the model is an encoder-decoder model.
811
+
812
+ Returns:
813
+ A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the given logits.
814
+ """
815
+ if logits.shape[:-1] != labels.shape:
816
+ raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.")
817
+
818
+ if not is_encoder_decoder:
819
+ labels = labels[:, 1:].clone()
820
+ logits = logits[:, :-1, :]
821
+ loss_mask = labels != label_pad_token_id
822
+
823
+ # dummy token; we'll ignore the losses on these tokens later
824
+ labels[labels == label_pad_token_id] = 0
825
+
826
+ per_token_logps = torch.gather(logits.log_softmax(-1), dim=2, index=labels.unsqueeze(2)).squeeze(2)
827
+
828
+ if average_log_prob:
829
+ return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1)
830
+ else:
831
+ return (per_token_logps * loss_mask).sum(-1)
832
+
833
+ def get_sft_loss(self, logits, labels):
834
+ # Shift so that tokens < n predict n
835
+ shift_logits = logits[..., :-1, :].contiguous()
836
+ shift_labels = labels[..., 1:].contiguous()
837
+ # Flatten the tokens
838
+ loss_fct = nn.CrossEntropyLoss()
839
+ shift_logits = shift_logits.view(-1, shift_logits.size(-1))
840
+ shift_labels = shift_labels.view(-1)
841
+ # Enable model/pipeline parallelism
842
+ shift_labels = shift_labels.to(shift_logits.device)
843
+ loss = loss_fct(shift_logits, shift_labels)
844
+ return loss
845
+
846
+ def concatenated_forward(self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]]) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
847
+ """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together.
848
+
849
+ We do this to avoid doing two forward passes, because it's faster for FSDP.
850
+ """
851
+ # import pdb; pdb.set_trace()
852
+ concatenated_batch = self.concatenated_inputs(
853
+ batch,
854
+ is_encoder_decoder=self.is_encoder_decoder,
855
+ label_pad_token_id=self.label_pad_token_id,
856
+ padding_value=self.padding_value,
857
+ device=self.accelerator.device,
858
+ )
859
+ len_chosen = batch["chosen_labels"].shape[0]
860
+
861
+ # import pdb; pdb.set_trace()
862
+ all_logits, new_labels = model(
863
+ concatenated_batch["concatenated_input_ids"],
864
+ attention_mask=concatenated_batch["concatenated_attention_mask"],
865
+ labels=concatenated_batch["concatenated_labels"],
866
+ images=concatenated_batch["concatenated_images"],
867
+ image_sizes=concatenated_batch["image_sizes"],
868
+ modalities=concatenated_batch["modalities"],
869
+ use_cache=False,
870
+ dpo_forward=True,
871
+ )
872
+ all_logits = all_logits.to(torch.float32)
873
+ all_logps = self.get_batch_logps(
874
+ all_logits,
875
+ new_labels,
876
+ average_log_prob=self.loss_type == "ipo",
877
+ is_encoder_decoder=self.is_encoder_decoder,
878
+ label_pad_token_id=self.label_pad_token_id,
879
+ )
880
+
881
+ chosen_logps = all_logps[:len_chosen]
882
+ rejected_logps = all_logps[len_chosen:]
883
+
884
+ # don't count image embeds logits
885
+ # loss_mask = new_labels != -100
886
+ # logits = [all_logits[i][loss_mask[i]] for i in range(loss_mask.shape[0])]
887
+ # chosen_logits = logits[:len_chosen]
888
+ # rejected_logits = logits[len_chosen:]
889
+ # chosen_logits = [l.detach().cpu().mean() for l in chosen_logits]
890
+ # rejected_logits = [l.detach().cpu().mean() for l in rejected_logits]
891
+ # chosen_logits = sum(chosen_logits)/len_chosen
892
+ # rejected_logits = sum(rejected_logits)/len_chosen
893
+
894
+ chosen_logits = all_logits[:len_chosen]
895
+ rejected_logits = all_logits[len_chosen:]
896
+
897
+ chosen_labels = new_labels[:len_chosen]
898
+ rejected_labels = new_labels[len_chosen:]
899
+
900
+ return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_labels, rejected_labels)
901
+
902
+ def get_batch_loss_metrics(
903
+ self,
904
+ model,
905
+ batch: Dict[str, Union[List, torch.LongTensor]],
906
+ train_eval: Literal["train", "eval"] = "train",
907
+ ):
908
+ """Compute the DPO loss and other metrics for the given batch of inputs for train or test.
909
+ CHANGE: 1. add sft loss
910
+ 2. all gather metrics
911
+ """
912
+ metrics = {}
913
+
914
+ (
915
+ policy_chosen_logps,
916
+ policy_rejected_logps,
917
+ policy_chosen_logits,
918
+ policy_rejected_logits,
919
+ chosen_labels,
920
+ rejected_labels,
921
+ ) = self.concatenated_forward(model, batch)
922
+
923
+ # if reference_chosen_logps and reference_rejected_logps in batch use them, otherwise use the reference model
924
+ if "reference_chosen_logps" in batch and "reference_rejected_logps" in batch:
925
+ reference_chosen_logps = batch["reference_chosen_logps"]
926
+ reference_rejected_logps = batch["reference_rejected_logps"]
927
+ else:
928
+ with torch.no_grad():
929
+ if self.ref_model is None:
930
+ with self.null_ref_context():
931
+ (
932
+ reference_chosen_logps,
933
+ reference_rejected_logps,
934
+ ) = self.concatenated_forward(
935
+ self.model, batch
936
+ )[:2]
937
+ else:
938
+ (
939
+ reference_chosen_logps,
940
+ reference_rejected_logps,
941
+ ) = self.concatenated_forward(
942
+ self.ref_model, batch
943
+ )[:2]
944
+
945
+ unscaled_dpo_losses, chosen_rewards, rejected_rewards = self.dpo_loss(
946
+ policy_chosen_logps,
947
+ policy_rejected_logps,
948
+ reference_chosen_logps,
949
+ reference_rejected_logps,
950
+ )
951
+ unscaled_dpo_losses = unscaled_dpo_losses.mean()
952
+ dpo_losses = unscaled_dpo_losses * self.dpo_alpha
953
+ unscaled_sft_loss = self.get_sft_loss(policy_chosen_logits, chosen_labels)
954
+ sft_loss = unscaled_sft_loss * self.gamma
955
+
956
+ # print(sft_loss.shape, dpo_losses.shape)
957
+ losses = dpo_losses + sft_loss
958
+ # losses = sft_loss # sft only
959
+ # losses = dpo_losses # dpo only
960
+ reward_accuracies = (chosen_rewards > rejected_rewards).float()
961
+
962
+ def all_gather_tensor(tensor):
963
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
964
+ tensor = tensor.detach()
965
+ gathered_tensor = [torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())]
966
+ torch.distributed.all_gather(gathered_tensor, tensor)
967
+ tensor = torch.cat(gathered_tensor, dim=0)
968
+ # else:
969
+ # print('not distributed')
970
+ return tensor
971
+
972
+ # gather chosen_rewards across devices
973
+ chosen_rewards = all_gather_tensor(chosen_rewards)
974
+ rejected_rewards = all_gather_tensor(rejected_rewards)
975
+ reward_accuracies = all_gather_tensor(reward_accuracies)
976
+ policy_chosen_logps = all_gather_tensor(policy_chosen_logps)
977
+ policy_rejected_logps = all_gather_tensor(policy_rejected_logps)
978
+ reference_chosen_logps = all_gather_tensor(reference_chosen_logps)
979
+ reference_rejected_logps = all_gather_tensor(reference_rejected_logps)
980
+
981
+ prefix = "eval_" if train_eval == "eval" else ""
982
+ metrics[f"{prefix}losses/dpo"] = unscaled_dpo_losses.cpu()
983
+ metrics[f"{prefix}losses/sft"] = unscaled_sft_loss.cpu()
984
+ metrics[f"{prefix}losses/total"] = losses.cpu()
985
+ metrics[f"{prefix}rewards/chosen"] = chosen_rewards.mean().cpu()
986
+ metrics[f"{prefix}rewards/rejected"] = rejected_rewards.mean().cpu()
987
+ metrics[f"{prefix}rewards/accuracies"] = reward_accuracies.mean().cpu()
988
+ metrics[f"{prefix}rewards/margins"] = (chosen_rewards - rejected_rewards).mean().cpu()
989
+ # policy logps
990
+ metrics[f"{prefix}logps/rejected"] = policy_rejected_logps.detach().mean().cpu()
991
+ metrics[f"{prefix}logps/chosen"] = policy_chosen_logps.detach().mean().cpu()
992
+ # policy logits (exclude image tokens)
993
+ # metrics[f"{prefix}logits/rejected"] =policy_rejected_logits
994
+ # metrics[f"{prefix}logits/chosen"] = policy_chosen_logits
995
+ # reference logps
996
+ metrics[f"{prefix}ref_logps/rejected"] = reference_rejected_logps.mean().cpu()
997
+ metrics[f"{prefix}ref_logps/chosen"] = reference_chosen_logps.mean().cpu()
998
+
999
+ # metrics all pick .4 digits
1000
+ # for k in metrics:
1001
+ # metrics[k] = round(metrics[k].item(), 4)
1002
+
1003
+ return losses, metrics
1004
+
1005
+ def compute_loss(
1006
+ self,
1007
+ model: Union[PreTrainedModel, nn.Module],
1008
+ inputs: Dict[str, Union[torch.Tensor, Any]],
1009
+ return_outputs=False,
1010
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]:
1011
+ if not self.use_dpo_data_collator:
1012
+ warnings.warn(
1013
+ "compute_loss is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than "
1014
+ "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator"
1015
+ )
1016
+
1017
+ compute_loss_context_manager = torch.cuda.amp.autocast if self._peft_has_been_casted_to_bf16 else nullcontext
1018
+
1019
+ with compute_loss_context_manager():
1020
+ loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train")
1021
+
1022
+ # force log the metrics
1023
+ self.store_metrics(metrics, train_eval="train")
1024
+
1025
+ if return_outputs:
1026
+ return (loss, metrics)
1027
+ return loss
1028
+
1029
+ def get_batch_samples(self, model, batch: Dict[str, torch.LongTensor]) -> Tuple[str, str]:
1030
+ """Generate samples from the model and reference model for the given batch of inputs."""
1031
+
1032
+ # If one uses `generate_during_eval` with peft + bf16, we need to explictly call generate with
1033
+ # the torch cuda amp context manager as some hidden states are silently casted to full precision.
1034
+ generate_context_manager = nullcontext if not self._peft_has_been_casted_to_bf16 else torch.cuda.amp.autocast
1035
+
1036
+ with generate_context_manager():
1037
+ policy_output = model.generate(
1038
+ input_ids=batch["prompt_input_ids"],
1039
+ attention_mask=batch["prompt_attention_mask"],
1040
+ max_length=self.max_length,
1041
+ do_sample=True,
1042
+ pad_token_id=self.tokenizer.pad_token_id,
1043
+ )
1044
+
1045
+ # if reference_output in batch use that otherwise use the reference model
1046
+ if "reference_output" in batch:
1047
+ reference_output = batch["reference_output"]
1048
+ else:
1049
+ if self.ref_model is None:
1050
+ with self.null_ref_context():
1051
+ reference_output = self.model.generate(
1052
+ input_ids=batch["prompt_input_ids"],
1053
+ attention_mask=batch["prompt_attention_mask"],
1054
+ max_length=self.max_length,
1055
+ do_sample=True,
1056
+ pad_token_id=self.tokenizer.pad_token_id,
1057
+ )
1058
+ else:
1059
+ reference_output = self.ref_model.generate(
1060
+ input_ids=batch["prompt_input_ids"],
1061
+ attention_mask=batch["prompt_attention_mask"],
1062
+ max_length=self.max_length,
1063
+ do_sample=True,
1064
+ pad_token_id=self.tokenizer.pad_token_id,
1065
+ )
1066
+
1067
+ policy_output = pad_to_length(policy_output, self.max_length, self.tokenizer.pad_token_id)
1068
+ policy_output_decoded = self.tokenizer.batch_decode(policy_output, skip_special_tokens=True)
1069
+
1070
+ reference_output = pad_to_length(reference_output, self.max_length, self.tokenizer.pad_token_id)
1071
+ reference_output_decoded = self.tokenizer.batch_decode(reference_output, skip_special_tokens=True)
1072
+
1073
+ return policy_output_decoded, reference_output_decoded
1074
+
1075
+ def prediction_step(
1076
+ self,
1077
+ model: Union[PreTrainedModel, nn.Module],
1078
+ inputs: Dict[str, Union[torch.Tensor, Any]],
1079
+ prediction_loss_only: bool,
1080
+ ignore_keys: Optional[List[str]] = None,
1081
+ ):
1082
+ if not self.use_dpo_data_collator:
1083
+ warnings.warn(
1084
+ "prediction_step is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than "
1085
+ "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator"
1086
+ )
1087
+ if ignore_keys is None:
1088
+ if hasattr(model, "config"):
1089
+ ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", [])
1090
+ else:
1091
+ ignore_keys = []
1092
+
1093
+ prediction_context_manager = torch.cuda.amp.autocast if self._peft_has_been_casted_to_bf16 else nullcontext
1094
+
1095
+ with torch.no_grad(), prediction_context_manager():
1096
+ loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval")
1097
+
1098
+ # force log the metrics
1099
+ self.store_metrics(metrics, train_eval="eval")
1100
+
1101
+ if prediction_loss_only:
1102
+ return (loss.detach(), None, None)
1103
+
1104
+ # logits for the chosen and rejected samples from model
1105
+ logits_dict = {
1106
+ "eval_logits/chosen": metrics["eval_logits/chosen"],
1107
+ "eval_logits/rejected": metrics["eval_logits/rejected"],
1108
+ }
1109
+ logits = tuple(v.unsqueeze(dim=0) for k, v in logits_dict.items() if k not in ignore_keys)
1110
+ logits = torch.stack(logits).mean(axis=1).to(self.accelerator.device)
1111
+ labels = torch.zeros(logits.shape[0], device=self.accelerator.device)
1112
+
1113
+ return (loss.detach(), logits, labels)
1114
+
1115
+ def store_metrics(self, metrics: Dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None:
1116
+ for key, value in metrics.items():
1117
+ self._stored_metrics[train_eval][key].append(value)
1118
+
1119
+ def evaluation_loop(
1120
+ self,
1121
+ dataloader: DataLoader,
1122
+ description: str,
1123
+ prediction_loss_only: Optional[bool] = None,
1124
+ ignore_keys: Optional[List[str]] = None,
1125
+ metric_key_prefix: str = "eval",
1126
+ ) -> EvalLoopOutput:
1127
+ """
1128
+ Overriding built-in evaluation loop to store metrics for each batch.
1129
+ Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`.
1130
+
1131
+ Works both with or without labels.
1132
+ """
1133
+
1134
+ # Sample and save to game log if requested (for one batch to save time)
1135
+ if self.generate_during_eval:
1136
+ # Generate random indices within the range of the total number of samples
1137
+ num_samples = len(dataloader.dataset)
1138
+ random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size)
1139
+
1140
+ # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader
1141
+ random_batch_dataset = dataloader.dataset.select(random_indices)
1142
+ random_batch = self.data_collator(random_batch_dataset)
1143
+ random_batch = self._prepare_inputs(random_batch)
1144
+
1145
+ policy_output_decoded, ref_output_decoded = self.get_batch_samples(self.model, random_batch)
1146
+
1147
+ self.log(
1148
+ {
1149
+ "game_log": wandb.Table(
1150
+ columns=["Prompt", "Policy", "Ref Model"],
1151
+ rows=[[prompt, pol[len(prompt) :], ref[len(prompt) :]] for prompt, pol, ref in zip(random_batch["prompt"], policy_output_decoded, ref_output_decoded)],
1152
+ )
1153
+ }
1154
+ )
1155
+ self.state.log_history.pop()
1156
+
1157
+ # Base evaluation
1158
+ initial_output = super().evaluation_loop(dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix)
1159
+
1160
+ return initial_output
1161
+
1162
+ def log(self, logs: Dict[str, float]) -> None:
1163
+ """
1164
+ Log `logs` on the various objects watching training, including stored metrics.
1165
+
1166
+ Args:
1167
+ logs (`Dict[str, float]`):
1168
+ The values to log.
1169
+ """
1170
+ # logs either has 'loss' or 'eval_loss'
1171
+ train_eval = "train" if "loss" in logs else "eval"
1172
+ # Add averaged stored metrics to logs
1173
+ for key, metrics in self._stored_metrics[train_eval].items():
1174
+ logs[key] = torch.tensor(metrics).mean().item()
1175
+ del self._stored_metrics[train_eval]
1176
+ return super().log(logs)
1177
+
1178
+ @wraps(Trainer.push_to_hub)
1179
+ def push_to_hub(self, commit_message: Optional[str] = "End of training", blocking: bool = True, **kwargs) -> str:
1180
+ """
1181
+ Overwrite the `push_to_hub` method in order to force-add the tag "sft" when pushing the
1182
+ model on the Hub. Please refer to `~transformers.Trainer.push_to_hub` for more details.
1183
+ """
1184
+ kwargs = trl_sanitze_kwargs_for_tagging(model=self.model, tag_names=self._tag_names, kwargs=kwargs)
1185
+
1186
+ return super().push_to_hub(commit_message=commit_message, blocking=blocking, **kwargs)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/iterative_sft_trainer.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import warnings
15
+ from typing import Callable, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ from datasets import Dataset
19
+ from torch.utils.data import DataLoader
20
+ from transformers import (
21
+ DataCollator,
22
+ DataCollatorForLanguageModeling,
23
+ DataCollatorForSeq2Seq,
24
+ PreTrainedModel,
25
+ PreTrainedTokenizerBase,
26
+ Trainer,
27
+ TrainingArguments,
28
+ )
29
+ from transformers.trainer_utils import EvalLoopOutput
30
+
31
+ from ..core import PPODecorators
32
+ from ..import_utils import is_peft_available
33
+
34
+
35
+ if is_peft_available():
36
+ from peft import PeftModel
37
+
38
+
39
+ class IterativeSFTTrainer(Trainer):
40
+ """
41
+ The IterativeSFTTrainer can be used to finetune models with methods that requires some steps between optimization.
42
+
43
+ Attributes:
44
+ **model** (`PreTrainedModel`) -- Model to be optimized, either an 'AutoModelForCausalLM' or an 'AutoModelForSeq2SeqLM'.
45
+ Check the documentation of `PreTrainedModel` for more details.
46
+ **args** (`transformers.TrainingArguments`): -- The arguments to use for training.
47
+ **tokenizer** (`PreTrainedTokenizerBase`) -- Tokenizer to be used for encoding the
48
+ data. Check the documentation of `transformers.PreTrainedTokenizer` and
49
+ `transformers.PreTrainedTokenizerFast` for more details.
50
+ **optimizers** (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): -- The optimizer and scheduler to use for training.
51
+ **data_collator** (Union[DataCollatorForLanguageModeling, DataCollatorForSeq2Seq], *optional*) -- Data collator to be used for training and
52
+ passed along the dataloader.
53
+ **eval_dataset** (`datasets.Dataset`): The dataset to use for evaluation.
54
+ **max_length** (`int`, defaults to `None`): -- The maximum length of the input.
55
+ **truncation_mode** (`str`, defaults to `keep_end`): -- The truncation mode to use, either `keep_end` or `keep_start`.
56
+ **preprocess_logits_for_metrics** (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): -- The function to use to preprocess the logits before computing the metrics.
57
+ **compute_metrics** (`Callable[[EvalPrediction], Dict]`, *optional*): -- The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to metric values.
58
+ **optimize_device_cache ** (`bool`, *optional*, defaults to `False`) -- Optimize CUDA cache for slightly more memory-efficient training.
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ model: PreTrainedModel = None,
64
+ args: TrainingArguments = None,
65
+ tokenizer: PreTrainedTokenizerBase = None,
66
+ optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (
67
+ None,
68
+ None,
69
+ ),
70
+ data_collator: Optional[DataCollator] = None,
71
+ eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None,
72
+ max_length: Optional[int] = None,
73
+ truncation_mode: Optional[str] = "keep_end",
74
+ preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
75
+ compute_metrics: Optional[Callable[[EvalLoopOutput], Dict]] = None,
76
+ optimize_device_cache: Optional[bool] = False,
77
+ ):
78
+ # Step 0: check positional arguments validity
79
+ if not isinstance(tokenizer, (PreTrainedTokenizerBase)):
80
+ raise ValueError(f"tokenizer must be a PreTrainedTokenizerBase like a PreTrainedTokenizer or a PreTrainedTokenizerFast, got {type(tokenizer)}")
81
+ if not isinstance(model, PreTrainedModel):
82
+ raise ValueError(f"model must be a PreTrainedModel, got {type(model)}")
83
+ if not model.can_generate():
84
+ warnings.warn(f"The current model class {type(model)} is not compatible with `.generate()`" "Please make sure that this is intended.")
85
+ if optimizers[1] is None and args.max_steps == -1:
86
+ raise ValueError("When no scheduler is provided, you need to set the total number of training steps to perform `max_steps`")
87
+
88
+ self.is_encoder_decoder = getattr(model.config, "is_encoder_decoder", False)
89
+ self.is_peft_model = is_peft_available() and isinstance(model, PeftModel)
90
+
91
+ self.tokenizer = tokenizer
92
+
93
+ if data_collator is None:
94
+ if self.is_encoder_decoder:
95
+ warnings.warn("No data collator is provided. Using 'DataCollatorForSeq2Seq' with" "'labels_pad_token_id' set to '-100' and 'pad_to_multiple_of' set to 8.")
96
+ self.data_collator = DataCollatorForSeq2Seq(tokenizer, label_pad_token_id=-100, pad_to_multiple_of=8)
97
+ else:
98
+ warnings.warn("No data collator is provided. Using 'DataCollatorForLanguageModeling'")
99
+ self.data_collator = DataCollatorForLanguageModeling(self.tokenizer, mlm=False)
100
+ else:
101
+ self.data_collator = data_collator
102
+
103
+ self.max_length = max_length
104
+ self.truncation_mode = truncation_mode
105
+ self.optimize_device_cache = optimize_device_cache
106
+
107
+ super().__init__(
108
+ model=model,
109
+ args=args,
110
+ data_collator=self.data_collator,
111
+ eval_dataset=eval_dataset,
112
+ tokenizer=tokenizer,
113
+ compute_metrics=compute_metrics,
114
+ optimizers=optimizers,
115
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
116
+ )
117
+
118
+ self.create_optimizer_and_scheduler(self.args.max_steps)
119
+
120
+ # prepare model, optimizer and lr_scheduler
121
+ self.model, self.optimizer, self.lr_scheduler = self.accelerator.prepare(self.model, self.optimizer, self.lr_scheduler)
122
+
123
+ self.tokenizer.truncation_side = "left" if self.truncation_mode == "keep_end" else "right"
124
+
125
+ if not hasattr(self, "accelerator"):
126
+ raise AttributeError("Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`.")
127
+
128
+ PPODecorators.optimize_device_cache = self.optimize_device_cache
129
+
130
+ def prepare_model_inputs(self, input_ids: torch.Tensor, attention_mask: torch.Tensor, labels: torch.Tensor):
131
+ if attention_mask is None:
132
+ attention_mask = [torch.ones_like(ids) for ids in input_ids]
133
+
134
+ if self.is_encoder_decoder:
135
+ input_data = self.data_collator([{"input_ids": ids, "attention_mask": att, "labels": lab} for ids, att, lab in zip(input_ids, attention_mask, labels)]).to(self.model.device)
136
+
137
+ input_data.pop("decoder_input_ids", None) # This is directly computed inside the model
138
+
139
+ input_data["labels"][input_data["labels"] == self.tokenizer.pad_token_id] = -100
140
+
141
+ else:
142
+ input_data = self.data_collator([{"input_ids": ids, "attention_mask": att} for ids, att in zip(input_ids, attention_mask)]).to(self.model.device)
143
+
144
+ # truncate in case the user has provided input_ids, attention_mask and labels
145
+ if self.max_length is not None:
146
+ if self.truncation_mode == "keep_start":
147
+ input_data = {k: v[: self.max_length] for k, v in input_data.items()}
148
+ elif self.truncation_mode == "keep_end":
149
+ input_data = {k: v[-self.max_length :] for k, v in input_data.items()}
150
+ else:
151
+ raise ValueError(f"Unknown truncation mode: {self.truncation_mode}")
152
+
153
+ return input_data
154
+
155
+ @staticmethod
156
+ def _step_safety_checker(
157
+ input_ids: List[torch.LongTensor],
158
+ attention_mask: List[torch.LongTensor],
159
+ labels: List[torch.LongTensor],
160
+ texts: List[str],
161
+ texts_labels: List[str],
162
+ ):
163
+ """
164
+ Check if the input data is valid for training.
165
+
166
+ Args:
167
+ input_ids (List[`torch.LongTensor`]):
168
+ List of tensors containing the input_ids
169
+ attention_mask (List[`torch.LongTensor`]):
170
+ List of tensors containing the attention_mask
171
+ labels (List[`torch.FloatTensor`]):
172
+ List of tensors containing the labels
173
+ texts (List[`str`]):
174
+ List of string containing the text input.
175
+ texts_labels (List[`str`]):
176
+ List of string containing the text labels.
177
+ Returns:
178
+ `tuple`: The input data.
179
+ """
180
+ if texts is None:
181
+ if attention_mask is None:
182
+ for name, tensor_list in zip(["input_ids", "labels"], [input_ids, labels]):
183
+ if not isinstance(tensor_list, list):
184
+ raise ValueError(f"{name} must be a list of tensors - got {type(tensor_list)}")
185
+ if not isinstance(tensor_list[0], torch.Tensor):
186
+ raise ValueError(f"Elements in {name} must be tensors - got {type(tensor_list[0])}")
187
+ else:
188
+ for name, tensor_list in zip(["input_ids", "attention_mask", "labels"], [input_ids, attention_mask, labels]):
189
+ if not isinstance(tensor_list, list):
190
+ raise ValueError(f"{name} must be a list of tensors - got {type(tensor_list)}")
191
+ if not isinstance(tensor_list[0], torch.Tensor):
192
+ raise ValueError(f"Elements in {name} must be tensors - got {type(tensor_list[0])}")
193
+ else:
194
+ if not isinstance(texts, list):
195
+ raise ValueError(f"'text' must be a list of strings - got {type(texts)}")
196
+ if not isinstance(texts[0], str):
197
+ raise ValueError(f"Elements in 'text' must be strings - got {type(texts[0])}")
198
+ if texts_labels is not None:
199
+ if not isinstance(texts_labels, list):
200
+ raise ValueError(f"'text_labels' must be a list of strings - got {type(texts_labels)}")
201
+ if not isinstance(texts_labels[0], str):
202
+ raise ValueError(f"Elements in 'text_labels' must be strings - got {type(texts_labels[0])}")
203
+
204
+ return input_ids, attention_mask, labels, texts, texts_labels
205
+
206
+ @PPODecorators.empty_device_cache()
207
+ def step(
208
+ self,
209
+ input_ids: Optional[List[torch.LongTensor]] = None,
210
+ attention_mask: Optional[List[torch.LongTensor]] = None,
211
+ labels: Optional[List[torch.LongTensor]] = None,
212
+ texts: Optional[List[str]] = None,
213
+ texts_labels: Optional[List[str]] = None,
214
+ ):
215
+ """
216
+ Run an optimisation step given a list of input_ids, attention_mask, and labels or a list of text and text_labels.
217
+ Args:
218
+ input_ids (List[`torch.LongTensor`]):
219
+ List of tensors containing the input_ids (if not provided, text will be used)
220
+ attention_mask (List[`torch.LongTensor`], , *optional*):
221
+ List of tensors containing the attention_mask
222
+ labels (List[`torch.FloatTensor`], *optional*):
223
+ List of tensors containing the labels (if set to None, will default to input_ids)
224
+ texts (List[`str`], *optional*):
225
+ List of strings containing the text input (if not provided, input_ids will directly be used)
226
+ texts_labels (List[`str`], *optional*):
227
+ List of strings containing the text labels (if set to None, will default to text)
228
+ Returns:
229
+ `dict[str, Any]`: A summary of the training statistics
230
+ """
231
+ self.model.train()
232
+
233
+ if self.state.global_step == 0:
234
+ self.tr_loss = torch.tensor(0.0).to(self.args.device)
235
+ self._globalstep_last_logged = self.state.global_step
236
+
237
+ if input_ids is None and texts is None:
238
+ raise ValueError("Step should include `input_ids` or `texts` as keyword arguments.")
239
+ elif input_ids is not None and texts is not None:
240
+ warnings.warn("Both 'input_ids' and 'texts' are provided. 'input_ids' will be overwritten using inputs provided by the 'texts' keyword argument.")
241
+
242
+ if labels is None and texts_labels is None and self.is_encoder_decoder:
243
+ raise ValueError("No 'labels' or 'text_labels' are provided. When using an encoder-decoder architecture, 'labels' or 'text_labels' must be passed.")
244
+
245
+ input_ids, attention_mask, labels, texts, texts_labels = self._step_safety_checker(input_ids, attention_mask, labels, texts, texts_labels)
246
+
247
+ if texts is not None:
248
+ model_inputs = self.tokenizer(texts, max_length=self.max_length, truncation=True, padding=True, return_tensors="pt")
249
+
250
+ input_ids, attention_mask = model_inputs["input_ids"], model_inputs["attention_mask"]
251
+
252
+ if texts_labels is not None:
253
+ labels = self.tokenizer(texts, max_length=self.max_length, truncation=True, padding=True, return_tensors="pt")["input_ids"]
254
+
255
+ if labels is None:
256
+ warnings.warn("No labels are provided. Setting labels to input_ids")
257
+ labels = input_ids
258
+
259
+ model_inputs = self.prepare_model_inputs(input_ids, attention_mask, labels)
260
+
261
+ model_inputs_names = list(model_inputs.keys())
262
+
263
+ batch_dict = {}
264
+ batch_dict.update(model_inputs)
265
+
266
+ def collator(data):
267
+ return_dict = dict()
268
+ for key in data[0]:
269
+ if key in ["input_ids", "attention_mask", "labels"]:
270
+ return_dict[key] = torch.stack([d[key] for d in data]).to(self.model.device)
271
+ return return_dict
272
+
273
+ batch_data = Dataset.from_dict(batch_dict)
274
+ batch_data.set_format("torch")
275
+
276
+ step_dataloader = DataLoader(
277
+ batch_data,
278
+ batch_size=self.args.per_device_train_batch_size,
279
+ shuffle=True,
280
+ collate_fn=collator,
281
+ )
282
+
283
+ for _, batch in enumerate(step_dataloader):
284
+ with self.accelerator.accumulate(self.model):
285
+ model_inputs = {k: batch[k] for k in model_inputs_names}
286
+ loss = self.compute_loss(self.model, model_inputs)
287
+
288
+ if self.args.n_gpu > 1:
289
+ loss = loss.mean()
290
+
291
+ tr_loss_step = loss.detach()
292
+
293
+ self.accelerator.backward(loss)
294
+
295
+ if self.accelerator.sync_gradients and self.args.max_grad_norm is not None:
296
+ self.accelerator.clip_grad_norm_(
297
+ self.model.parameters(),
298
+ self.args.max_grad_norm,
299
+ )
300
+
301
+ self.optimizer.step()
302
+ self.optimizer.zero_grad()
303
+ if self.lr_scheduler is not None:
304
+ self.lr_scheduler.step()
305
+
306
+ self.state.global_step += 1
307
+
308
+ # update stats etc
309
+ self.tr_loss += tr_loss_step
310
+
311
+ self._maybe_log_save_evaluate()
312
+
313
+ def _maybe_log_save_evaluate(self):
314
+ # check if eval is required
315
+ if self.args.eval_steps is not None:
316
+ if self.state.global_step % self.args.eval_steps == 0 and self.state.global_step != 0:
317
+ self.evaluate(self.eval_dataset)
318
+
319
+ # check if logging is required
320
+ if self.args.logging_steps is not None:
321
+ if self.state.global_step % self.args.logging_steps == 0 and self.state.global_step != 0:
322
+ logs: Dict[str, float] = {}
323
+
324
+ tr_loss_scalar = self._nested_gather(self.tr_loss).mean().item()
325
+
326
+ # reset tr_loss to zero
327
+ self.tr_loss -= self.tr_loss
328
+
329
+ logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)
330
+ logs["learning_rate"] = self._get_learning_rate()
331
+
332
+ self._globalstep_last_logged = self.state.global_step
333
+
334
+ self.log(logs)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/model_config.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+ from typing import List, Optional
3
+
4
+ from ..core import flatten_dict
5
+
6
+
7
+ @dataclass
8
+ class ModelConfig:
9
+ """
10
+ Arguments which define the model and tokenizer to load.
11
+ """
12
+
13
+ model_name_or_path: Optional[str] = field(
14
+ default=None,
15
+ metadata={"help": ("The model checkpoint for weights initialization.")},
16
+ )
17
+ model_revision: str = field(
18
+ default="main",
19
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
20
+ )
21
+ torch_dtype: Optional[str] = field(
22
+ default=None,
23
+ metadata={
24
+ "help": ("Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the " "dtype will be automatically derived from the model's weights."),
25
+ "choices": ["auto", "bfloat16", "float16", "float32"],
26
+ },
27
+ )
28
+ trust_remote_code: bool = field(default=False, metadata={"help": "Trust remote code when loading a model."})
29
+ attn_implementation: Optional[str] = field(
30
+ default=None,
31
+ metadata={"help": ("Which attention implementation to use; you can run --attn_implementation=flash_attention_2, in which case you must install this manually by running `pip install flash-attn --no-build-isolation`")},
32
+ )
33
+ use_peft: bool = field(
34
+ default=False,
35
+ metadata={"help": ("Whether to use PEFT or not for training.")},
36
+ )
37
+ lora_r: Optional[int] = field(
38
+ default=16,
39
+ metadata={"help": ("LoRA R value.")},
40
+ )
41
+ lora_alpha: Optional[int] = field(
42
+ default=32,
43
+ metadata={"help": ("LoRA alpha.")},
44
+ )
45
+ lora_dropout: Optional[float] = field(
46
+ default=0.05,
47
+ metadata={"help": ("LoRA dropout.")},
48
+ )
49
+ lora_target_modules: Optional[List[str]] = field(
50
+ default=None,
51
+ metadata={"help": ("LoRA target modules.")},
52
+ )
53
+ lora_modules_to_save: Optional[List[str]] = field(
54
+ default=None,
55
+ metadata={"help": ("Model layers to unfreeze & train")},
56
+ )
57
+ load_in_8bit: bool = field(default=False, metadata={"help": "use 8 bit precision for the base model - works only with LoRA"})
58
+ load_in_4bit: bool = field(default=False, metadata={"help": "use 4 bit precision for the base model - works only with LoRA"})
59
+
60
+ bnb_4bit_quant_type: Optional[str] = field(default="nf4", metadata={"help": "precise the quantization type (fp4 or nf4)"})
61
+ use_bnb_nested_quant: bool = field(default=False, metadata={"help": "use nested quantization"})
62
+
63
+ def to_dict(self):
64
+ output_dict = {}
65
+ for key, value in self.__dict__.items():
66
+ output_dict[key] = value
67
+ return flatten_dict(output_dict)
68
+
69
+ def __post_init__(self):
70
+ if self.load_in_8bit and self.load_in_4bit:
71
+ raise ValueError("You can't use 8 bit and 4 bit precision at the same time")
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/ppo_config.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import json
15
+ import os
16
+ import sys
17
+ import warnings
18
+ from dataclasses import dataclass, field
19
+ from typing import Literal, Optional
20
+
21
+ import numpy as np
22
+ import tyro
23
+ from typing_extensions import Annotated
24
+
25
+ from trl.trainer.utils import exact_div
26
+
27
+ from ..core import flatten_dict
28
+ from ..import_utils import is_wandb_available
29
+
30
+
31
+ JSONDict = Annotated[Optional[dict], tyro.conf.arg(metavar="JSON", constructor=json.loads)]
32
+
33
+
34
+ @dataclass
35
+ class PPOConfig:
36
+ """
37
+ Configuration class for PPOTrainer
38
+ """
39
+
40
+ # common parameters
41
+ exp_name: str = os.path.basename(sys.argv[0])[: -len(".py")]
42
+ """the name of this experiment (by default is the file name without the extension name)"""
43
+ seed: int = 0
44
+ """Seed value for random generations"""
45
+ log_with: Optional[Literal["wandb", "tensorboard"]] = None
46
+ """Log with either 'wandb' or 'tensorboard', check https://huggingface.co/docs/accelerate/usage_guides/tracking for more details"""
47
+ task_name: Optional[str] = None
48
+ """Name of task to use - used only for tracking purposes"""
49
+ model_name: Optional[str] = "gpt2"
50
+ """Name of model to use - used only for tracking purposes"""
51
+ query_dataset: Optional[str] = "imdb"
52
+ """Name of dataset to query - used only for tracking purposes"""
53
+ reward_model: Optional[str] = "sentiment-analysis:lvwerra/distilbert-imdb"
54
+ """The reward model to use - used only for tracking purposes"""
55
+ remove_unused_columns: bool = True
56
+ """Remove unused columns from the dataset if `datasets.Dataset` is used"""
57
+ tracker_kwargs: JSONDict = field(default_factory=dict)
58
+ """Keyword arguments for the tracker (e.g. python ppo.py --tracker_kwargs='{"wandb": {"entity": "my_wandb_entity", "name": "my_exp_name"}}'"""
59
+ accelerator_kwargs: JSONDict = field(default_factory=dict)
60
+ """Keyword arguments for the accelerator"""
61
+ project_kwargs: JSONDict = field(default_factory=dict)
62
+ """Keyword arguments for the accelerator project config (e.g. `logging_dir`)"""
63
+ tracker_project_name: str = "trl"
64
+ """Name of project to use for tracking"""
65
+ push_to_hub_if_best_kwargs: JSONDict = field(default_factory=dict)
66
+ """Keyword arguments for pushing model to the hub during training (e.g. repo_id)"""
67
+
68
+ # hyperparameters
69
+ steps: int = 20000
70
+ """Number of training steps"""
71
+ learning_rate: float = 1.41e-5
72
+ """Adam learning rate"""
73
+ adap_kl_ctrl: bool = True
74
+ """Use adaptive KL control, otherwise linear"""
75
+ init_kl_coef: Optional[float] = 0.2
76
+ """Initial KL penalty coefficient (used for adaptive and linear control)"""
77
+ kl_penalty: Literal["kl", "abs", "mse", "full"] = "kl"
78
+ """kl penalty options: 'kl': model_logp - ref_logp, 'abs': abs(kl), 'mse': mean squared error mse(kl) and 'full': the actual kl for all tokens in the distribution"""
79
+ target: Optional[float] = 6
80
+ """Target KL value for adaptive KL control"""
81
+ horizon: Optional[float] = 10000
82
+ """Horizon for adaptive KL control"""
83
+ gamma: float = 1
84
+ """Gamma parameter for advantage calculation"""
85
+ lam: float = 0.95
86
+ """Lambda parameter for advantage calculation"""
87
+ cliprange: float = 0.2
88
+ """Range for clipping in PPO policy gradient loss"""
89
+ cliprange_value: float = 0.2
90
+ """Range for clipping values in loss calculation"""
91
+ vf_coef: float = 0.1
92
+ """Scaling factor for value loss"""
93
+ batch_size: int = 128
94
+ """Number of samples per optimisation step"""
95
+ forward_batch_size: Optional[int] = None
96
+ """DEPRECATED: use `mini_batch_size` instead, which does the same thing."""
97
+ mini_batch_size: int = 128
98
+ """Number of samples optimized in each mini batch"""
99
+ gradient_accumulation_steps: int = 1
100
+ """The number of gradient accumulation steps"""
101
+ world_size: tyro.conf.Suppress[int] = None
102
+ """The world size for distributed training"""
103
+ ppo_epochs: int = 4
104
+ """Number of optimisation epochs per batch of samples"""
105
+ max_grad_norm: Optional[float] = None
106
+ """Maximum gradient norm for gradient clipping"""
107
+ optimize_cuda_cache: Optional[bool] = None
108
+ """DEPRECATED: use `optimize_device_cache` instead, which does the same thing."""
109
+ optimize_device_cache: Optional[bool] = False
110
+ """Optimize device cache for slightly more memory-efficient training"""
111
+ early_stopping: bool = False
112
+ """Whether to stop the PPO optimization loop early is the KL too high"""
113
+ target_kl: float = 1
114
+ """Stop early if we exceed this value by over 50%"""
115
+ compare_steps: int = 1
116
+ """Number of steps between comparison of the current reward with the best seen so far"""
117
+ ratio_threshold: float = 10.0
118
+ """Skip mini-batches with high PPO ratios that can cause loss spikes"""
119
+ use_score_scaling: bool = False
120
+ """Use score scaling"""
121
+ use_score_norm: bool = False
122
+ """Use score normalization. Only applicable if use_score_scaling is True"""
123
+ score_clip: Optional[float] = None
124
+ """Score clipping"""
125
+ whiten_rewards: bool = False
126
+ """Whiten the rewards before compute advantages"""
127
+
128
+ # computed hyperparameters at runtime; we use `tyro.conf.Suppress` to hide them from the help text
129
+ is_encoder_decoder: Optional[tyro.conf.Suppress[bool]] = None
130
+ """TO BE FILLED In RUNTIME: Whether the model is an encoder-decoder model"""
131
+ is_peft_model: Optional[tyro.conf.Suppress[bool]] = None
132
+ """TO BE FILLED In RUNTIME: Whether the model is a PEFT model"""
133
+ backward_batch_size: tyro.conf.Suppress[int] = None
134
+ """TO BE FILLED In RUNTIME: Number of samples optimized in an `optimizer.step()` call"""
135
+ global_backward_batch_size: tyro.conf.Suppress[int] = None
136
+ """TO BE FILLED In RUNTIME: the effective `backward_batch_size` across all processes"""
137
+ global_batch_size: tyro.conf.Suppress[int] = None
138
+ """TO BE FILLED In RUNTIME: the effective `batch_size` across all processes"""
139
+
140
+ if optimize_cuda_cache is not None:
141
+ warnings.warn("The `optimize_cuda_cache` argument will be deprecated soon, please use `optimize_device_cache` instead.")
142
+ optimize_device_cache = optimize_cuda_cache
143
+ else:
144
+ optimize_device_cache = False
145
+
146
+ def __post_init__(self):
147
+ if self.forward_batch_size is not None:
148
+ warnings.warn(
149
+ "Note that using `forward_batch_size` is deprecated, use `mini_batch_size` instead. By setting it you overwrite `mini_batch_size` which affects both the batch size during forward passes and also the mini batch size for PPO optimization."
150
+ )
151
+ self.mini_batch_size = self.forward_batch_size
152
+
153
+ self.backward_batch_size = self.mini_batch_size * self.gradient_accumulation_steps
154
+ exact_div(
155
+ self.batch_size,
156
+ self.backward_batch_size,
157
+ "`batch_size`",
158
+ "`mini_batch_size * gradient_accumulation_steps`",
159
+ "`batch_size` must be a multiple of `mini_batch_size * gradient_accumulation_steps`",
160
+ )
161
+
162
+ # check if wandb is installed
163
+ if self.log_with == "wandb":
164
+ # raise error if wandb is not installed
165
+ if not is_wandb_available():
166
+ raise ImportError("Please install wandb to use wandb logging. You can do this by running `pip install wandb`.")
167
+
168
+ self.total_ppo_epochs = int(np.ceil(self.steps / self.batch_size))
169
+ assert self.kl_penalty in ["kl", "abs", "mse", "full"]
170
+
171
+ def to_dict(self):
172
+ output_dict = {}
173
+ for key, value in self.__dict__.items():
174
+ output_dict[key] = value
175
+ return flatten_dict(output_dict)
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/ppo_trainer.py ADDED
@@ -0,0 +1,1397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import inspect
15
+ import math
16
+ import os
17
+ import time
18
+ import typing
19
+ import warnings
20
+ from contextlib import nullcontext
21
+ from typing import Callable, List, Optional, Union
22
+
23
+ import datasets
24
+ import numpy as np
25
+ import torch
26
+ import torch.nn.functional as F
27
+ from accelerate import Accelerator
28
+ from accelerate.utils import ProjectConfiguration, gather_object, is_deepspeed_available
29
+ from datasets import Dataset
30
+ from huggingface_hub import whoami
31
+ from packaging import version
32
+ from torch.optim import Adam
33
+ from transformers import (
34
+ DataCollatorForLanguageModeling,
35
+ PreTrainedTokenizer,
36
+ PreTrainedTokenizerBase,
37
+ PreTrainedTokenizerFast,
38
+ )
39
+
40
+ from ..core import (
41
+ WANDB_PADDING,
42
+ PPODecorators,
43
+ clip_by_value,
44
+ convert_to_scalar,
45
+ entropy_from_logits,
46
+ flatten_dict,
47
+ logprobs_from_logits,
48
+ masked_mean,
49
+ masked_var,
50
+ masked_whiten,
51
+ set_seed,
52
+ stack_dicts,
53
+ stats_to_np,
54
+ )
55
+ from ..import_utils import is_npu_available, is_torch_greater_2_0, is_xpu_available
56
+ from ..models import SUPPORTED_ARCHITECTURES, PreTrainedModelWrapper, create_reference_model
57
+ from . import AdaptiveKLController, BaseTrainer, FixedKLController, PPOConfig, RunningMoments
58
+
59
+
60
+ if is_deepspeed_available():
61
+ import deepspeed
62
+
63
+ MODEL_CARD_TEMPLATE = """---
64
+ license: apache-2.0
65
+ tags:
66
+ - trl
67
+ - ppo
68
+ - transformers
69
+ - reinforcement-learning
70
+ ---
71
+
72
+ # {model_name}
73
+
74
+ This is a [TRL language model](https://github.com/huggingface/trl) that has been fine-tuned with reinforcement learning to
75
+ guide the model outputs according to a value, function, or human feedback. The model can be used for text generation.
76
+
77
+ ## Usage
78
+
79
+ To use this model for inference, first install the TRL library:
80
+
81
+ ```bash
82
+ python -m pip install trl
83
+ ```
84
+
85
+ You can then generate text as follows:
86
+
87
+ ```python
88
+ from transformers import pipeline
89
+
90
+ generator = pipeline("text-generation", model="{model_id}")
91
+ outputs = generator("Hello, my llama is cute")
92
+ ```
93
+
94
+ If you want to use the model for training or to obtain the outputs from the value head, load the model as follows:
95
+
96
+ ```python
97
+ from transformers import AutoTokenizer
98
+ from trl import AutoModelForCausalLMWithValueHead
99
+
100
+ tokenizer = AutoTokenizer.from_pretrained("{model_id}")
101
+ model = AutoModelForCausalLMWithValueHead.from_pretrained("{model_id}")
102
+
103
+ inputs = tokenizer("Hello, my llama is cute", return_tensors="pt")
104
+ outputs = model(**inputs, labels=inputs["input_ids"])
105
+ ```
106
+ """
107
+
108
+
109
+ class PPOTrainer(BaseTrainer):
110
+ """
111
+ The PPOTrainer uses Proximal Policy Optimization to optimise language models.
112
+ Note, this trainer is heavily inspired by the original OpenAI learning to summarize work here:
113
+ https://github.com/openai/summarize-from-feedback
114
+
115
+ Attributes:
116
+ **config** (`PPOConfig`) -- Configuration object for PPOTrainer. Check the documentation of `PPOConfig` for more
117
+ details.
118
+ **model** (`PreTrainedModelWrapper`) -- Model to be optimized, Hugging Face transformer model with a value head.
119
+ Check the documentation of `PreTrainedModelWrapper` for more details.
120
+ **ref_model** (`PreTrainedModelWrapper`, *optional*) -- Reference model to be used for KL penalty, Hugging Face
121
+ transformer model with a casual language modelling head. Check the documentation of `PreTrainedModelWrapper`
122
+ for more details. If no reference model is provided, the trainer will create a reference model with the same
123
+ architecture as the model to be optimized with shared layers.
124
+ **tokenizer** (`PreTrainedTokenizerBase`) -- Tokenizer to be used for encoding the
125
+ data. Check the documentation of `transformers.PreTrainedTokenizer` and
126
+ `transformers.PreTrainedTokenizerFast` for more details.
127
+ **dataset** (Union[`torch.utils.data.Dataset`, `datasets.Dataset`], *optional*) -- PyTorch dataset or Hugging
128
+ Face dataset. This is used to create a PyTorch dataloader. If no dataset is provided, the dataloader must be
129
+ created outside the trainer users needs to design their own dataloader and make sure the batch
130
+ size that is used is the same as the one specified in the configuration object.
131
+ **optimizer** (`torch.optim.Optimizer`, *optional*) -- Optimizer to be used for training. If no optimizer is
132
+ provided, the trainer will create an Adam optimizer with the learning rate specified in the configuration
133
+ object.
134
+ **data_collator** (DataCollatorForLanguageModeling, *optional*) -- Data collator to be used for training and
135
+ passed along the dataloader
136
+ **num_shared_layers** (int, *optional*) -- Number of layers to be shared between the model and the reference
137
+ model, if no reference model is passed. If no number is provided, all the layers will be shared.
138
+ **lr_scheduler** (`torch.optim.lr_scheduler`, *optional*) -- Learning rate scheduler to be used for training.
139
+ """
140
+
141
+ _tag_names = ["trl", "ppo"]
142
+
143
+ def __init__(
144
+ self,
145
+ config: PPOConfig = None,
146
+ model: PreTrainedModelWrapper = None,
147
+ ref_model: Optional[PreTrainedModelWrapper] = None,
148
+ tokenizer: PreTrainedTokenizerBase = None,
149
+ dataset: Optional[Union[torch.utils.data.Dataset, Dataset]] = None,
150
+ optimizer: Optional[torch.optim.Optimizer] = None,
151
+ data_collator: Optional[typing.Callable] = None,
152
+ num_shared_layers: Optional[int] = None,
153
+ lr_scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,
154
+ ):
155
+ """
156
+ Initialize PPOTrainer.
157
+
158
+ Args:
159
+ config (`PPOConfig`):
160
+ Configuration object for PPOTrainer. Check the documentation of `PPOConfig` for more details.
161
+ model (`PreTrainedModelWrapper`):
162
+ Hugging Face transformer model with a value head.
163
+ ref_model (`PreTrainedModelWrapper`):
164
+ Hugging Face transformer model with a casual language modelling head. Used for KL penalty
165
+ tokenizer (`transformers.PreTrainedTokenizerBase`):
166
+ Hugging Face tokenizer
167
+ dataset (Optional[Union[`torch.utils.data.Dataset`, `datasets.Dataset`]]):
168
+ PyTorch dataset or Hugging Face dataset. If a Hugging Face dataset is passed, the dataset
169
+ will be preprocessed by removing the columns that are not used by the model. If none is passed,
170
+ a warning will be raised in a multi-GPU setting.
171
+ optimizer (Optional[`torch.optim.Optimizer`]):
172
+ Optimizer used for training. If `None`, the `Adam` is used as default.
173
+ data_collator (Optional[function]):
174
+ Data collator function.
175
+ num_shared_layers (Optional[int]):
176
+ Number of shared layers between the model and the reference model. If `None`, all layers are shared.
177
+ used only if `ref_model` is `None`.
178
+ lr_scheduler (Optional[`torch.optim.lr_scheduler`]):
179
+ Learning rate scheduler used for training.
180
+ """
181
+ super().__init__(config)
182
+
183
+ # initial seed for reproducible experiments
184
+ set_seed(config.seed)
185
+
186
+ # Step 0: check positional arguments validity
187
+ if not isinstance(config, PPOConfig):
188
+ raise ValueError(f"config must be a PPOConfig, got {type(config)}")
189
+ if not isinstance(tokenizer, (PreTrainedTokenizerBase)):
190
+ raise ValueError(f"tokenizer must be a PreTrainedTokenizerBase like a PreTrainedTokenizer or a PreTrainedTokenizerFast, got {type(tokenizer)}")
191
+ if not isinstance(model, (SUPPORTED_ARCHITECTURES)):
192
+ raise ValueError(f"model must be a PreTrainedModelWrapper, got {type(model)} - supported architectures are: {SUPPORTED_ARCHITECTURES}")
193
+ # Step 1: Initialize Accelerator
194
+ self.accelerator = Accelerator(
195
+ log_with=config.log_with,
196
+ gradient_accumulation_steps=config.gradient_accumulation_steps,
197
+ project_config=ProjectConfiguration(**config.project_kwargs),
198
+ **config.accelerator_kwargs,
199
+ )
200
+
201
+ # Step 1.1 Runtime variables filled by the accelerator
202
+ config.world_size = self.accelerator.num_processes
203
+ config.global_backward_batch_size = config.backward_batch_size * config.world_size
204
+ config.global_batch_size = config.batch_size * config.world_size
205
+
206
+ self.model = model
207
+ self.model_params = filter(lambda p: p.requires_grad, self.model.parameters())
208
+ self.is_encoder_decoder = hasattr(self.model, "is_encoder_decoder")
209
+ self.is_peft_model = getattr(self.model, "is_peft_model", False)
210
+ config.is_encoder_decoder = self.is_encoder_decoder
211
+ config.is_peft_model = self.is_peft_model
212
+
213
+ is_using_tensorboard = config.log_with is not None and config.log_with == "tensorboard"
214
+ self.accelerator.init_trackers(
215
+ config.tracker_project_name,
216
+ config=dict(trl_ppo_trainer_config=config.to_dict()) if not is_using_tensorboard else config.to_dict(),
217
+ init_kwargs=config.tracker_kwargs,
218
+ )
219
+ self.is_using_text_environment = getattr(config, "use_text_environment", False)
220
+
221
+ if isinstance(ref_model, SUPPORTED_ARCHITECTURES):
222
+ self.ref_model = ref_model
223
+ if num_shared_layers is not None:
224
+ warnings.warn(
225
+ "num_shared_layers is ignored when ref_model is provided. Two different models are used for the " "model and the reference model and no layers are shared.",
226
+ UserWarning,
227
+ )
228
+ elif ref_model is None and not self.is_peft_model:
229
+ self.ref_model = create_reference_model(self.model, num_shared_layers=num_shared_layers)
230
+ elif self.is_peft_model:
231
+ self.ref_model = None
232
+ else:
233
+ raise ValueError(f"ref_model must be a PreTrainedModelWrapper or `None`, got {type(ref_model)} - supported " f"architectures are: {SUPPORTED_ARCHITECTURES} ")
234
+ self.optional_peft_ctx = self.accelerator.unwrap_model(self.model).pretrained_model.disable_adapter if self.is_peft_model else nullcontext
235
+
236
+ if not (isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast)):
237
+ raise ValueError("tokenizer must be a transformers.PreTrainedTokenizer or transformers.PreTrainedTokenizerFast")
238
+ self.tokenizer = tokenizer
239
+
240
+ if dataset is not None and not (isinstance(dataset, torch.utils.data.Dataset) or isinstance(dataset, Dataset)):
241
+ raise ValueError("dataset must be a torch.utils.data.Dataset or datasets.Dataset")
242
+ elif dataset is None:
243
+ warnings.warn(
244
+ "No dataset is provided. Make sure to set config.batch_size to the correct value before training.",
245
+ UserWarning,
246
+ )
247
+ self.dataset = dataset
248
+ self._signature_columns = None
249
+ if self.dataset is not None:
250
+ self.dataloader = self.prepare_dataloader(self.dataset, data_collator)
251
+ elif self.dataset is None and self.accelerator.num_processes > 1:
252
+ warnings.warn(
253
+ "No dataset is provided. In a multi-GPU setting, this will lead to an error. You should"
254
+ " prepare your dataloader yourself with `dataloader = ppo_trainer.accelerator.prepare(dataloader)`"
255
+ " and using `torch.utils.data.DataLoader`, or pass a dataset to the `PPOTrainer`. Please "
256
+ " refer to the documentation for more details.",
257
+ UserWarning,
258
+ )
259
+ self.dataloader = None
260
+ else:
261
+ self.dataloader = None
262
+
263
+ # Step 3: Initialize optimizer and data collator
264
+ self.data_collator = DataCollatorForLanguageModeling(self.tokenizer, mlm=False)
265
+ if optimizer is None:
266
+ self.optimizer = Adam(
267
+ filter(lambda p: p.requires_grad, self.model.parameters()),
268
+ lr=self.config.learning_rate,
269
+ )
270
+ else:
271
+ self.optimizer = optimizer
272
+
273
+ self.lr_scheduler = lr_scheduler
274
+ if self.lr_scheduler is not None:
275
+ lr_scheduler_class = torch.optim.lr_scheduler._LRScheduler if not is_torch_greater_2_0() else torch.optim.lr_scheduler.LRScheduler
276
+
277
+ if not isinstance(self.lr_scheduler, lr_scheduler_class):
278
+ raise ValueError("lr_scheduler must be a torch.optim.lr_scheduler._LRScheduler or torch.optim.lr_scheduler.LRScheduler (for torch >= 2.0)")
279
+
280
+ if self.config.adap_kl_ctrl:
281
+ self.kl_ctl = AdaptiveKLController(self.config.init_kl_coef, self.config.target, self.config.horizon)
282
+ else:
283
+ self.kl_ctl = FixedKLController(self.config.init_kl_coef)
284
+
285
+ # Safety checkers for DS integration
286
+ is_deepspeed_used = self.accelerator.distributed_type == "DEEPSPEED" and hasattr(self.accelerator.state, "deepspeed_plugin")
287
+
288
+ (
289
+ self.model,
290
+ self.optimizer,
291
+ self.data_collator,
292
+ self.dataloader,
293
+ self.lr_scheduler,
294
+ ) = self.accelerator.prepare(
295
+ self.model,
296
+ self.optimizer,
297
+ self.data_collator,
298
+ self.dataloader,
299
+ self.lr_scheduler,
300
+ )
301
+ if is_deepspeed_used:
302
+ # Quantized models are already set on the correct device
303
+ if not self.is_peft_model and not (getattr(self.ref_model.pretrained_model, "is_loaded_in_8bit", False) or getattr(self.ref_model.pretrained_model, "is_loaded_in_4bit", False)):
304
+ self.ref_model = self._prepare_deepspeed(self.ref_model)
305
+ else:
306
+ self.ref_model = self.accelerator.prepare(self.ref_model)
307
+
308
+ # In a distributed setup, only logging needs to be performed on the main process
309
+ # check: https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html
310
+ # or: https://discuss.pytorch.org/t/use-distributed-data-parallel-correctly/82500/11
311
+ self.is_distributed = self.accelerator.num_processes > 1
312
+
313
+ # init the current step
314
+ self.current_step = 0
315
+
316
+ # init variables for pushing model to hub
317
+ if config.push_to_hub_if_best_kwargs:
318
+ if "repo_id" not in config.push_to_hub_if_best_kwargs:
319
+ raise ValueError("You have to specify repo_id in order to push the model to the hub!")
320
+ self.push_to_hub_kwargs = config.push_to_hub_if_best_kwargs
321
+ self.compare_step = 0
322
+ self.highest_reward = torch.tensor(-float("inf"))
323
+
324
+ # post process for PP
325
+ if not getattr(self.model, "is_sequential_parallel", False):
326
+ self.current_device = self.accelerator.device
327
+ else:
328
+ if is_xpu_available():
329
+ self.current_device = torch.device("xpu:0")
330
+ elif is_npu_available():
331
+ self.current_device = torch.device("npu:0")
332
+ else:
333
+ self.current_device = torch.device("cuda:0")
334
+
335
+ PPODecorators.optimize_device_cache = self.config.optimize_device_cache
336
+
337
+ self.running = RunningMoments(self.accelerator)
338
+
339
+ def _filter_kwargs(self, kwargs, target_func):
340
+ """
341
+ filter the keyword arguments that are supported by the target function.
342
+
343
+ Args:
344
+ kwargs (dict):
345
+ Keyword arguments
346
+ target_func (function):
347
+ Target function
348
+ """
349
+ return {k: v for k, v in kwargs.items() if k in inspect.signature(target_func).parameters.keys()}
350
+
351
+ def prepare_dataloader(self, dataset: Union[torch.utils.data.Dataset, Dataset], data_collator=None):
352
+ """
353
+ Prepare the dataloader for training.
354
+
355
+ Args:
356
+ dataset (Union[`torch.utils.data.Dataset`, `datasets.Dataset`]):
357
+ PyTorch dataset or Hugging Face dataset. If a Hugging Face dataset is passed, the dataset
358
+ will be preprocessed by removing the columns that are not used by the model.
359
+ data_collator (Optional[function]):
360
+ Data collator function.
361
+
362
+ Returns:
363
+ `torch.utils.data.DataLoader`: PyTorch dataloader
364
+ """
365
+ if isinstance(dataset, Dataset):
366
+ dataset = self._remove_unused_columns(dataset)
367
+ dataloader = torch.utils.data.DataLoader(
368
+ dataset,
369
+ batch_size=self.config.batch_size,
370
+ collate_fn=data_collator,
371
+ shuffle=True,
372
+ drop_last=True,
373
+ )
374
+ return dataloader
375
+
376
+ # Adapted from transformers.Trainer._set_signature_columns_if_needed
377
+ def _set_signature_columns_if_needed(self):
378
+ if self._signature_columns is None:
379
+ # Inspect model forward signature to keep only the arguments it accepts.
380
+ signature = inspect.signature(self.model.forward)
381
+ self._signature_columns = list(signature.parameters.keys())
382
+ # label => sentiment | we need query and response for logging purpose
383
+ self._signature_columns += ["label", "query", "response"]
384
+
385
+ # Adapted from transformers.Trainer._remove_unused_columns
386
+ def _remove_unused_columns(self, dataset: "Dataset"):
387
+ if not self.config.remove_unused_columns:
388
+ return dataset
389
+ self._set_signature_columns_if_needed()
390
+ signature_columns = self._signature_columns
391
+
392
+ ignored_columns = list(set(dataset.column_names) - set(signature_columns))
393
+
394
+ columns = [k for k in signature_columns if k in dataset.column_names]
395
+
396
+ if version.parse(datasets.__version__) < version.parse("1.4.0"):
397
+ dataset.set_format(
398
+ type=dataset.format["type"],
399
+ columns=columns,
400
+ format_kwargs=dataset.format["format_kwargs"],
401
+ )
402
+ return dataset
403
+ else:
404
+ return dataset.remove_columns(ignored_columns)
405
+
406
+ def generate(
407
+ self,
408
+ query_tensor: Union[torch.Tensor, List[torch.Tensor]],
409
+ length_sampler: Callable = None,
410
+ batch_size: int = 4,
411
+ return_prompt: bool = True,
412
+ generate_ref_response: bool = False,
413
+ **generation_kwargs,
414
+ ):
415
+ """
416
+ Generate response with the model given the query tensor.
417
+ call the `generate` method of the model.
418
+
419
+ Args:
420
+ query_tensor (`torch.LongTensor`):
421
+ A tensor of shape (`seq_len`) containing query tokens or a list of tensors of shape (`seq_len`).
422
+ length_sampler (`Callable`, *optional*):
423
+ Callable that returns the number of newly generated tokens.
424
+ batch_size (`int`, *optional):
425
+ Batch size used for generation, defaults to `4`.
426
+ return_prompt (`bool`, *optional*):
427
+ If set to `False` the prompt is not returned but only the newly generated tokens, defaults to `True`.
428
+ generate_ref_response (`bool`, *optional*):
429
+ If set to `True` the reference response is also generated, defaults to `False`.
430
+ generation_kwargs (dict[str, Any]):
431
+ Keyword arguments for generation.
432
+
433
+ Returns:
434
+ `torch.LongTensor`: A tensor of shape (`batch_size`, `gen_len`) containing response tokens.
435
+ """
436
+ if generate_ref_response:
437
+ ref_model = self.model if self.is_peft_model else self.ref_model
438
+ if isinstance(query_tensor, List):
439
+ response = self._generate_batched(
440
+ self.model,
441
+ query_tensor,
442
+ length_sampler=length_sampler,
443
+ batch_size=batch_size,
444
+ return_prompt=return_prompt,
445
+ **generation_kwargs,
446
+ )
447
+ if generate_ref_response:
448
+ with self.optional_peft_ctx():
449
+ ref_response = self._generate_batched(
450
+ ref_model,
451
+ query_tensor,
452
+ length_sampler=length_sampler,
453
+ batch_size=batch_size,
454
+ return_prompt=return_prompt,
455
+ **generation_kwargs,
456
+ )
457
+
458
+ else:
459
+ if len(query_tensor.shape) == 2:
460
+ raise ValueError("query_tensor must be a tensor of shape (`seq_len`) or a list of tensors of shape (`seq_len`)")
461
+
462
+ if length_sampler is not None:
463
+ generation_kwargs["max_new_tokens"] = length_sampler()
464
+ response = self.accelerator.unwrap_model(self.model).generate(input_ids=query_tensor.unsqueeze(dim=0), **generation_kwargs)
465
+ if generate_ref_response:
466
+ with self.optional_peft_ctx():
467
+ ref_response = ref_model.generate(input_ids=query_tensor.unsqueeze(dim=0), **generation_kwargs)
468
+
469
+ if not return_prompt and not self.is_encoder_decoder:
470
+ response = response[:, query_tensor.shape[0] :]
471
+ if generate_ref_response:
472
+ ref_response = ref_response[:, query_tensor.shape[0] :]
473
+
474
+ if generate_ref_response:
475
+ return response, ref_response
476
+ return response
477
+
478
+ def _generate_batched(
479
+ self,
480
+ model: PreTrainedModelWrapper,
481
+ query_tensors: List[torch.Tensor],
482
+ length_sampler: Callable = None,
483
+ batch_size: int = 4,
484
+ return_prompt: bool = True,
485
+ pad_to_multiple_of: int = None,
486
+ remove_padding: bool = True,
487
+ **generation_kwargs,
488
+ ):
489
+ outputs = []
490
+
491
+ padding_side_default = self.tokenizer.padding_side
492
+ if not self.is_encoder_decoder:
493
+ self.tokenizer.padding_side = "left"
494
+
495
+ # in case we have fewer examples than bs
496
+ batch_size = min(len(query_tensors), batch_size)
497
+
498
+ for i in range(0, len(query_tensors), batch_size):
499
+ if length_sampler is not None:
500
+ generation_kwargs["max_new_tokens"] = length_sampler()
501
+
502
+ # prevent overflow if query tensors are not even multiple of bs
503
+ end_index = min(len(query_tensors), i + batch_size)
504
+
505
+ batch = query_tensors[i:end_index]
506
+ batch_mask = [torch.ones_like(element) for element in batch]
507
+ inputs = {"input_ids": batch, "attention_mask": batch_mask}
508
+
509
+ padded_inputs = self.tokenizer.pad(
510
+ inputs,
511
+ padding=True,
512
+ max_length=None,
513
+ pad_to_multiple_of=pad_to_multiple_of,
514
+ return_tensors="pt",
515
+ ).to(self.current_device)
516
+
517
+ generations = self.accelerator.unwrap_model(model).generate(**padded_inputs, **generation_kwargs)
518
+
519
+ for generation, mask in zip(generations, padded_inputs["attention_mask"]):
520
+ if not self.is_encoder_decoder:
521
+ output = generation[(1 - mask).sum() :] # remove padding
522
+ else:
523
+ output = generation
524
+
525
+ if not return_prompt and not self.is_encoder_decoder:
526
+ output = output[(mask).sum() :] # remove prompt
527
+
528
+ if remove_padding and self.tokenizer.eos_token_id in output:
529
+ pad_mask = output == self.tokenizer.eos_token_id
530
+ pad_start = torch.nonzero(pad_mask, as_tuple=False)[0, 0].item()
531
+ output = output[: pad_start + 1] # keep the eos token at the end
532
+
533
+ outputs.append(output)
534
+
535
+ self.tokenizer.padding_side = padding_side_default
536
+ return outputs
537
+
538
+ def _step_safety_checker(
539
+ self,
540
+ batch_size: int,
541
+ queries: List[torch.LongTensor],
542
+ responses: List[torch.LongTensor],
543
+ scores: List[torch.FloatTensor],
544
+ masks: Optional[List[torch.LongTensor]] = None,
545
+ ):
546
+ """
547
+ Check if the input data is valid for training.
548
+
549
+ Args:
550
+ batch_size (int):
551
+ Batch size from the config file.
552
+ queries (List[`torch.LongTensor`]):
553
+ List of tensors containing the encoded queries of shape (`query_length`)
554
+ responses (List[`torch.LongTensor`]):
555
+ List of tensors containing the encoded responses of shape (`response_length`)
556
+ scores (List[`torch.FloatTensor`]):
557
+ List of tensors containing the scores.
558
+ masks (List[`torch.LongTensor`], *optional*):
559
+ list of optional tensors containing the masks of shape (`query_length` + `response_length`)
560
+ Returns:
561
+ `tuple`: The input processed data.
562
+ """
563
+ for name, tensor_list in zip(["queries", "responses", "scores"], [queries, responses, scores]):
564
+ if not isinstance(tensor_list, list):
565
+ raise ValueError(f"{name} must be a list of tensors - got {type(tensor_list)}")
566
+ if not isinstance(tensor_list[0], torch.Tensor):
567
+ raise ValueError(f"Elements in {name} must be tensors - got {type(tensor_list[0])}")
568
+ if batch_size is not None and len(tensor_list) != batch_size:
569
+ raise ValueError(f"Batch size ({batch_size}) does not match number of examples - but got {len(tensor_list)} for: {name}")
570
+
571
+ # add queries, scores and responses on the correct device
572
+ queries = [tensor.to(self.current_device) for tensor in queries]
573
+ responses = [tensor.to(self.current_device) for tensor in responses]
574
+ scores = [tensor.to(self.current_device) for tensor in scores]
575
+ masks = [tensor.to(self.current_device) for tensor in masks] if masks is not None else None
576
+
577
+ # squeeze scores if needed
578
+ for i, score in enumerate(scores):
579
+ if score.dim() > 1:
580
+ raise ValueError(f"Scores must be 1-dimensional - got {score.dim()} for {score}")
581
+ elif score.dim() == 1:
582
+ scores[i] = score.squeeze()
583
+
584
+ return queries, responses, scores, masks
585
+
586
+ @PPODecorators.empty_device_cache()
587
+ def step(
588
+ self,
589
+ queries: List[torch.LongTensor],
590
+ responses: List[torch.LongTensor],
591
+ scores: List[torch.FloatTensor],
592
+ response_masks: Optional[List[torch.LongTensor]] = None,
593
+ ):
594
+ """
595
+ Run a PPO optimisation step given a list of queries, model responses, and rewards.
596
+
597
+ Args:
598
+ queries (List[`torch.LongTensor`]):
599
+ List of tensors containing the encoded queries of shape (`query_length`)
600
+ responses (List[`torch.LongTensor`]):
601
+ List of tensors containing the encoded responses of shape (`response_length`)
602
+ scores (List[`torch.FloatTensor`]):
603
+ List of tensors containing the scores.
604
+ response_masks (List[`torch.FloatTensor`], *optional*)):
605
+ List of tensors containing masks of the response tokens.
606
+
607
+ Returns:
608
+ `dict[str, Any]`: A summary of the training statistics
609
+ """
610
+ bs = self.config.batch_size
611
+
612
+ queries, responses, scores, response_masks = self._step_safety_checker(bs, queries, responses, scores, response_masks)
613
+ scores = torch.tensor(scores, device=self.current_device)
614
+ if self.config.use_score_scaling:
615
+ # Score scaling
616
+ scores_mean, scores_std = self.running.update(scores)
617
+ tensor_to_kwargs = dict(dtype=scores.dtype, device=scores.device)
618
+ score_scaling_factor = self.running.std.to(**tensor_to_kwargs) + torch.finfo(scores.dtype).eps
619
+ if self.config.use_score_norm:
620
+ scores = (scores - self.running.mean.to(**tensor_to_kwargs)) / score_scaling_factor
621
+ else:
622
+ scores /= score_scaling_factor
623
+
624
+ if self.config.score_clip is not None:
625
+ # Score clipping
626
+ scores_dtype = scores.dtype
627
+ scores = torch.clip(scores.float(), -self.config.score_clip, self.config.score_clip).to(dtype=scores_dtype)
628
+
629
+ # if we want to push best model to the hub
630
+ if hasattr(self, "highest_reward"):
631
+ if self.compare_step % self.config.compare_steps == 0:
632
+ curr_mean_reward = scores.mean()
633
+ # if the best reward ever seen
634
+ if curr_mean_reward > self.highest_reward:
635
+ self.highest_reward = curr_mean_reward
636
+ # push model to hub
637
+ self.push_to_hub(**self.push_to_hub_kwargs)
638
+ self.compare_step += 1
639
+
640
+ timing = dict()
641
+ t0 = time.time()
642
+
643
+ t = time.time()
644
+
645
+ model_inputs = self.prepare_model_inputs(queries, responses)
646
+
647
+ if self.is_distributed:
648
+ pad_first = self.tokenizer.padding_side == "left"
649
+
650
+ model_inputs["input_ids"] = self.accelerator.pad_across_processes(
651
+ model_inputs["input_ids"],
652
+ dim=1,
653
+ pad_index=self.tokenizer.pad_token_id,
654
+ pad_first=pad_first,
655
+ )
656
+ model_inputs["attention_mask"] = self.accelerator.pad_across_processes(model_inputs["attention_mask"], dim=1, pad_index=0, pad_first=pad_first)
657
+ if self.is_encoder_decoder:
658
+ model_inputs["decoder_input_ids"] = self.accelerator.pad_across_processes(
659
+ model_inputs["decoder_input_ids"],
660
+ dim=1,
661
+ pad_index=self.tokenizer.pad_token_id,
662
+ pad_first=pad_first,
663
+ )
664
+ model_inputs["decoder_attention_mask"] = self.accelerator.pad_across_processes(
665
+ model_inputs["decoder_attention_mask"],
666
+ dim=1,
667
+ pad_index=0,
668
+ pad_first=pad_first,
669
+ )
670
+
671
+ model_inputs_names = list(model_inputs.keys())
672
+
673
+ full_kl_penalty = self.config.kl_penalty == "full"
674
+
675
+ with torch.no_grad():
676
+ all_logprobs, logits_or_none, values, masks = self.batched_forward_pass(
677
+ self.model,
678
+ queries,
679
+ responses,
680
+ model_inputs,
681
+ response_masks=response_masks,
682
+ return_logits=full_kl_penalty,
683
+ )
684
+ with self.optional_peft_ctx():
685
+ ref_logprobs, ref_logits_or_none, _, _ = self.batched_forward_pass(
686
+ self.model if self.is_peft_model else self.ref_model,
687
+ queries,
688
+ responses,
689
+ model_inputs,
690
+ return_logits=full_kl_penalty,
691
+ )
692
+
693
+ timing["time/ppo/forward_pass"] = time.time() - t
694
+
695
+ with torch.no_grad():
696
+ t = time.time()
697
+ if full_kl_penalty:
698
+ active_full_logprobs = logprobs_from_logits(logits_or_none, None, gather=False)
699
+ ref_full_logprobs = logprobs_from_logits(ref_logits_or_none, None, gather=False)
700
+
701
+ rewards, non_score_reward, kls = self.compute_rewards(scores, active_full_logprobs, ref_full_logprobs, masks)
702
+ else:
703
+ rewards, non_score_reward, kls = self.compute_rewards(scores, all_logprobs, ref_logprobs, masks)
704
+ timing["time/ppo/compute_rewards"] = time.time() - t
705
+
706
+ t = time.time()
707
+ values, advantages, returns = self.compute_advantages(values, rewards, masks)
708
+ timing["time/ppo/compute_advantages"] = time.time() - t
709
+
710
+ # upcast to float32 to avoid dataset issues
711
+ batch_dict = {
712
+ "queries": queries,
713
+ "responses": responses,
714
+ "logprobs": all_logprobs.to(torch.float32),
715
+ "values": values.to(torch.float32),
716
+ "masks": masks,
717
+ "advantages": advantages,
718
+ "returns": returns,
719
+ }
720
+ batch_dict.update(model_inputs)
721
+
722
+ t = time.time()
723
+ all_stats = []
724
+ early_stop = False
725
+ for _ in range(self.config.ppo_epochs):
726
+ if early_stop:
727
+ break
728
+ b_inds = np.random.permutation(bs)
729
+ for backward_batch_start in range(0, bs, self.config.backward_batch_size):
730
+ backward_batch_end = backward_batch_start + self.config.backward_batch_size
731
+ backward_batch_inds = b_inds[backward_batch_start:backward_batch_end]
732
+
733
+ for mini_batch_start in range(0, self.config.backward_batch_size, self.config.mini_batch_size):
734
+ mini_batch_end = mini_batch_start + self.config.mini_batch_size
735
+ mini_batch_inds = backward_batch_inds[mini_batch_start:mini_batch_end]
736
+ mini_batch_dict = {
737
+ "logprobs": batch_dict["logprobs"][mini_batch_inds],
738
+ "values": batch_dict["values"][mini_batch_inds],
739
+ "masks": batch_dict["masks"][mini_batch_inds],
740
+ # hacks: the queries and responses are ragged.
741
+ "queries": [batch_dict["queries"][i] for i in mini_batch_inds],
742
+ "responses": [batch_dict["responses"][i] for i in mini_batch_inds],
743
+ "advantages": batch_dict["advantages"][mini_batch_inds],
744
+ "returns": batch_dict["returns"][mini_batch_inds],
745
+ }
746
+ for k in model_inputs_names:
747
+ mini_batch_dict[k] = batch_dict[k][mini_batch_inds]
748
+ with self.accelerator.accumulate(self.model):
749
+ model_inputs = {k: mini_batch_dict[k] for k in model_inputs_names}
750
+
751
+ logprobs, logits, vpreds, _ = self.batched_forward_pass(
752
+ self.model,
753
+ mini_batch_dict["queries"],
754
+ mini_batch_dict["responses"],
755
+ model_inputs,
756
+ return_logits=True,
757
+ )
758
+ train_stats = self.train_minibatch(
759
+ mini_batch_dict["logprobs"],
760
+ mini_batch_dict["values"],
761
+ logprobs,
762
+ logits,
763
+ vpreds,
764
+ mini_batch_dict["masks"],
765
+ mini_batch_dict["advantages"],
766
+ mini_batch_dict["returns"],
767
+ )
768
+ all_stats.append(train_stats)
769
+
770
+ # typically, early stopping is done at the epoch level
771
+ if self.config.early_stopping:
772
+ policykl = train_stats["policy/policykl"]
773
+ early_stop = self._early_stop(policykl)
774
+ if early_stop:
775
+ break
776
+
777
+ timing["time/ppo/optimize_step"] = time.time() - t
778
+
779
+ t = time.time()
780
+ train_stats = stack_dicts(all_stats)
781
+
782
+ # reshape advantages/ratios such that they are not averaged.
783
+ train_stats["policy/advantages"] = torch.flatten(train_stats["policy/advantages"]).unsqueeze(0)
784
+ train_stats["policy/advantages"] = torch.nan_to_num(train_stats["policy/advantages"], WANDB_PADDING)
785
+ train_stats["policy/ratio"] = torch.flatten(train_stats["policy/ratio"]).unsqueeze(0)
786
+
787
+ stats = self.record_step_stats(
788
+ scores=scores,
789
+ logprobs=all_logprobs,
790
+ ref_logprobs=ref_logprobs,
791
+ non_score_reward=non_score_reward,
792
+ train_stats=train_stats,
793
+ kl_coef=self.kl_ctl.value,
794
+ masks=masks,
795
+ queries=queries,
796
+ responses=responses,
797
+ kls=kls,
798
+ )
799
+ # Gather/Reduce stats from all processes
800
+ if self.is_distributed:
801
+ stats = self.gather_stats(stats)
802
+ stats = stats_to_np(stats)
803
+ timing["time/ppo/calc_stats"] = time.time() - t
804
+ stats["ppo/learning_rate"] = self.optimizer.param_groups[0]["lr"]
805
+
806
+ # Update the KL control - multiply the batch_size by the number of processes
807
+ self.kl_ctl.update(
808
+ stats["objective/kl"],
809
+ self.config.batch_size * self.accelerator.num_processes,
810
+ )
811
+
812
+ # Log the total ppo time
813
+ timing["time/ppo/total"] = time.time() - t0
814
+ stats.update(timing)
815
+
816
+ # post-process stats for tensorboard and other loggers
817
+ if self.config.log_with != "wandb":
818
+ stats = convert_to_scalar(stats)
819
+
820
+ if self.lr_scheduler is not None:
821
+ self.lr_scheduler.step()
822
+
823
+ return stats
824
+
825
+ def _early_stop(self, policykl):
826
+ r"""
827
+ Handles the early stopping logic. If the policy KL is greater than the target KL, then the gradient is zeroed and
828
+ the optimization step is skipped.
829
+ This also handles the multi-gpu case where the policy KL is averaged across all processes.
830
+
831
+ Args:
832
+ policy_kl (torch.Tensor):
833
+ the policy KL
834
+
835
+ Returns:
836
+ `bool`: whether to early stop or not
837
+ """
838
+ early_stop = False
839
+ if not self.config.early_stopping:
840
+ return early_stop
841
+
842
+ if not self.is_distributed and policykl > 1.5 * self.config.target_kl:
843
+ self.optimizer.zero_grad()
844
+ early_stop = True
845
+ elif self.is_distributed:
846
+ import torch.distributed as dist
847
+
848
+ # Wait for all processes to finish
849
+ dist.barrier()
850
+
851
+ # all gather the policykl
852
+ dist.all_reduce(policykl, dist.ReduceOp.SUM)
853
+ policykl /= self.accelerator.num_processes
854
+
855
+ if policykl > 1.5 * self.config.target_kl:
856
+ self.optimizer.zero_grad()
857
+ early_stop = True
858
+ return early_stop
859
+
860
+ def gather_stats(self, stats):
861
+ """
862
+ Gather stats from all processes. Useful in the context of distributed training.
863
+
864
+ Args:
865
+ stats (dict[str, Any]):
866
+ a dictionary of stats to be gathered. The stats should contain torch tensors.
867
+
868
+ Returns:
869
+ `dict[str, Any]`: A dictionary of stats with the tensors gathered.
870
+ """
871
+ import torch.distributed as dist
872
+
873
+ # Wait for all processes to finish
874
+ dist.barrier()
875
+
876
+ for k, v in stats.items():
877
+ if isinstance(v, torch.Tensor):
878
+ dist.all_reduce(v.to(self.accelerator.device), dist.ReduceOp.SUM)
879
+ v /= self.accelerator.num_processes
880
+ stats[k] = v
881
+ return stats
882
+
883
+ def prepare_model_inputs(self, queries: torch.Tensor, responses: torch.Tensor):
884
+ if self.is_encoder_decoder:
885
+ input_data = self.data_collator([{"input_ids": q, "attention_mask": torch.ones_like(q)} for q in queries]).to(self.current_device)
886
+
887
+ decoder_inputs = self.data_collator([{"input_ids": r, "attention_mask": torch.ones_like(r)} for r in responses]).to(self.current_device)
888
+
889
+ input_data["decoder_input_ids"] = decoder_inputs["input_ids"]
890
+ input_data["decoder_attention_mask"] = decoder_inputs["attention_mask"]
891
+ else:
892
+ input_ids = [torch.cat([q, r]) for q, r in zip(queries, responses)]
893
+ input_data = self.data_collator([{"input_ids": ids, "attention_mask": torch.ones_like(ids)} for ids in input_ids]).to(self.current_device)
894
+
895
+ input_data.pop("labels", None) # we don't want to compute LM losses
896
+ return input_data
897
+
898
+ @PPODecorators.empty_device_cache()
899
+ def batched_forward_pass(
900
+ self,
901
+ model: PreTrainedModelWrapper,
902
+ queries: torch.Tensor,
903
+ responses: torch.Tensor,
904
+ model_inputs: dict,
905
+ return_logits: bool = False,
906
+ response_masks: Optional[torch.Tensor] = None,
907
+ ):
908
+ """
909
+ Calculate model outputs in multiple batches.
910
+
911
+ Args:
912
+ queries (`torch.LongTensor`):
913
+ List of tensors containing the encoded queries, shape (`batch_size`, `query_length`)
914
+ responses (`torch.LongTensor`):
915
+ List of tensors containing the encoded responses, shape (`batch_size`, `response_length`)
916
+ return_logits (`bool`, *optional*, defaults to `False`):
917
+ Whether to return all_logits. Set to `False` if logits are not needed to reduce memory consumption.
918
+ Returns:
919
+ (tuple):
920
+ - all_logprobs (`torch.FloatTensor`): Log probabilities of the responses,
921
+ shape (`batch_size`, `response_length`)
922
+ - all_ref_logprobs (`torch.FloatTensor`): Log probabilities of the responses,
923
+ shape (`batch_size`, `response_length`)
924
+ - all_values (`torch.FloatTensor`): Values of the responses, shape (`batch_size`, `response_length`)
925
+ """
926
+ bs = len(queries)
927
+ fbs = self.config.mini_batch_size
928
+ all_logprobs = []
929
+ all_logits = []
930
+ all_masks = []
931
+ all_values = []
932
+
933
+ model.eval()
934
+
935
+ for i in range(math.ceil(bs / fbs)):
936
+ input_kwargs = {key: value[i * fbs : (i + 1) * fbs] for key, value in model_inputs.items()}
937
+ query_batch = queries[i * fbs : (i + 1) * fbs]
938
+ response_batch = responses[i * fbs : (i + 1) * fbs]
939
+ if response_masks is not None:
940
+ response_masks_batch = response_masks[i * fbs : (i + 1) * fbs]
941
+ logits, _, values = model(**input_kwargs)
942
+
943
+ if self.is_encoder_decoder:
944
+ input_ids = input_kwargs["decoder_input_ids"]
945
+ attention_mask = input_kwargs["decoder_attention_mask"]
946
+ else:
947
+ input_ids = input_kwargs["input_ids"]
948
+ attention_mask = input_kwargs["attention_mask"]
949
+
950
+ logprobs = logprobs_from_logits(logits[:, :-1, :], input_ids[:, 1:])
951
+ masks = torch.zeros_like(attention_mask)
952
+ masks[:, :-1] = attention_mask[:, 1:]
953
+
954
+ for j in range(len(query_batch)):
955
+ if self.is_encoder_decoder:
956
+ # Decoder sentence starts always in the index 1 after padding in the Enc-Dec Models
957
+ start = 1
958
+ end = attention_mask[j, :].sum() - 1
959
+ else:
960
+ start = len(query_batch[j]) - 1 # logprobs starts from the second query token
961
+ if attention_mask[j, 0] == 0: # offset left padding
962
+ start += attention_mask[j, :].nonzero()[0]
963
+ end = start + len(response_batch[j])
964
+ if response_masks is not None:
965
+ response_masks_batch[j] = torch.cat((torch.zeros_like(query_batch[j]), response_masks_batch[j]))[1:]
966
+
967
+ masks[j, :start] = 0
968
+ masks[j, end:] = 0
969
+ if response_masks is not None:
970
+ masks[j, start:end] = masks[j, start:end] * response_masks_batch[j][start:end]
971
+
972
+ if return_logits:
973
+ all_logits.append(logits)
974
+ else:
975
+ del logits
976
+ all_values.append(values)
977
+ all_logprobs.append(logprobs)
978
+ all_masks.append(masks)
979
+
980
+ return (
981
+ torch.cat(all_logprobs),
982
+ torch.cat(all_logits)[:, :-1] if return_logits else None,
983
+ torch.cat(all_values)[:, :-1],
984
+ torch.cat(all_masks)[:, :-1],
985
+ )
986
+
987
+ @PPODecorators.empty_device_cache()
988
+ def train_minibatch(
989
+ self,
990
+ old_logprobs: torch.FloatTensor,
991
+ values: torch.FloatTensor,
992
+ logprobs: torch.FloatTensor,
993
+ logits: torch.FloatTensor,
994
+ vpreds: torch.FloatTensor,
995
+ mask: torch.LongTensor,
996
+ advantages: torch.FloatTensor,
997
+ returns: torch.FloatTensor,
998
+ ):
999
+ """
1000
+ Train one PPO minibatch
1001
+
1002
+ Args:
1003
+ logprobs (`torch.FloatTensor`):
1004
+ Log probabilities of the model, shape [mini_batch_size, response_length]
1005
+ values (`torch.FloatTensor`):
1006
+ Values of the value head, shape [mini_batch_size, response_length]
1007
+ query (`torch.LongTensor`):
1008
+ Encoded queries, shape [mini_batch_size, query_length]
1009
+ response (`torch.LongTensor`):
1010
+ Encoded responses, shape [mini_batch_size, response_length]
1011
+ model_input (`torch.LongTensor`):
1012
+ Concatenated queries and responses, shape [mini_batch_size, query_length+response_length]
1013
+
1014
+ Returns:
1015
+ train_stats (dict[str, `torch.Tensor`]):
1016
+ Dictionary of training statistics
1017
+ """
1018
+ self.model.train()
1019
+ loss_p, loss_v, train_stats = self.loss(old_logprobs, values, logits, vpreds, logprobs, mask, advantages, returns)
1020
+ loss = loss_p + loss_v
1021
+ self.accelerator.backward(loss)
1022
+ if self.config.max_grad_norm is not None:
1023
+ if self.accelerator.sync_gradients:
1024
+ self.accelerator.clip_grad_norm_(self.model_params, self.config.max_grad_norm)
1025
+ self.optimizer.step()
1026
+ # we call optimizer.zero_grad() every time and let `accelerator` handle accumulation
1027
+ # see https://huggingface.co/docs/accelerate/usage_guides/gradient_accumulation#the-finished-code
1028
+ self.optimizer.zero_grad()
1029
+ return train_stats
1030
+
1031
+ def compute_rewards(
1032
+ self,
1033
+ scores: torch.FloatTensor,
1034
+ logprobs: torch.FloatTensor,
1035
+ ref_logprobs: torch.FloatTensor,
1036
+ masks: torch.LongTensor,
1037
+ ):
1038
+ """
1039
+ Compute per token rewards from scores and KL-penalty.
1040
+
1041
+ Args:
1042
+ scores (`torch.FloatTensor`):
1043
+ Scores from the reward model, shape (`batch_size`)
1044
+ logprobs (`torch.FloatTensor`):
1045
+ Log probabilities of the model, shape (`batch_size`, `response_length`)
1046
+ ref_logprobs (`torch.FloatTensor`):
1047
+ Log probabilities of the reference model, shape (`batch_size`, `response_length`)
1048
+
1049
+ Returns:
1050
+ `torch.FloatTensor`: Per token rewards, shape (`batch_size`, `response_length`)
1051
+ `torch.FloatTensor`: Non score rewards, shape (`batch_size`, `response_length`)
1052
+ `torch.FloatTensor`: KL penalty, shape (`batch_size`, `response_length`)
1053
+ """
1054
+ rewards, non_score_rewards, kls = [], [], []
1055
+ for score, logprob, ref_logprob, mask in zip(scores, logprobs, ref_logprobs, masks):
1056
+ # compute KL penalty (from difference in logprobs)
1057
+ kl = self._kl_penalty(logprob, ref_logprob)
1058
+ kls.append(kl)
1059
+ non_score_reward = -self.kl_ctl.value * kl
1060
+ non_score_rewards.append(non_score_reward)
1061
+ reward = non_score_reward.clone()
1062
+ last_non_masked_index = mask.nonzero()[-1]
1063
+
1064
+ # reward is preference model score + KL penalty
1065
+ reward[last_non_masked_index] += score
1066
+ rewards.append(reward)
1067
+ return torch.stack(rewards), torch.stack(non_score_rewards), torch.stack(kls)
1068
+
1069
+ def _kl_penalty(self, logprob: torch.FloatTensor, ref_logprob: torch.FloatTensor) -> torch.FloatTensor:
1070
+ if self.config.kl_penalty == "kl":
1071
+ return logprob - ref_logprob
1072
+
1073
+ if self.config.kl_penalty == "abs":
1074
+ return (logprob - ref_logprob).abs()
1075
+
1076
+ if self.config.kl_penalty == "mse":
1077
+ return 0.5 * (logprob - ref_logprob).square()
1078
+
1079
+ if self.config.kl_penalty == "full":
1080
+ # Flip is required due to this issue? :https://github.com/pytorch/pytorch/issues/57459
1081
+ return F.kl_div(ref_logprob, logprob, log_target=True, reduction="none").sum(-1)
1082
+
1083
+ raise NotImplementedError
1084
+
1085
+ def compute_advantages(
1086
+ self,
1087
+ values: torch.FloatTensor,
1088
+ rewards: torch.FloatTensor,
1089
+ mask: torch.FloatTensor,
1090
+ ):
1091
+ lastgaelam = 0
1092
+ advantages_reversed = []
1093
+ gen_len = rewards.shape[-1]
1094
+
1095
+ values = values * mask
1096
+ rewards = rewards * mask
1097
+
1098
+ if self.config.whiten_rewards:
1099
+ rewards = masked_whiten(rewards, mask, shift_mean=False)
1100
+
1101
+ for t in reversed(range(gen_len)):
1102
+ nextvalues = values[:, t + 1] if t < gen_len - 1 else 0.0
1103
+ delta = rewards[:, t] + self.config.gamma * nextvalues - values[:, t]
1104
+ lastgaelam = delta + self.config.gamma * self.config.lam * lastgaelam
1105
+ advantages_reversed.append(lastgaelam)
1106
+ advantages = torch.stack(advantages_reversed[::-1]).transpose(0, 1)
1107
+
1108
+ returns = advantages + values
1109
+ advantages = masked_whiten(advantages, mask)
1110
+ advantages = advantages.detach()
1111
+ return values, advantages, returns
1112
+
1113
+ def loss(
1114
+ self,
1115
+ old_logprobs: torch.FloatTensor,
1116
+ values: torch.FloatTensor,
1117
+ logits: torch.FloatTensor,
1118
+ vpreds: torch.FloatTensor,
1119
+ logprobs: torch.FloatTensor,
1120
+ mask: torch.LongTensor,
1121
+ advantages: torch.FloatTensor,
1122
+ returns: torch.FloatTensor,
1123
+ ):
1124
+ """
1125
+ Calculate policy and value losses.
1126
+
1127
+ Args:
1128
+ old_logprobs (`torch.FloatTensor`):
1129
+ Log probabilities of the model, shape (`batch_size`, `response_length`)
1130
+ values (`torch.FloatTensor`):
1131
+ Values of the value head, shape (`batch_size`, `response_length`)
1132
+ rewards (`torch.FloatTensor`):
1133
+ Rewards from the reward model, shape (`batch_size`, `response_length`)
1134
+ logits (`torch.FloatTensor`):
1135
+ Logits of the model, shape (`batch_size`, `response_length`, `vocab_size`)
1136
+ v_pred (`torch.FloatTensor`):
1137
+ Values of the value head, shape (`batch_size`, `response_length`)
1138
+ logprobs (`torch.FloatTensor`):
1139
+ Log probabilities of the model, shape (`batch_size`, `response_length`)
1140
+ """
1141
+
1142
+ vpredclipped = clip_by_value(
1143
+ vpreds,
1144
+ values - self.config.cliprange_value,
1145
+ values + self.config.cliprange_value,
1146
+ )
1147
+
1148
+ vf_losses1 = (vpreds - returns) ** 2
1149
+ vf_losses2 = (vpredclipped - returns) ** 2
1150
+ vf_loss = 0.5 * masked_mean(torch.max(vf_losses1, vf_losses2), mask)
1151
+ vf_clipfrac = masked_mean(torch.gt(vf_losses2, vf_losses1).float(), mask)
1152
+
1153
+ ratio = torch.exp(logprobs - old_logprobs)
1154
+
1155
+ pg_losses = -advantages * ratio
1156
+ pg_losses2 = -advantages * torch.clamp(ratio, 1.0 - self.config.cliprange, 1.0 + self.config.cliprange)
1157
+
1158
+ pg_loss = masked_mean(torch.max(pg_losses, pg_losses2), mask)
1159
+ pg_clipfrac = masked_mean(torch.gt(pg_losses2, pg_losses).float(), mask)
1160
+
1161
+ loss = pg_loss + self.config.vf_coef * vf_loss
1162
+
1163
+ avg_ratio = masked_mean(ratio, mask).item()
1164
+ if avg_ratio > self.config.ratio_threshold:
1165
+ warnings.warn(f"The average ratio of batch ({avg_ratio:.2f}) exceeds threshold {self.config.ratio_threshold:.2f}. Skipping batch.")
1166
+ pg_loss = pg_loss * 0.0
1167
+ vf_loss = vf_loss * 0.0
1168
+ loss = loss * 0.0
1169
+
1170
+ entropy = masked_mean(entropy_from_logits(logits), mask)
1171
+
1172
+ approxkl = 0.5 * masked_mean((logprobs - old_logprobs) ** 2, mask)
1173
+ policykl = masked_mean(old_logprobs - logprobs, mask)
1174
+
1175
+ return_mean, return_var = masked_mean(returns, mask), masked_var(returns, mask)
1176
+ value_mean, value_var = masked_mean(values, mask), masked_var(values, mask)
1177
+
1178
+ stats = dict(
1179
+ loss=dict(policy=pg_loss.detach(), value=vf_loss.detach(), total=loss.detach()),
1180
+ policy=dict(
1181
+ entropy=entropy.detach(),
1182
+ approxkl=approxkl.detach(),
1183
+ policykl=policykl.detach(),
1184
+ clipfrac=pg_clipfrac.detach(),
1185
+ advantages=advantages.detach(),
1186
+ advantages_mean=masked_mean(advantages, mask).detach(),
1187
+ ratio=ratio.detach(),
1188
+ ),
1189
+ returns=dict(mean=return_mean.detach(), var=return_var.detach()),
1190
+ val=dict(
1191
+ vpred=masked_mean(vpreds, mask).detach(),
1192
+ error=masked_mean((vpreds - returns) ** 2, mask).detach(),
1193
+ clipfrac=vf_clipfrac.detach(),
1194
+ mean=value_mean.detach(),
1195
+ var=value_var.detach(),
1196
+ ),
1197
+ )
1198
+ return pg_loss, self.config.vf_coef * vf_loss, flatten_dict(stats)
1199
+
1200
+ def record_step_stats(self, kl_coef: float, **data):
1201
+ """
1202
+ Record training step statistics.
1203
+
1204
+
1205
+ Args:
1206
+ kl_coef (`float`):
1207
+ KL coefficient
1208
+ data (`dict`):
1209
+ Dictionary of training step data
1210
+
1211
+ Returns:
1212
+ stats (`dict`):
1213
+ Dictionary of training step statistics
1214
+ """
1215
+ mask = data.pop("masks")
1216
+
1217
+ kls = data.pop("kls")
1218
+ kl_list = ((kls) * mask).sum(axis=-1)
1219
+ mean_kl = kl_list.mean()
1220
+ mean_entropy = (-data["logprobs"] * mask).sum(axis=-1).mean()
1221
+
1222
+ mean_non_score_reward = masked_mean(data["non_score_reward"], mask) # non_score_reward is size `batch_size`, `response_length`
1223
+ mean_scores = data["scores"].mean() # scores is size `batch_size`
1224
+ std_scores = data["scores"].std()
1225
+
1226
+ if mean_kl.item() < -1.0:
1227
+ # warn users
1228
+ warnings.warn(
1229
+ f"KL divergence is starting to become negative: {mean_kl.item():.2f} - this might be a precursor for failed training."
1230
+ " sometimes this happens because the generation kwargs are not correctly set. Please make sure"
1231
+ " that the generation kwargs are set correctly, or review your training hyperparameters."
1232
+ )
1233
+
1234
+ stats = {
1235
+ "objective/kl": mean_kl,
1236
+ "objective/kl_dist": kl_list,
1237
+ "objective/logprobs": data["logprobs"],
1238
+ "objective/ref_logprobs": data["ref_logprobs"],
1239
+ "objective/kl_coef": kl_coef,
1240
+ "objective/entropy": mean_entropy,
1241
+ "ppo/mean_non_score_reward": mean_non_score_reward,
1242
+ "ppo/mean_scores": mean_scores,
1243
+ "ppo/std_scores": std_scores,
1244
+ }
1245
+
1246
+ # Log text properties
1247
+ query_lens = torch.tensor([len(query) for query in data["queries"]], dtype=torch.float)
1248
+ response_lens = torch.tensor([len(response) for response in data["responses"]], dtype=torch.float)
1249
+
1250
+ stats["tokens/queries_len_mean"] = torch.mean(query_lens).cpu().numpy().item()
1251
+ stats["tokens/queries_len_std"] = torch.std(query_lens).cpu().numpy().item()
1252
+ stats["tokens/queries_dist"] = query_lens.cpu().numpy()
1253
+ stats["tokens/responses_len_mean"] = torch.mean(response_lens).cpu().numpy().item()
1254
+ stats["tokens/responses_len_std"] = torch.std(response_lens).cpu().numpy().item()
1255
+ stats["tokens/responses_dist"] = response_lens.cpu().numpy()
1256
+
1257
+ for k, v in data["train_stats"].items():
1258
+ stats[f"ppo/{k}"] = torch.mean(v, axis=0)
1259
+ stats["ppo/val/var_explained"] = 1 - stats["ppo/val/error"] / stats["ppo/returns/var"]
1260
+ return stats
1261
+
1262
+ def log_stats(
1263
+ self,
1264
+ stats: dict,
1265
+ batch: dict,
1266
+ rewards: List[torch.FloatTensor],
1267
+ columns_to_log: List[str] = ["query", "response"],
1268
+ ):
1269
+ """
1270
+ A function that logs all the training stats. Call it at the end of each epoch.
1271
+
1272
+ Args:
1273
+ stats (dict[str, Any]):
1274
+ A dictionary of training stats.
1275
+ batch (dict[str, Any]):
1276
+ A dictionary of batch data, this contains the queries and responses.
1277
+ rewards (`List[torch.FloatTensor]`):
1278
+ A tensor of rewards.
1279
+ """
1280
+
1281
+ # all gather stats
1282
+ if not isinstance(rewards, torch.Tensor):
1283
+ rewards = torch.tensor(rewards).to(self.current_device)
1284
+ rewards = self.accelerator.gather(rewards).flatten()
1285
+
1286
+ if self.config.log_with == "wandb":
1287
+ import wandb
1288
+
1289
+ if any([column_to_log not in batch.keys() for column_to_log in columns_to_log]):
1290
+ raise ValueError(f"Columns to log {columns_to_log} are not present in the batch {batch.keys()}.")
1291
+
1292
+ batch_list = [batch[column_to_log] for column_to_log in columns_to_log]
1293
+ if self.is_distributed:
1294
+ gathered_batch_list = []
1295
+ for b in batch_list:
1296
+ flattened = gather_object(b)
1297
+ gathered_batch_list.append(flattened)
1298
+ batch_list = gathered_batch_list
1299
+
1300
+ # Log only if we are in the main process
1301
+ if self.accelerator.is_main_process:
1302
+ logs = {}
1303
+
1304
+ # Log stats
1305
+ if "query" not in batch.keys() and "response" not in batch.keys():
1306
+ # warn the user that the game logs will not be logged
1307
+ warnings.warn("The game logs will not be logged because the batch does not contain the keys 'query' and " "'response'. ")
1308
+ elif self.config.log_with == "wandb":
1309
+ table_rows = [list(r) for r in zip(*batch_list, rewards.cpu().tolist())]
1310
+ logs.update({"game_log": wandb.Table(columns=[*columns_to_log, "reward"], rows=table_rows)})
1311
+
1312
+ logs.update(stats)
1313
+
1314
+ # manually cast in fp32 for bf16 torch tensors
1315
+ for k, v in logs.items():
1316
+ if isinstance(v, torch.Tensor) and v.dtype == torch.bfloat16:
1317
+ logs[k] = v.float()
1318
+
1319
+ logs["env/reward_mean"] = torch.mean(rewards).cpu().numpy().item()
1320
+ logs["env/reward_std"] = torch.std(rewards).cpu().numpy().item()
1321
+ logs["env/reward_dist"] = rewards.cpu().numpy()
1322
+
1323
+ if self.config.log_with == "tensorboard":
1324
+ # update the current step
1325
+ self.current_step += 1
1326
+
1327
+ self.accelerator.log(
1328
+ logs,
1329
+ step=self.current_step if self.config.log_with == "tensorboard" else None,
1330
+ )
1331
+
1332
+ def create_model_card(self, path: str, model_name: Optional[str] = "TRL Model") -> None:
1333
+ """Creates and saves a model card for a TRL model.
1334
+
1335
+ Args:
1336
+ path (`str`): The path to save the model card to.
1337
+ model_name (`str`, *optional*): The name of the model, defaults to `TRL Model`.
1338
+ """
1339
+ try:
1340
+ user = whoami()["name"]
1341
+ # handle the offline case
1342
+ except: # noqa
1343
+ warnings.warn("Cannot retrieve user information assuming you are running in offline mode.")
1344
+ return
1345
+
1346
+ if not os.path.exists(path):
1347
+ os.makedirs(path)
1348
+
1349
+ model_card_content = MODEL_CARD_TEMPLATE.format(model_name=model_name, model_id=f"{user}/{path}")
1350
+ with open(os.path.join(path, "README.md"), "w", encoding="utf-8") as f:
1351
+ f.write(model_card_content)
1352
+
1353
+ def _save_pretrained(self, save_directory: str) -> None:
1354
+ self.accelerator.unwrap_model(self.model).save_pretrained(save_directory)
1355
+ self.tokenizer.save_pretrained(save_directory)
1356
+ self.create_model_card(save_directory)
1357
+
1358
+ def _show_tokens(self, tokens, masks):
1359
+ from rich import print
1360
+ from rich.text import Text
1361
+
1362
+ text = Text()
1363
+
1364
+ for i, (token, mask) in enumerate(zip(tokens, masks)):
1365
+ if mask == 1:
1366
+ text.append(self.tokenizer.decode(token.item()), style="black on deep_sky_blue1")
1367
+ text.append(" ")
1368
+ else:
1369
+ text.append(self.tokenizer.decode(token.item()), style="black on cyan3")
1370
+ text.append(" ")
1371
+ print(text)
1372
+
1373
+ def _prepare_deepspeed(self, model: PreTrainedModelWrapper):
1374
+ # Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473
1375
+ deepspeed_plugin = self.accelerator.state.deepspeed_plugin
1376
+ config_kwargs = deepspeed_plugin.deepspeed_config
1377
+ if model is not None:
1378
+ if hasattr(model, "config"):
1379
+ hidden_size = max(model.config.hidden_sizes) if getattr(model.config, "hidden_sizes", None) else getattr(model.config, "hidden_size", None)
1380
+ if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3:
1381
+ # Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0`
1382
+ # This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081
1383
+ config_kwargs.update(
1384
+ {
1385
+ "zero_optimization.reduce_bucket_size": hidden_size * hidden_size,
1386
+ "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size,
1387
+ "zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size,
1388
+ }
1389
+ )
1390
+
1391
+ # If ZeRO-3 is used, we shard both the active and reference model.
1392
+ # Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0)
1393
+ if config_kwargs["zero_optimization"]["stage"] != 3:
1394
+ config_kwargs["zero_optimization"]["stage"] = 0
1395
+ model, *_ = deepspeed.initialize(model=model, config=config_kwargs)
1396
+ model.eval()
1397
+ return model
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/reward_config.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass
16
+ from typing import Optional
17
+
18
+ from transformers import TrainingArguments
19
+
20
+
21
+ @dataclass
22
+ class RewardConfig(TrainingArguments):
23
+ """
24
+ RewardConfig collects all training arguments related to the [`RewardTrainer`] class.
25
+
26
+ Using [`HfArgumentParser`] we can turn this class into
27
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
28
+ command line.
29
+
30
+ Parameters:
31
+ max_length (`int`, *optional*, defaults to `None`):
32
+ The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator.
33
+ gradient_checkpointing (`bool`, *optional*, defaults to `True`):
34
+ If True, use gradient checkpointing to save memory at the expense of slower backward pass.
35
+ """
36
+
37
+ max_length: Optional[int] = None
38
+ """The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator."""
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/reward_trainer.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import inspect
15
+ import warnings
16
+ from dataclasses import FrozenInstanceError, replace
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ from datasets import Dataset
22
+ from transformers import DataCollator, PreTrainedModel, PreTrainedTokenizerBase, Trainer, TrainingArguments
23
+ from transformers.trainer_callback import TrainerCallback
24
+ from transformers.trainer_pt_utils import nested_detach
25
+ from transformers.trainer_utils import EvalPrediction
26
+
27
+ from ..import_utils import is_peft_available
28
+ from .reward_config import RewardConfig
29
+ from .utils import RewardDataCollatorWithPadding, compute_accuracy
30
+
31
+
32
+ if is_peft_available():
33
+ from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training
34
+
35
+
36
+ class RewardTrainer(Trainer):
37
+ r"""
38
+ The RewardTrainer can be used to train your custom Reward Model. It is a subclass of the
39
+ `transformers.Trainer` class and inherits all of its attributes and methods. It is recommended to use
40
+ an `AutoModelForSequenceClassification` as the reward model. The reward model should be trained on a dataset
41
+ of paired examples, where each example is a tuple of two sequences. The reward model should be trained to
42
+ predict which example in the pair is more relevant to the task at hand.
43
+
44
+ The reward trainer expects a very specific format for the dataset. The dataset should contain two 4 entries at least
45
+ if you don't use the default `RewardDataCollatorWithPadding` data collator. The entries should be named
46
+ - `input_ids_chosen`
47
+ - `attention_mask_chosen`
48
+ - `input_ids_rejected`
49
+ - `attention_mask_rejected`
50
+
51
+ Optionally, you can also pass a `margin` entry to the dataset. This entry should contain the margin used to modulate the
52
+ loss of the reward model as outlined in https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/.
53
+ If you don't pass a margin, no margin will be used.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ model: Union[PreTrainedModel, nn.Module] = None,
59
+ args: Optional[RewardConfig] = None,
60
+ data_collator: Optional[DataCollator] = None,
61
+ train_dataset: Optional[Dataset] = None,
62
+ eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None,
63
+ tokenizer: Optional[PreTrainedTokenizerBase] = None,
64
+ model_init: Optional[Callable[[], PreTrainedModel]] = None,
65
+ compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,
66
+ callbacks: Optional[List[TrainerCallback]] = None,
67
+ optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (
68
+ None,
69
+ None,
70
+ ),
71
+ preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
72
+ max_length: Optional[int] = None,
73
+ peft_config: Optional[Dict] = None,
74
+ ):
75
+ """
76
+ Initialize RewardTrainer.
77
+
78
+ Args:
79
+ model (`transformers.PreTrainedModel`):
80
+ The model to train, preferably an `AutoModelForSequenceClassification`.
81
+ args (`RewardConfig`):
82
+ The arguments to use for training.
83
+ data_collator (`transformers.DataCollator`):
84
+ The data collator to use for training. If None is specified, the default data collator (`RewardDataCollatorWithPadding`) will be used
85
+ which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.
86
+ train_dataset (`datasets.Dataset`):
87
+ The dataset to use for training.
88
+ eval_dataset (`datasets.Dataset`):
89
+ The dataset to use for evaluation.
90
+ tokenizer (`transformers.PreTrainedTokenizerBase`):
91
+ The tokenizer to use for training. This argument is required if you want to use the default data collator.
92
+ model_init (`Callable[[], transformers.PreTrainedModel]`):
93
+ The model initializer to use for training. If None is specified, the default model initializer will be used.
94
+ compute_metrics (`Callable[[transformers.EvalPrediction], Dict]`, *optional* defaults to `compute_accuracy`):
95
+ The metrics to use for evaluation. If no metrics are specified, the default metric (`compute_accuracy`) will be used.
96
+ callbacks (`List[transformers.TrainerCallback]`):
97
+ The callbacks to use for training.
98
+ optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
99
+ The optimizer and scheduler to use for training.
100
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
101
+ The function to use to preprocess the logits before computing the metrics.
102
+ max_length (`int`, defaults to `None`):
103
+ The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator.
104
+ peft_config (`Dict`, defaults to `None`):
105
+ The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.
106
+ """
107
+ if type(args) == TrainingArguments:
108
+ warnings.warn(
109
+ "Using `transformers.TrainingArguments` for `args` is deprecated and will be removed in a future version. Please use `RewardConfig` instead.",
110
+ FutureWarning,
111
+ )
112
+ if max_length is not None:
113
+ warnings.warn(
114
+ "The `max_length` argument is deprecated and will be removed in a future version. Please use the `RewardConfig` to set `max_length` instead.",
115
+ FutureWarning,
116
+ )
117
+ else:
118
+ if max_length is not None and args.max_length is not None:
119
+ raise ValueError("You cannot specify both `max_length` and `args.max_length`. Please use the `RewardConfig` to set `max_length` once.")
120
+ if max_length is not None and args.max_length is None:
121
+ warnings.warn(
122
+ "The `max_length` argument is deprecated and will be removed in a future version. Please use the `RewardConfig` to set `max_length` instead.",
123
+ FutureWarning,
124
+ )
125
+ if not is_peft_available() and peft_config is not None:
126
+ raise ValueError("PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models")
127
+ elif is_peft_available() and peft_config is not None:
128
+ if not isinstance(model, PeftModel):
129
+ if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_quantized", False):
130
+ _supports_gc_kwargs = "gradient_checkpointing_kwargs" in list(inspect.signature(prepare_model_for_kbit_training).parameters)
131
+
132
+ preprare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing}
133
+
134
+ if not _supports_gc_kwargs and args.gradient_checkpointing_kwargs is not None:
135
+ warnings.warn("You passed `gradient_checkpointing_kwargs` in the trainer's kwargs, but your peft version does not support it. " "please update to the latest version of peft to use `gradient_checkpointing_kwargs`.")
136
+ elif _supports_gc_kwargs and args.gradient_checkpointing_kwargs is not None:
137
+ preprare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs
138
+
139
+ model = prepare_model_for_kbit_training(model, **preprare_model_kwargs)
140
+
141
+ model = get_peft_model(model, peft_config)
142
+
143
+ if compute_metrics is None:
144
+ compute_metrics = compute_accuracy
145
+
146
+ if data_collator is None:
147
+ if tokenizer is None:
148
+ raise ValueError("max_length or a tokenizer must be specified when using the default RewardDataCollatorWithPadding")
149
+ if type(args) == TrainingArguments:
150
+ if max_length is None:
151
+ warnings.warn(
152
+ "When using RewardDataCollatorWithPadding, you should set `max_length` in RewardConfig." " It will be set to `512` by default, but you should do it yourself in the future.",
153
+ UserWarning,
154
+ )
155
+ max_length = 512
156
+ else:
157
+ if max_length is None and args.max_length is None:
158
+ warnings.warn(
159
+ "When using RewardDataCollatorWithPadding, you should set `max_length` in RewardConfig." " It will be set to `512` by default, but you should do it yourself in the future.",
160
+ UserWarning,
161
+ )
162
+ max_length = 512
163
+ if max_length is None and args.max_length is not None:
164
+ max_length = args.max_length
165
+
166
+ data_collator = RewardDataCollatorWithPadding(tokenizer, max_length=max_length)
167
+
168
+ if args.remove_unused_columns:
169
+ try: # for bc before https://github.com/huggingface/transformers/pull/25435
170
+ args.remove_unused_columns = False
171
+ except FrozenInstanceError:
172
+ args = replace(args, remove_unused_columns=False)
173
+ # warn users
174
+ warnings.warn(
175
+ "When using RewardDataCollatorWithPadding, you should set `remove_unused_columns=False` in your RewardConfig" " we have set it for you, but you should do it yourself in the future.",
176
+ UserWarning,
177
+ )
178
+
179
+ self.use_reward_data_collator = True
180
+ else:
181
+ self.use_reward_data_collator = False
182
+ super().__init__(
183
+ model,
184
+ args,
185
+ data_collator,
186
+ train_dataset,
187
+ eval_dataset,
188
+ tokenizer,
189
+ model_init,
190
+ compute_metrics,
191
+ callbacks,
192
+ optimizers,
193
+ preprocess_logits_for_metrics,
194
+ )
195
+
196
+ def compute_loss(
197
+ self,
198
+ model: Union[PreTrainedModel, nn.Module],
199
+ inputs: Dict[str, Union[torch.Tensor, Any]],
200
+ return_outputs=False,
201
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]:
202
+ if not self.use_reward_data_collator:
203
+ warnings.warn("The current compute_loss is implemented for RewardDataCollatorWithPadding," " if you are using a custom data collator make sure you know what you are doing or" " implement your own compute_loss method.")
204
+ rewards_chosen = model(
205
+ input_ids=inputs["input_ids_chosen"],
206
+ attention_mask=inputs["attention_mask_chosen"],
207
+ return_dict=True,
208
+ )["logits"]
209
+ rewards_rejected = model(
210
+ input_ids=inputs["input_ids_rejected"],
211
+ attention_mask=inputs["attention_mask_rejected"],
212
+ return_dict=True,
213
+ )["logits"]
214
+ # calculate loss, optionally modulate with margin
215
+ if "margin" in inputs:
216
+ loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected - inputs["margin"]).mean()
217
+ else:
218
+ loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected).mean()
219
+
220
+ if return_outputs:
221
+ return loss, {
222
+ "rewards_chosen": rewards_chosen,
223
+ "rewards_rejected": rewards_rejected,
224
+ }
225
+ return loss
226
+
227
+ def prediction_step(
228
+ self,
229
+ model: Union[PreTrainedModel, nn.Module],
230
+ inputs: Dict[str, Union[torch.Tensor, Any]],
231
+ prediction_loss_only: bool,
232
+ ignore_keys: Optional[List[str]] = None,
233
+ ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]:
234
+ inputs = self._prepare_inputs(inputs)
235
+ if ignore_keys is None:
236
+ if hasattr(self.model, "config"):
237
+ ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", [])
238
+ else:
239
+ ignore_keys = []
240
+
241
+ with torch.no_grad():
242
+ loss, logits_dict = self.compute_loss(model, inputs, return_outputs=True)
243
+
244
+ if prediction_loss_only:
245
+ return (loss, None, None)
246
+
247
+ loss = loss.detach()
248
+ logits = tuple(v for k, v in logits_dict.items() if k not in ignore_keys)
249
+ logits = nested_detach(logits)
250
+ # Stack accepted against rejected, mean over logits
251
+ # and softmax to get preferences between accepted and rejected to sum to 1
252
+ logits = torch.stack(logits).mean(dim=2).softmax(dim=0).T
253
+
254
+ labels = torch.zeros(logits.shape[0])
255
+ labels = self._prepare_inputs(labels)
256
+
257
+ return loss, logits, labels
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/sft_trainer.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import dataclasses
15
+ import inspect
16
+ import warnings
17
+ from functools import wraps
18
+ from typing import Callable, Dict, List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ from accelerate.state import PartialState
23
+ from datasets import Dataset
24
+ from datasets.arrow_writer import SchemaInferenceError
25
+ from datasets.builder import DatasetGenerationError
26
+ from transformers import (
27
+ AutoModelForCausalLM,
28
+ AutoTokenizer,
29
+ DataCollator,
30
+ DataCollatorForLanguageModeling,
31
+ PreTrainedModel,
32
+ PreTrainedTokenizerBase,
33
+ Trainer,
34
+ TrainingArguments,
35
+ )
36
+ from transformers.modeling_utils import unwrap_model
37
+ from transformers.trainer_callback import TrainerCallback
38
+ from transformers.trainer_utils import EvalPrediction
39
+
40
+ from ..extras.dataset_formatting import get_formatting_func_from_dataset
41
+ from ..import_utils import is_peft_available
42
+ from .utils import (
43
+ ConstantLengthDataset,
44
+ DataCollatorForCompletionOnlyLM,
45
+ neftune_post_forward_hook,
46
+ peft_module_casting_to_bf16,
47
+ trl_sanitze_kwargs_for_tagging,
48
+ )
49
+
50
+
51
+ if is_peft_available():
52
+ from peft import PeftConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training
53
+
54
+
55
+ class SFTTrainer(Trainer):
56
+ r"""
57
+ Class definition of the Supervised Finetuning Trainer (SFT Trainer).
58
+ This class is a wrapper around the `transformers.Trainer` class and inherits all of its attributes and methods.
59
+ The trainer takes care of properly initializing the PeftModel in case a user passes a `PeftConfig` object.
60
+
61
+ Args:
62
+ model (Union[`transformers.PreTrainedModel`, `nn.Module`, `str`]):
63
+ The model to train, can be a `PreTrainedModel`, a `torch.nn.Module` or a string with the model name to
64
+ load from cache or download. The model can be also converted to a `PeftModel` if a `PeftConfig` object is
65
+ passed to the `peft_config` argument.
66
+ args (Optional[`transformers.TrainingArguments`]):
67
+ The arguments to tweak for training. Please refer to the official documentation of `transformers.TrainingArguments`
68
+ for more information.
69
+ data_collator (Optional[`transformers.DataCollator`]):
70
+ The data collator to use for training.
71
+ train_dataset (Optional[`datasets.Dataset`]):
72
+ The dataset to use for training. We recommend users to use `trl.trainer.ConstantLengthDataset` to create their dataset.
73
+ eval_dataset (Optional[Union[`datasets.Dataset`, Dict[`str`, `datasets.Dataset`]]]):
74
+ The dataset to use for evaluation. We recommend users to use `trl.trainer.ConstantLengthDataset` to create their dataset.
75
+ tokenizer (Optional[`transformers.PreTrainedTokenizer`]):
76
+ The tokenizer to use for training. If not specified, the tokenizer associated to the model will be used.
77
+ model_init (`Callable[[], transformers.PreTrainedModel]`):
78
+ The model initializer to use for training. If None is specified, the default model initializer will be used.
79
+ compute_metrics (`Callable[[transformers.EvalPrediction], Dict]`, *optional* defaults to None):
80
+ The function used to compute metrics during evaluation. It should return a dictionary mapping metric names to metric values.
81
+ If not specified, only the loss will be computed during evaluation.
82
+ callbacks (`List[transformers.TrainerCallback]`):
83
+ The callbacks to use for training.
84
+ optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
85
+ The optimizer and scheduler to use for training.
86
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
87
+ The function to use to preprocess the logits before computing the metrics.
88
+ peft_config (`Optional[PeftConfig]`):
89
+ The PeftConfig object to use to initialize the PeftModel.
90
+ dataset_text_field (`Optional[str]`):
91
+ The name of the text field of the dataset, in case this is passed by a user, the trainer will automatically create a
92
+ `ConstantLengthDataset` based on the `dataset_text_field` argument.
93
+ formatting_func (`Optional[Callable]`):
94
+ The formatting function to be used for creating the `ConstantLengthDataset`.
95
+ max_seq_length (`Optional[int]`):
96
+ The maximum sequence length to use for the `ConstantLengthDataset` and for automatically creating the Dataset. Defaults to `512`.
97
+ infinite (`Optional[bool]`):
98
+ Whether to use an infinite dataset or not. Defaults to `False`.
99
+ num_of_sequences (`Optional[int]`):
100
+ The number of sequences to use for the `ConstantLengthDataset`. Defaults to `1024`.
101
+ chars_per_token (`Optional[float]`):
102
+ The number of characters per token to use for the `ConstantLengthDataset`. Defaults to `3.6`. You can check how this is computed in the
103
+ stack-llama example: https://github.com/huggingface/trl/blob/08f550674c553c36c51d1027613c29f14f3676a5/examples/stack_llama/scripts/supervised_finetuning.py#L53.
104
+ packing (`Optional[bool]`):
105
+ Used only in case `dataset_text_field` is passed. This argument is used by the `ConstantLengthDataset` to pack the sequences
106
+ of the dataset.
107
+ dataset_num_proc (`Optional[int]`):
108
+ The number of workers to use to tokenize the data. Only used when `packing=False`. Defaults to None.
109
+ dataset_batch_size (`int`):
110
+ The number of examples to tokenize per batch. If batch_size <= 0 or batch_size == None,
111
+ tokenize the full dataset as a single batch. Defaults to 1000.
112
+ neftune_noise_alpha (`Optional[float]`):
113
+ If not `None`, this will activate NEFTune noise embeddings. This has been proven to drastically improve model performances for instruction
114
+ fine-tuning. Check out the original paper here: https://arxiv.org/abs/2310.05914 and the original code here: https://github.com/neelsjain/NEFTune
115
+ model_init_kwargs: (`Optional[Dict]`, *optional*):
116
+ Dict of Optional kwargs to pass when instantiating the model from a string
117
+ dataset_kwargs: (`Optional[Dict]`, *optional*):
118
+ Dict of Optional kwargs to pass when creating packed or non-packed datasets
119
+ """
120
+
121
+ _tag_names = ["trl", "sft"]
122
+
123
+ def __init__(
124
+ self,
125
+ model: Union[PreTrainedModel, nn.Module, str] = None,
126
+ args: TrainingArguments = None,
127
+ data_collator: Optional[DataCollator] = None,
128
+ train_dataset: Optional[Dataset] = None,
129
+ eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None,
130
+ tokenizer: Optional[PreTrainedTokenizerBase] = None,
131
+ model_init: Optional[Callable[[], PreTrainedModel]] = None,
132
+ compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,
133
+ callbacks: Optional[List[TrainerCallback]] = None,
134
+ optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
135
+ preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
136
+ peft_config: Optional["PeftConfig"] = None,
137
+ dataset_text_field: Optional[str] = None,
138
+ packing: Optional[bool] = False,
139
+ formatting_func: Optional[Callable] = None,
140
+ max_seq_length: Optional[int] = None,
141
+ infinite: Optional[bool] = None,
142
+ num_of_sequences: Optional[int] = 1024,
143
+ chars_per_token: Optional[float] = 3.6,
144
+ dataset_num_proc: Optional[int] = None,
145
+ dataset_batch_size: int = 1000,
146
+ neftune_noise_alpha: Optional[float] = None,
147
+ model_init_kwargs: Optional[Dict] = None,
148
+ dataset_kwargs: Optional[Dict] = None,
149
+ ):
150
+ if model_init_kwargs is None:
151
+ model_init_kwargs = {}
152
+ elif not isinstance(model, str):
153
+ raise ValueError("You passed model_kwargs to the SFTTrainer. But your model is already instantiated.")
154
+
155
+ if infinite is not None:
156
+ warnings.warn("The `infinite` argument is deprecated and will be removed in a future version of TRL. Use `TrainingArguments.max_steps` or `TrainingArguments.num_train_epochs` instead to control training length.")
157
+
158
+ if isinstance(model, str):
159
+ warnings.warn("You passed a model_id to the SFTTrainer. This will automatically create an " "`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you.")
160
+ model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
161
+
162
+ if packing and data_collator is not None and isinstance(data_collator, DataCollatorForCompletionOnlyLM):
163
+ raise ValueError("You passed a `DataCollatorForCompletionOnlyLM` to the SFTTrainer. This is not compatible with the `packing` argument.")
164
+
165
+ if is_peft_available() and peft_config is not None:
166
+ if not isinstance(peft_config, PeftConfig):
167
+ raise ValueError("If you want to use the PeftModel, you need to pass a PeftConfig object to the SFTTrainer." f" and you passed a {type(peft_config)}.")
168
+
169
+ if not isinstance(model, PeftModel):
170
+ _support_gc_kwargs = hasattr(args, "gradient_checkpointing_kwargs") and "gradient_checkpointing_kwargs" in list(inspect.signature(prepare_model_for_kbit_training).parameters)
171
+ gradient_checkpointing_kwargs = getattr(args, "gradient_checkpointing_kwargs", None) or {}
172
+ if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False):
173
+ preprare_model_kwargs = {"use_gradient_checkpointing": getattr(args, "gradient_checkpointing", False)}
174
+
175
+ if _support_gc_kwargs:
176
+ preprare_model_kwargs["gradient_checkpointing_kwargs"] = gradient_checkpointing_kwargs
177
+
178
+ model = prepare_model_for_kbit_training(model, **preprare_model_kwargs)
179
+
180
+ if args is not None:
181
+ args = dataclasses.replace(args, gradient_checkpointing=False)
182
+ elif getattr(args, "gradient_checkpointing", False) and ("use_reentrant" not in gradient_checkpointing_kwargs or gradient_checkpointing_kwargs["use_reentrant"]):
183
+ # For backward compatibility with older versions of transformers
184
+ if hasattr(model, "enable_input_require_grads"):
185
+ model.enable_input_require_grads()
186
+ else:
187
+
188
+ def make_inputs_require_grad(module, input, output):
189
+ output.requires_grad_(True)
190
+
191
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
192
+
193
+ model = get_peft_model(model, peft_config)
194
+ if args.bf16 and getattr(model, "is_loaded_in_4bit", False):
195
+ peft_module_casting_to_bf16(model)
196
+
197
+ if tokenizer is None:
198
+ tokenizer = AutoTokenizer.from_pretrained(model.config._name_or_path)
199
+ if getattr(tokenizer, "pad_token", None) is None:
200
+ tokenizer.pad_token = tokenizer.eos_token
201
+
202
+ if max_seq_length is None:
203
+ # to overcome some issues with broken tokenizers
204
+ max_seq_length = min(tokenizer.model_max_length, 1024)
205
+
206
+ warnings.warn(f"You didn't pass a `max_seq_length` argument to the SFTTrainer, this will default to {max_seq_length}")
207
+
208
+ self.dataset_num_proc = dataset_num_proc
209
+ self.dataset_batch_size = dataset_batch_size
210
+
211
+ self._trainer_supports_neftune = hasattr(args, "neftune_noise_alpha")
212
+
213
+ if neftune_noise_alpha is not None and self._trainer_supports_neftune:
214
+ args.neftune_noise_alpha = neftune_noise_alpha
215
+ warnings.warn("You passed a `neftune_noise_alpha` argument to the SFTTrainer, the value you passed will override the one in the `TrainingArguments`.")
216
+ # self.neftune_noise_alpha is done at Trainer level
217
+ elif not self._trainer_supports_neftune:
218
+ self.neftune_noise_alpha = neftune_noise_alpha
219
+
220
+ if formatting_func is None and dataset_text_field is None:
221
+ # check if dataset has ChatML format or instruction format and is supported
222
+ # if not stays #None
223
+ formatting_func = get_formatting_func_from_dataset(train_dataset, tokenizer)
224
+
225
+ if not packing:
226
+ if dataset_text_field is None and formatting_func is None:
227
+ raise ValueError("You passed `packing=False` to the SFTTrainer, but you didn't pass a `dataset_text_field` or `formatting_func` argument.")
228
+
229
+ if data_collator is None:
230
+ data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
231
+
232
+ # Pre-process the datasets only once per node. The remaining processes will use the cache.
233
+ with PartialState().local_main_process_first():
234
+ if dataset_kwargs is None:
235
+ dataset_kwargs = {}
236
+ if train_dataset is not None:
237
+ train_dataset = self._prepare_dataset(
238
+ train_dataset,
239
+ tokenizer,
240
+ packing,
241
+ dataset_text_field,
242
+ max_seq_length,
243
+ formatting_func,
244
+ num_of_sequences,
245
+ chars_per_token,
246
+ remove_unused_columns=args.remove_unused_columns if args is not None else True,
247
+ **dataset_kwargs,
248
+ )
249
+ if eval_dataset is not None:
250
+ _multiple = isinstance(eval_dataset, dict)
251
+ _eval_datasets = eval_dataset if _multiple else {"singleton": eval_dataset}
252
+ for _eval_dataset_name, _eval_dataset in _eval_datasets.items():
253
+ _eval_datasets[_eval_dataset_name] = self._prepare_dataset(
254
+ _eval_dataset,
255
+ tokenizer,
256
+ packing,
257
+ dataset_text_field,
258
+ max_seq_length,
259
+ formatting_func,
260
+ num_of_sequences,
261
+ chars_per_token,
262
+ remove_unused_columns=args.remove_unused_columns if args is not None else True,
263
+ **dataset_kwargs,
264
+ )
265
+ if not _multiple:
266
+ eval_dataset = _eval_datasets["singleton"]
267
+
268
+ if tokenizer.padding_side is not None and tokenizer.padding_side != "right":
269
+ warnings.warn(
270
+ "You passed a tokenizer with `padding_side` not equal to `right` to the SFTTrainer. This might lead to some unexpected behaviour due to "
271
+ "overflow issues when training a model in half-precision. You might consider adding `tokenizer.padding_side = 'right'` to your code."
272
+ )
273
+
274
+ super().__init__(
275
+ model=model,
276
+ args=args,
277
+ data_collator=data_collator,
278
+ train_dataset=train_dataset,
279
+ eval_dataset=eval_dataset,
280
+ tokenizer=tokenizer,
281
+ model_init=model_init,
282
+ compute_metrics=compute_metrics,
283
+ callbacks=callbacks,
284
+ optimizers=optimizers,
285
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
286
+ )
287
+
288
+ if self.args.max_steps > 0 and packing:
289
+ warnings.warn("You passed `packing=True` to the SFTTrainer, and you are training your model with `max_steps` strategy. The dataset will be iterated until the `max_steps` are reached.")
290
+ self.train_dataset.infinite = True
291
+ elif self.args.max_steps == -1 and packing:
292
+ self.train_dataset.infinite = False
293
+
294
+ @wraps(Trainer.train)
295
+ def train(self, *args, **kwargs):
296
+ # Activate neftune right before training.
297
+ if self.neftune_noise_alpha is not None and not self._trainer_supports_neftune:
298
+ self.model = self._trl_activate_neftune(self.model)
299
+
300
+ output = super().train(*args, **kwargs)
301
+
302
+ # After training we make sure to retrieve back the original forward pass method
303
+ # for the embedding layer by removing the forward post hook.
304
+ if self.neftune_noise_alpha is not None and not self._trainer_supports_neftune:
305
+ unwrapped_model = unwrap_model(self.model)
306
+ if is_peft_available() and isinstance(unwrapped_model, PeftModel):
307
+ embeddings = unwrapped_model.base_model.model.get_input_embeddings()
308
+ else:
309
+ embeddings = unwrapped_model.get_input_embeddings()
310
+
311
+ self.neftune_hook_handle.remove()
312
+ del embeddings.neftune_noise_alpha
313
+
314
+ return output
315
+
316
+ @wraps(Trainer.push_to_hub)
317
+ def push_to_hub(self, commit_message: Optional[str] = "End of training", blocking: bool = True, **kwargs) -> str:
318
+ """
319
+ Overwrite the `push_to_hub` method in order to force-add the tag "sft" when pushing the
320
+ model on the Hub. Please refer to `~transformers.Trainer.push_to_hub` for more details.
321
+ """
322
+ kwargs = trl_sanitze_kwargs_for_tagging(model=self.model, tag_names=self._tag_names, kwargs=kwargs)
323
+
324
+ return super().push_to_hub(commit_message=commit_message, blocking=blocking, **kwargs)
325
+
326
+ def _prepare_dataset(
327
+ self,
328
+ dataset,
329
+ tokenizer,
330
+ packing,
331
+ dataset_text_field,
332
+ max_seq_length,
333
+ formatting_func,
334
+ num_of_sequences,
335
+ chars_per_token,
336
+ remove_unused_columns=True,
337
+ append_concat_token=True,
338
+ add_special_tokens=True,
339
+ ):
340
+ if dataset is None:
341
+ raise ValueError("The dataset should not be None")
342
+
343
+ # check if torch dataset / dataloader and do nothing
344
+ if isinstance(dataset, (torch.utils.data.IterableDataset, torch.utils.data.Dataset, ConstantLengthDataset)):
345
+ return dataset
346
+
347
+ if not packing:
348
+ return self._prepare_non_packed_dataloader(
349
+ tokenizer,
350
+ dataset,
351
+ dataset_text_field,
352
+ max_seq_length,
353
+ formatting_func,
354
+ add_special_tokens,
355
+ remove_unused_columns,
356
+ )
357
+
358
+ else:
359
+ return self._prepare_packed_dataloader(
360
+ tokenizer,
361
+ dataset,
362
+ dataset_text_field,
363
+ max_seq_length,
364
+ num_of_sequences,
365
+ chars_per_token,
366
+ formatting_func,
367
+ append_concat_token,
368
+ add_special_tokens,
369
+ )
370
+
371
+ def _prepare_non_packed_dataloader(
372
+ self,
373
+ tokenizer,
374
+ dataset,
375
+ dataset_text_field,
376
+ max_seq_length,
377
+ formatting_func=None,
378
+ add_special_tokens=True,
379
+ remove_unused_columns=True,
380
+ ):
381
+ use_formatting_func = formatting_func is not None and dataset_text_field is None
382
+ self._dataset_sanity_checked = False
383
+
384
+ # Inspired from: https://huggingface.co/learn/nlp-course/chapter7/6?fw=pt
385
+ def tokenize(element):
386
+ outputs = tokenizer(
387
+ element[dataset_text_field] if not use_formatting_func else formatting_func(element),
388
+ add_special_tokens=add_special_tokens,
389
+ truncation=True,
390
+ padding=False,
391
+ max_length=max_seq_length,
392
+ return_overflowing_tokens=False,
393
+ return_length=False,
394
+ )
395
+
396
+ if use_formatting_func and not self._dataset_sanity_checked:
397
+ if not isinstance(formatting_func(element), list):
398
+ raise ValueError("The `formatting_func` should return a list of processed strings since it can lead to silent bugs.")
399
+ else:
400
+ self._dataset_sanity_checked = True
401
+
402
+ return {"input_ids": outputs["input_ids"], "attention_mask": outputs["attention_mask"]}
403
+
404
+ signature_columns = ["input_ids", "labels", "attention_mask"]
405
+
406
+ extra_columns = list(set(dataset.column_names) - set(signature_columns))
407
+
408
+ if not remove_unused_columns and len(extra_columns) > 0:
409
+ warnings.warn(
410
+ "You passed `remove_unused_columns=False` on a non-packed dataset. This might create some issues with the default collator and yield to errors. If you want to "
411
+ f"inspect dataset other columns (in this case {extra_columns}), you can subclass `DataCollatorForLanguageModeling` in case you used the default collator and create your own data collator in order to inspect the unused dataset columns."
412
+ )
413
+
414
+ tokenized_dataset = dataset.map(
415
+ tokenize,
416
+ batched=True,
417
+ remove_columns=dataset.column_names if remove_unused_columns else None,
418
+ num_proc=self.dataset_num_proc,
419
+ batch_size=self.dataset_batch_size,
420
+ )
421
+
422
+ return tokenized_dataset
423
+
424
+ def _prepare_packed_dataloader(
425
+ self,
426
+ tokenizer,
427
+ dataset,
428
+ dataset_text_field,
429
+ max_seq_length,
430
+ num_of_sequences,
431
+ chars_per_token,
432
+ formatting_func=None,
433
+ append_concat_token=True,
434
+ add_special_tokens=True,
435
+ ):
436
+ if dataset_text_field is not None or formatting_func is not None:
437
+ if tokenizer is None:
438
+ raise ValueError("You need to pass a tokenizer when using `dataset_text_field` with `SFTTrainer`.")
439
+
440
+ constant_length_iterator = ConstantLengthDataset(
441
+ tokenizer,
442
+ dataset,
443
+ dataset_text_field=dataset_text_field,
444
+ formatting_func=formatting_func,
445
+ seq_length=max_seq_length,
446
+ infinite=False,
447
+ num_of_sequences=num_of_sequences,
448
+ chars_per_token=chars_per_token,
449
+ eos_token_id=tokenizer.eos_token_id,
450
+ append_concat_token=append_concat_token,
451
+ add_special_tokens=add_special_tokens,
452
+ )
453
+
454
+ def data_generator(constant_length_iterator):
455
+ for i in constant_length_iterator:
456
+ yield i
457
+
458
+ try:
459
+ packed_dataset = Dataset.from_generator(data_generator, gen_kwargs={"constant_length_iterator": constant_length_iterator})
460
+ except (DatasetGenerationError, SchemaInferenceError):
461
+ raise ValueError("Error occurred while packing the dataset. Make sure that your dataset has enough samples to at least yield one packed sequence.")
462
+ return packed_dataset
463
+ else:
464
+ raise ValueError("You need to pass a `dataset_text_field` or `formatting_func` argument to the SFTTrainer if you want to use the `ConstantLengthDataset`.")
465
+
466
+ def _trl_activate_neftune(self, model):
467
+ r"""
468
+ Activates the neftune as presented in this code: https://github.com/neelsjain/NEFTune and paper: https://arxiv.org/abs/2310.05914
469
+ Since in transformers Trainer we do have an `_activate_neftune` method, we need to rename this method to avoid conflicts.
470
+ """
471
+ unwrapped_model = unwrap_model(model)
472
+ if is_peft_available() and isinstance(unwrapped_model, PeftModel):
473
+ embeddings = unwrapped_model.base_model.model.get_input_embeddings()
474
+ else:
475
+ embeddings = unwrapped_model.get_input_embeddings()
476
+
477
+ embeddings.neftune_noise_alpha = self.neftune_noise_alpha
478
+ hook_handle = embeddings.register_forward_hook(neftune_post_forward_hook)
479
+ self.neftune_hook_handle = hook_handle
480
+ return model
之前的代码版本/第一版-全部代码/MedEvalKit-v1-v1-fullcode/LLaVA-NeXT/trl/trainer/utils.py ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import random
15
+ import warnings
16
+ from collections import deque
17
+ from dataclasses import dataclass
18
+ from typing import Any, Dict, List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+ from accelerate import PartialState
23
+ from torch.nn.utils.rnn import pad_sequence
24
+ from torch.utils.data import IterableDataset
25
+ from transformers import BitsAndBytesConfig, DataCollatorForLanguageModeling, PreTrainedTokenizerBase
26
+
27
+ from ..import_utils import is_peft_available, is_unsloth_available, is_xpu_available
28
+ from ..trainer.model_config import ModelConfig
29
+
30
+
31
+ if is_peft_available():
32
+ from peft import LoraConfig, PeftConfig
33
+
34
+
35
+ class AdaptiveKLController:
36
+ """
37
+ Adaptive KL controller described in the paper:
38
+ https://arxiv.org/pdf/1909.08593.pdf
39
+ """
40
+
41
+ def __init__(self, init_kl_coef, target, horizon):
42
+ self.value = init_kl_coef
43
+ self.target = target
44
+ self.horizon = horizon
45
+
46
+ def update(self, current, n_steps):
47
+ target = self.target
48
+ proportional_error = np.clip(current / target - 1, -0.2, 0.2)
49
+ mult = 1 + proportional_error * n_steps / self.horizon
50
+ self.value *= mult
51
+
52
+
53
+ class FixedKLController:
54
+ """Fixed KL controller."""
55
+
56
+ def __init__(self, kl_coef):
57
+ self.value = kl_coef
58
+
59
+ def update(self, current, n_steps):
60
+ pass
61
+
62
+
63
+ class DataCollatorForCompletionOnlyLM(DataCollatorForLanguageModeling):
64
+ """
65
+ Data collator used for completion tasks. It ensures that all the tokens of the labels are set to an 'ignore_index'
66
+ when they do not come from the assistant. This ensure that the loss is only
67
+ calculated on the completion made by the assistant.
68
+
69
+ Args:
70
+ response_template (`Union[str, List[int]]`): the template form that indicates the start of the response, typically something like
71
+ '### Response:\n'. It can also be passed as tokenized ids, which can be useful when using a tokenizer that encodes the response
72
+ differently if it does not have proper context.
73
+ instruction_template (`Union[str, List[int]]`): the template form that indicates the start of the human instruction, typically something like
74
+ '### Human:\n'. Useful for assistant-style conversation datasets. It can also be passed as tokenized ids.
75
+ mlm (`bool`, *optional*, defaults to `False`): Whether or not to use masked language modeling in the underlying
76
+ `DataCollatorForLanguageModeling` class. Note that this option currently has no effect but is present
77
+ for flexibility and backwards-compatibility.
78
+ ignore_index (`int`, *optional*, defaults to `-100`):
79
+ The index to use to ignore the initial tokens with
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ response_template: Union[str, List[int]],
85
+ instruction_template: Union[str, List[int]] = None,
86
+ *args,
87
+ mlm: bool = False,
88
+ ignore_index: int = -100,
89
+ **kwargs,
90
+ ):
91
+ super().__init__(*args, mlm=mlm, **kwargs)
92
+
93
+ self.instruction_template = instruction_template
94
+ if isinstance(instruction_template, str):
95
+ # The user provides a string, must tokenize
96
+ self.instruction_token_ids = self.tokenizer.encode(self.instruction_template, add_special_tokens=False)
97
+ else:
98
+ # The user already provides the token ids
99
+ self.instruction_token_ids = instruction_template
100
+
101
+ self.response_template = response_template
102
+ if isinstance(response_template, str):
103
+ # The user provides a string, must tokenize
104
+ self.response_token_ids = self.tokenizer.encode(self.response_template, add_special_tokens=False)
105
+ else:
106
+ # The user already provides the token ids
107
+ self.response_token_ids = response_template
108
+
109
+ if not self.mlm and self.instruction_template and self.tokenizer.pad_token_id == self.tokenizer.eos_token_id:
110
+ warnings.warn(
111
+ "The pad_token_id and eos_token_id values of this tokenizer are identical. "
112
+ "If you are planning for multi-turn training, "
113
+ "it can result in the model continuously generating questions and answers without eos token. "
114
+ "To avoid this, set the pad_token_id to a different value."
115
+ )
116
+
117
+ self.ignore_index = ignore_index
118
+
119
+ def torch_call(self, examples: List[Union[List[int], Any, Dict[str, Any]]]) -> Dict[str, Any]:
120
+ batch = super().torch_call(examples)
121
+
122
+ if self.instruction_template is None:
123
+ for i in range(len(examples)):
124
+ response_token_ids_start_idx = None
125
+
126
+ for idx in np.where(batch["labels"][i] == self.response_token_ids[0])[0]:
127
+ # `response_token_ids` is `'### Response:\n'`, here we are just making sure that the token IDs match
128
+ if self.response_token_ids == batch["labels"][i][idx : idx + len(self.response_token_ids)].tolist():
129
+ response_token_ids_start_idx = idx
130
+
131
+ if response_token_ids_start_idx is None:
132
+ warnings.warn(
133
+ f"Could not find response key `{self.response_template}` in the "
134
+ f'following instance: {self.tokenizer.decode(batch["input_ids"][i])} '
135
+ f"This instance will be ignored in loss calculation. "
136
+ f"Note, if this happens often, consider increasing the `max_seq_length`."
137
+ )
138
+ batch["labels"][i, :] = self.ignore_index
139
+ else:
140
+ response_token_ids_end_idx = response_token_ids_start_idx + len(self.response_token_ids)
141
+
142
+ # Make pytorch loss function ignore all tokens up through the end of the response key
143
+ batch["labels"][i, :response_token_ids_end_idx] = self.ignore_index
144
+
145
+ else:
146
+ for i in range(len(examples)):
147
+ response_token_ids_idxs = []
148
+ human_token_ids_idxs = []
149
+
150
+ for assistant_idx in np.where(batch["labels"][i] == self.response_token_ids[0])[0]:
151
+ # find the indexes of the start of a response.
152
+ if self.response_token_ids == batch["labels"][i][assistant_idx : assistant_idx + len(self.response_token_ids)].tolist():
153
+ response_token_ids_idxs.append(assistant_idx + len(self.response_token_ids))
154
+
155
+ if len(response_token_ids_idxs) == 0:
156
+ warnings.warn(
157
+ f"Could not find response key `{self.response_template}` in the "
158
+ f'following instance: {self.tokenizer.decode(batch["input_ids"][i])} '
159
+ f"This instance will be ignored in loss calculation. "
160
+ f"Note, if this happens often, consider increasing the `max_seq_length`."
161
+ )
162
+ batch["labels"][i, :] = self.ignore_index
163
+
164
+ human_token_ids = self.instruction_token_ids
165
+ for human_idx in np.where(batch["labels"][i] == human_token_ids[0])[0]:
166
+ # find the indexes of the start of a human answer.
167
+ if human_token_ids == batch["labels"][i][human_idx : human_idx + len(human_token_ids)].tolist():
168
+ human_token_ids_idxs.append(human_idx)
169
+
170
+ if len(human_token_ids_idxs) == 0:
171
+ warnings.warn(
172
+ f"Could not find instruction key `{self.instruction_template}` in the "
173
+ f'following instance: {self.tokenizer.decode(batch["input_ids"][i])} '
174
+ f"This instance will be ignored in loss calculation. "
175
+ f"Note, if this happens often, consider increasing the `max_seq_length`."
176
+ )
177
+ batch["labels"][i, :] = self.ignore_index
178
+
179
+ if len(human_token_ids_idxs) > 0 and len(response_token_ids_idxs) > 0 and human_token_ids_idxs[0] > response_token_ids_idxs[0]:
180
+ human_token_ids_idxs = [0] + human_token_ids_idxs
181
+
182
+ for idx, (start, end) in enumerate(zip(human_token_ids_idxs, response_token_ids_idxs)):
183
+ # Make pytorch loss function ignore all non response tokens
184
+ if idx != 0:
185
+ batch["labels"][i, start:end] = self.ignore_index
186
+ else:
187
+ batch["labels"][i, :end] = self.ignore_index
188
+
189
+ if len(response_token_ids_idxs) < len(human_token_ids_idxs):
190
+ batch["labels"][i, human_token_ids_idxs[-1] :] = self.ignore_index
191
+
192
+ return batch
193
+
194
+
195
+ @dataclass
196
+ class RewardDataCollatorWithPadding:
197
+ r"""
198
+ Reward DataCollator class that pads the inputs to the maximum length of the batch.
199
+ Args:
200
+ tokenizer (`PreTrainedTokenizerBase`):
201
+ The tokenizer used for encoding the data.
202
+ padding (`Union[bool, str, `PaddingStrategy`]`, `optional`, defaults to `True`):
203
+ padding_strategy to pass to the tokenizer.
204
+ max_length (`Optional[int]`, `optional`, defaults to `None`):
205
+ The maximum length of the sequence to be processed.
206
+ pad_to_multiple_of (`Optional[int]`, `optional`, defaults to `None`):
207
+ If set will pad the sequence to a multiple of the provided value.
208
+ return_tensors (`str`, `optional`, defaults to `"pt"`):
209
+ The tensor type to use.
210
+ """
211
+
212
+ tokenizer: PreTrainedTokenizerBase
213
+ padding: Union[bool, str] = True
214
+ max_length: Optional[int] = None
215
+ pad_to_multiple_of: Optional[int] = None
216
+ return_tensors: str = "pt"
217
+
218
+ def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
219
+ features_chosen = []
220
+ features_rejected = []
221
+ margin = []
222
+ # check if we have a margin. If we do, we need to batch it as well
223
+ has_margin = "margin" in features[0]
224
+ for feature in features:
225
+ # check if the keys are named as expected
226
+ if "input_ids_chosen" not in feature or "input_ids_rejected" not in feature or "attention_mask_chosen" not in feature or "attention_mask_rejected" not in feature:
227
+ raise ValueError("The features should include `input_ids_chosen`, `attention_mask_chosen`, `input_ids_rejected` and `attention_mask_rejected`")
228
+
229
+ features_chosen.append(
230
+ {
231
+ "input_ids": feature["input_ids_chosen"],
232
+ "attention_mask": feature["attention_mask_chosen"],
233
+ }
234
+ )
235
+ features_rejected.append(
236
+ {
237
+ "input_ids": feature["input_ids_rejected"],
238
+ "attention_mask": feature["attention_mask_rejected"],
239
+ }
240
+ )
241
+ if has_margin:
242
+ margin.append(feature["margin"])
243
+ batch_chosen = self.tokenizer.pad(
244
+ features_chosen,
245
+ padding=self.padding,
246
+ max_length=self.max_length,
247
+ pad_to_multiple_of=self.pad_to_multiple_of,
248
+ return_tensors=self.return_tensors,
249
+ )
250
+ batch_rejected = self.tokenizer.pad(
251
+ features_rejected,
252
+ padding=self.padding,
253
+ max_length=self.max_length,
254
+ pad_to_multiple_of=self.pad_to_multiple_of,
255
+ return_tensors=self.return_tensors,
256
+ )
257
+ batch = {
258
+ "input_ids_chosen": batch_chosen["input_ids"],
259
+ "attention_mask_chosen": batch_chosen["attention_mask"],
260
+ "input_ids_rejected": batch_rejected["input_ids"],
261
+ "attention_mask_rejected": batch_rejected["attention_mask"],
262
+ "return_loss": True,
263
+ }
264
+ if has_margin:
265
+ margin = torch.tensor(margin, dtype=torch.float)
266
+ batch["margin"] = margin
267
+ return batch
268
+
269
+
270
+ @dataclass
271
+ class DPODataCollatorWithPadding:
272
+ r"""
273
+ DPO DataCollator class that pads the tokenized inputs to the maximum length of the batch.
274
+ Args:
275
+ pad_token_id (`int` defaults to 0):
276
+ The tokenizer's pad_token_id.
277
+ label_pad_token_id (`int`, defaults to -100):
278
+ The label used for masking.
279
+ is_encoder_decoder (`Optional[bool]`, `optional`, defaults to `None`):
280
+ Whether or not you model has an encoder_decoder architecture.
281
+ """
282
+
283
+ tokenizer: PreTrainedTokenizerBase
284
+ pad_token_id: int = 0
285
+ label_pad_token_id: int = -100
286
+ is_encoder_decoder: Optional[bool] = False
287
+
288
+ def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
289
+ # first, pad everything to the same length
290
+ padded_batch = {}
291
+ for k in features[0].keys():
292
+ if k.endswith("_input_ids") or k.endswith("_attention_mask") or k.endswith("_labels"):
293
+ if self.is_encoder_decoder:
294
+ to_pad = [torch.LongTensor(ex[k]) for ex in features]
295
+
296
+ if (k.startswith("prompt")) and (k.endswith("input_ids")):
297
+ if self.pad_token_id is None:
298
+ raise ValueError(
299
+ "Padding is enabled, but the tokenizer is not configured with a padding token." " Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`)" " before calling the trainer."
300
+ )
301
+ padding_value = self.pad_token_id
302
+ elif k.endswith("_attention_mask"):
303
+ padding_value = 0
304
+ elif (k.startswith("chosen")) or (k.startswith("rejected")) or ("decoder" in k):
305
+ padding_value = self.label_pad_token_id
306
+ else:
307
+ raise ValueError(f"Unexpected key in batch '{k}'")
308
+ padded_batch[k] = pad_sequence(to_pad, batch_first=True, padding_value=padding_value)
309
+ else:
310
+ # adapted from https://stackoverflow.com/questions/73256206
311
+ if "prompt" in k:
312
+ to_pad = [torch.LongTensor(ex[k][::-1]) for ex in features]
313
+ else:
314
+ to_pad = [torch.LongTensor(ex[k]) for ex in features]
315
+ if k.endswith("_input_ids"):
316
+ if self.pad_token_id is None:
317
+ raise ValueError(
318
+ "Padding is enabled, but the tokenizer is not configured with a padding token." " Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`)" " before calling the trainer."
319
+ )
320
+ padding_value = self.pad_token_id
321
+ elif k.endswith("_labels"):
322
+ padding_value = self.label_pad_token_id
323
+ elif k.endswith("_attention_mask"):
324
+ padding_value = 0
325
+ else:
326
+ raise ValueError(f"Unexpected key in batch '{k}'")
327
+
328
+ padded_batch[k] = pad_sequence(to_pad, batch_first=True, padding_value=padding_value)
329
+ # for the prompt, flip back so padding is on left side
330
+ if "prompt" in k:
331
+ padded_batch[k] = padded_batch[k].flip(dims=[1])
332
+ elif k.endswith("_logps"):
333
+ # the cached reference model logprobs
334
+ padded_batch[k] = torch.tensor([ex[k] for ex in features])
335
+ else:
336
+ padded_batch[k] = [ex[k] for ex in features]
337
+
338
+ return padded_batch
339
+
340
+
341
+ class ConstantLengthDataset(IterableDataset):
342
+ """
343
+ Iterable dataset that returns constant length chunks of tokens from stream of text files.
344
+ The dataset also formats the text before tokenization with a specific format that is provided
345
+ by the user.
346
+
347
+ Args:
348
+ tokenizer (`transformers.PreTrainedTokenizer`):
349
+ The processor used for processing the data.
350
+ dataset (`dataset.Dataset`):
351
+ Dataset with text files.
352
+ dataset_text_field (`str`, **optional**):
353
+ Name of the field in the dataset that contains the text. Used only if `formatting_func` is `None`.
354
+ formatting_func (`Callable`, **optional**):
355
+ Function that formats the text before tokenization. Usually it is recommended to have follows a certain
356
+ pattern such as `"### Question: {question} ### Answer: {answer}"`
357
+ infinite (`bool`, *optional*, defaults to `False`):
358
+ If True the iterator is reset after dataset reaches end else stops.
359
+ seq_length (`int`, *optional*, defaults to `1024`):
360
+ Length of token sequences to return.
361
+ num_of_sequences (`int`, *optional*, defaults to `1024`):
362
+ Number of token sequences to keep in buffer.
363
+ chars_per_token (`int`, *optional*, defaults to `3.6`):
364
+ Number of characters per token used to estimate number of tokens in text buffer.
365
+ eos_token_id (`int`, *optional*, defaults to `0`):
366
+ Id of the end of sequence token if the passed tokenizer does not have an EOS token.
367
+ shuffle ('bool', *optional*, defaults to True)
368
+ Shuffle the examples before they are returned
369
+ append_concat_token ('bool', *optional*, defaults to True)
370
+ If true, appends `eos_token_id` at the end of each sample being packed.
371
+ add_special_tokens ('bool', *optional*, defaults to True)
372
+ If true, tokenizers adds special tokens to each sample being packed.
373
+ """
374
+
375
+ def __init__(
376
+ self,
377
+ tokenizer,
378
+ dataset,
379
+ dataset_text_field=None,
380
+ formatting_func=None,
381
+ infinite=False,
382
+ seq_length=1024,
383
+ num_of_sequences=1024,
384
+ chars_per_token=3.6,
385
+ eos_token_id=0,
386
+ shuffle=True,
387
+ append_concat_token=True,
388
+ add_special_tokens=True,
389
+ ):
390
+ self.tokenizer = tokenizer
391
+
392
+ if tokenizer.eos_token_id is None:
393
+ warnings.warn(
394
+ "The passed tokenizer does not have an EOS token. We will use the passed eos_token_id instead which corresponds" f" to {eos_token_id}. If this is not the correct EOS token, make sure to pass the correct eos_token_id."
395
+ )
396
+
397
+ self.concat_token_id = tokenizer.eos_token_id if tokenizer.eos_token_id else eos_token_id
398
+ self.dataset = dataset
399
+ self.seq_length = seq_length
400
+ self.infinite = infinite
401
+ self.current_size = 0
402
+ self.max_buffer_size = seq_length * chars_per_token * num_of_sequences
403
+ self.shuffle = shuffle
404
+ self.append_concat_token = append_concat_token
405
+ self.add_special_tokens = add_special_tokens
406
+ if formatting_func is None:
407
+ self.formatting_func = lambda x: x[dataset_text_field]
408
+ else:
409
+ self.formatting_func = formatting_func
410
+
411
+ if formatting_func is not None:
412
+ if formatting_func.__code__.co_argcount > 1:
413
+ warnings.warn(
414
+ "The passed formatting_func has more than one argument. Usually that function should have a single argument `example`"
415
+ " which corresponds to the dictionary returned by each element of the dataset. Make sure you know what you are doing."
416
+ )
417
+
418
+ def __len__(self):
419
+ return len(self.dataset)
420
+
421
+ def __iter__(self):
422
+ iterator = iter(self.dataset)
423
+ more_examples = True
424
+ while more_examples:
425
+ buffer, buffer_len = [], 0
426
+ while True:
427
+ if buffer_len >= self.max_buffer_size:
428
+ break
429
+ try:
430
+ buffer.append(self.formatting_func(next(iterator)))
431
+ buffer_len += len(buffer[-1])
432
+ except StopIteration:
433
+ if self.infinite:
434
+ iterator = iter(self.dataset)
435
+ warnings.warn("The dataset reached end and the iterator is reset to the start.")
436
+ else:
437
+ more_examples = False
438
+ break
439
+ tokenized_inputs = self.tokenizer(buffer, add_special_tokens=self.add_special_tokens, truncation=False)["input_ids"]
440
+ all_token_ids = []
441
+ for tokenized_input in tokenized_inputs:
442
+ if self.append_concat_token:
443
+ tokenized_input = tokenized_input + [self.concat_token_id]
444
+ all_token_ids.extend(tokenized_input)
445
+ examples = []
446
+ for i in range(0, len(all_token_ids), self.seq_length):
447
+ input_ids = all_token_ids[i : i + self.seq_length]
448
+ if len(input_ids) == self.seq_length:
449
+ examples.append(input_ids)
450
+ if self.shuffle:
451
+ random.shuffle(examples)
452
+ for example in examples:
453
+ self.current_size += 1
454
+ yield {
455
+ "input_ids": torch.LongTensor(example),
456
+ "labels": torch.LongTensor(example),
457
+ }
458
+
459
+
460
+ class RunningMoments:
461
+ def __init__(self, accelerator):
462
+ """
463
+ Calculates the running mean and standard deviation of a data stream. Reference:
464
+ https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L75
465
+ """
466
+ self.mean = 0
467
+ self.std = 1
468
+ self.var = 1
469
+ self.count = 1e-24
470
+ self.accelerator = accelerator
471
+
472
+ @torch.no_grad()
473
+ def update(self, xs: torch.Tensor) -> Tuple[float, float]:
474
+ """
475
+ Updates running moments from batch's moments computed across ranks
476
+ """
477
+ if self.accelerator.use_distributed:
478
+ xs_mean, xs_var, xs_count = get_global_statistics(self.accelerator, xs)
479
+ else:
480
+ xs_count = xs.numel()
481
+ xs_var, xs_mean = torch.var_mean(xs, unbiased=False)
482
+ xs_mean, xs_var = xs_mean.float(), xs_var.float()
483
+
484
+ delta = xs_mean - self.mean
485
+ tot_count = self.count + xs_count
486
+
487
+ new_sum = xs_var * xs_count
488
+ # correct old_sum deviation accounting for the new mean
489
+ old_sum = self.var * self.count + delta**2 * self.count * xs_count / tot_count
490
+ tot_sum = old_sum + new_sum
491
+
492
+ self.mean += delta * xs_count / tot_count
493
+ self.var = tot_sum / tot_count
494
+ self.std = (self.var * tot_count / (tot_count - 1)).float().sqrt()
495
+ self.count = tot_count
496
+
497
+ return xs_mean.item(), (xs_var * xs_count / (xs_count - 1)).float().sqrt().item()
498
+
499
+
500
+ @torch.no_grad()
501
+ def get_global_statistics(accelerator, xs: torch.Tensor, mask=None, device="cpu") -> Tuple[float, float, int]:
502
+ """
503
+ Computes element-wise mean and variance of the tensor across processes. Reference:
504
+ https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L57C1-L73C75
505
+ """
506
+ xs = xs.to(accelerator.device)
507
+ sum_and_count = torch.tensor([xs.sum(), (xs.numel() if mask is None else mask.sum())], device=xs.device)
508
+ sum_and_count = accelerator.reduce(sum_and_count)
509
+ global_sum, count = sum_and_count
510
+ global_mean = global_sum / count
511
+
512
+ sum_var = torch.sum(((xs - global_mean) ** 2).mul(1 if mask is None else mask))
513
+ sum_var = accelerator.reduce(sum_var)
514
+ global_var = sum_var / count
515
+
516
+ return global_mean.to(device), global_var.to(device), count.to(device)
517
+
518
+
519
+ def compute_accuracy(eval_pred) -> Dict[str, float]:
520
+ predictions, labels = eval_pred
521
+ # Here, predictions is rewards_chosen and rewards_rejected.
522
+ # We want to see how much of the time rewards_chosen > rewards_rejected.
523
+ if np.array(predictions[:, 0] == predictions[:, 1], dtype=float).sum() > 0:
524
+ warnings.warn(f"There are {np.array(predictions[:, 0] == predictions[:, 1]).sum()} out of {len(predictions[:, 0])} instances where the predictions for both options are equal. As a consequence the accuracy can be misleading.")
525
+ predictions = np.argmax(predictions, axis=1)
526
+
527
+ accuracy = np.array(predictions == labels, dtype=float).mean().item()
528
+ return {"accuracy": accuracy}
529
+
530
+
531
+ def pad_to_length(tensor: torch.Tensor, length: int, pad_value: Union[int, float], dim: int = -1) -> torch.Tensor:
532
+ if tensor.size(dim) >= length:
533
+ return tensor
534
+ else:
535
+ pad_size = list(tensor.shape)
536
+ pad_size[dim] = length - tensor.size(dim)
537
+ return torch.cat(
538
+ [
539
+ tensor,
540
+ pad_value * torch.ones(*pad_size, dtype=tensor.dtype, device=tensor.device),
541
+ ],
542
+ dim=dim,
543
+ )
544
+
545
+
546
+ def disable_dropout_in_model(model: torch.nn.Module) -> None:
547
+ for module in model.modules():
548
+ if isinstance(module, torch.nn.Dropout):
549
+ module.p = 0
550
+
551
+
552
+ def exact_div(a, b, a_str, b_str, custom_error_message=""):
553
+ q = a // b
554
+ if a != q * b:
555
+ raise ValueError(f"{custom_error_message}, {a_str}={a}, {b_str}={b}, inexact division: {a} / {b} = {a / b}")
556
+ return q
557
+
558
+
559
+ # copied from https://github.com/kvablack/ddpo-pytorch/blob/main/ddpo_pytorch/stat_tracking.py#L5
560
+ class PerPromptStatTracker:
561
+ r"""
562
+ Class for tracking statistics per prompt. Mainly used to calculate advantage for the DPPO algorithm
563
+
564
+ Args:
565
+ buffer_size (`int`):
566
+ Size of the buffer to keep for each prompt.
567
+ min_count (`int`):
568
+ Minimum number of samples to keep in the buffer before calculating the mean and std.
569
+ """
570
+
571
+ def __init__(self, buffer_size, min_count):
572
+ self.buffer_size = buffer_size
573
+ self.min_count = min_count
574
+ self.stats = {}
575
+
576
+ def update(self, prompts, rewards):
577
+ prompts = np.array(prompts)
578
+ rewards = np.array(rewards)
579
+ unique = np.unique(prompts)
580
+ advantages = np.empty_like(rewards)
581
+ for prompt in unique:
582
+ prompt_rewards = rewards[prompts == prompt]
583
+ if prompt not in self.stats:
584
+ self.stats[prompt] = deque(maxlen=self.buffer_size)
585
+ self.stats[prompt].extend(prompt_rewards)
586
+
587
+ if len(self.stats[prompt]) < self.min_count:
588
+ mean = np.mean(rewards)
589
+ std = np.std(rewards) + 1e-6
590
+ else:
591
+ mean = np.mean(self.stats[prompt])
592
+ std = np.std(self.stats[prompt]) + 1e-6
593
+ advantages[prompts == prompt] = (prompt_rewards - mean) / std
594
+
595
+ return advantages
596
+
597
+ def get_stats(self):
598
+ return {k: {"mean": np.mean(v), "std": np.std(v), "count": len(v)} for k, v in self.stats.items()}
599
+
600
+
601
+ def neftune_post_forward_hook(module, input, output):
602
+ """
603
+ Implements the NEFTune forward pass for the model using forward hooks. Note this works only for
604
+ torch.nn.Embedding layers. This method is slightly adapted from the original source code
605
+ that can be found here: https://github.com/neelsjain/NEFTune
606
+
607
+ Simply add it to your model as follows:
608
+ ```python
609
+ model = ...
610
+ model.embed_tokens.neftune_noise_alpha = 0.1
611
+ model.embed_tokens.register_forward_hook(neftune_post_forward_hook)
612
+ ```
613
+
614
+ Args:
615
+ module (`torch.nn.Module`):
616
+ The embedding module where the hook is attached. Note that you need to set
617
+ `module.neftune_noise_alpha` to the desired noise alpha value.
618
+ input (`torch.Tensor`):
619
+ The input tensor to the model.
620
+ output (`torch.Tensor`):
621
+ The output tensor of the model (i.e. the embeddings).
622
+ """
623
+ if module.training:
624
+ dims = torch.tensor(output.size(1) * output.size(2))
625
+ mag_norm = module.neftune_noise_alpha / torch.sqrt(dims)
626
+ output = output + torch.zeros_like(output).uniform_(-mag_norm, mag_norm)
627
+ return output
628
+
629
+
630
+ def peft_module_casting_to_bf16(model):
631
+ from peft.tuners.tuners_utils import BaseTunerLayer
632
+
633
+ for name, module in model.named_modules():
634
+ if isinstance(module, BaseTunerLayer):
635
+ module = module.to(torch.bfloat16)
636
+ elif isinstance(module, torch.nn.LayerNorm) or "norm" in name:
637
+ module = module.to(torch.float32)
638
+ elif any(x in name for x in ["lm_head", "embed_tokens", "wte", "wpe"]):
639
+ if hasattr(module, "weight"):
640
+ if module.weight.dtype == torch.float32:
641
+ module = module.to(torch.bfloat16)
642
+
643
+
644
+ def trl_sanitze_kwargs_for_tagging(model, tag_names, kwargs=None):
645
+ if is_unsloth_available():
646
+ # Unsloth adds a new attribute in the model config `unsloth_version`
647
+ # to keep track of models that have been patched with unsloth.
648
+ if hasattr(model, "config") and getattr(model.config, "unsloth_version", None) is not None:
649
+ tag_names.append("unsloth")
650
+
651
+ if kwargs is not None:
652
+ if "tags" not in kwargs:
653
+ kwargs["tags"] = tag_names
654
+ elif "tags" in kwargs and isinstance(kwargs["tags"], list):
655
+ kwargs["tags"].extend(tag_names)
656
+ elif "tags" in kwargs and isinstance(kwargs["tags"], str):
657
+ tag_names.append(kwargs["tags"])
658
+ kwargs["tags"] = tag_names
659
+ return kwargs
660
+
661
+
662
+ def get_quantization_config(model_config: ModelConfig) -> Optional[BitsAndBytesConfig]:
663
+ if model_config.load_in_4bit:
664
+ quantization_config = BitsAndBytesConfig(
665
+ load_in_4bit=True,
666
+ bnb_4bit_compute_dtype=model_config.torch_dtype, # For consistency with model weights, we use the same value as `torch_dtype`
667
+ bnb_4bit_quant_type=model_config.bnb_4bit_quant_type,
668
+ bnb_4bit_use_double_quant=model_config.use_bnb_nested_quant,
669
+ )
670
+ elif model_config.load_in_8bit:
671
+ quantization_config = BitsAndBytesConfig(
672
+ load_in_8bit=True,
673
+ )
674
+ else:
675
+ quantization_config = None
676
+
677
+ return quantization_config
678
+
679
+
680
+ def get_kbit_device_map() -> Optional[Dict[str, int]]:
681
+ if is_xpu_available():
682
+ return {"": f"xpu:{PartialState().local_process_index}"}
683
+ elif torch.cuda.is_available():
684
+ return {"": PartialState().local_process_index}
685
+ else:
686
+ return None
687
+
688
+
689
+ def get_peft_config(model_config: ModelConfig) -> "Optional[PeftConfig]":
690
+ if model_config.use_peft is False:
691
+ return None
692
+
693
+ peft_config = LoraConfig(
694
+ r=model_config.lora_r,
695
+ lora_alpha=model_config.lora_alpha,
696
+ lora_dropout=model_config.lora_dropout,
697
+ bias="none",
698
+ task_type="CAUSAL_LM",
699
+ target_modules=model_config.lora_target_modules,
700
+ modules_to_save=model_config.lora_modules_to_save,
701
+ )
702
+
703
+ return peft_config