AdithyaSK HF Staff commited on
Commit
9c28b08
·
verified ·
1 Parent(s): 82a5c53

Stage Harbor release files 4501-5000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/distillation/__init__.py +19 -0
  2. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/distillation/distillation.py +179 -0
  3. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/distillation/distillation_config.py +445 -0
  4. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/distillation/distillation_trainer.py +1687 -0
  5. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/dppo/__init__.py +17 -0
  6. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/dppo/dppo_config.py +121 -0
  7. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/dppo/dppo_trainer.py +1385 -0
  8. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gfpo/__init__.py +16 -0
  9. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gfpo/gfpo_config.py +35 -0
  10. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gfpo/gfpo_trainer.py +462 -0
  11. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gkd/__init__.py +19 -0
  12. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gkd/gkd_config.py +110 -0
  13. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gkd/gkd_trainer.py +456 -0
  14. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gold/__init__.py +19 -0
  15. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gold/gold.py +155 -0
  16. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gold/gold_config.py +479 -0
  17. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gold/gold_trainer.py +0 -0
  18. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/grpo_with_replay_buffer/__init__.py +16 -0
  19. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py +34 -0
  20. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py +795 -0
  21. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gspo_token/__init__.py +15 -0
  22. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gspo_token/grpo_trainer.py +157 -0
  23. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/judges/__init__.py +36 -0
  24. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/judges/judges.py +482 -0
  25. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/kto/__init__.py +19 -0
  26. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/kto/kto_config.py +161 -0
  27. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/kto/kto_trainer.py +1451 -0
  28. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/merge_model_callback.py +352 -0
  29. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/minillm/__init__.py +19 -0
  30. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/minillm/minillm_config.py +137 -0
  31. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/minillm/minillm_trainer.py +412 -0
  32. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/nash_md/__init__.py +19 -0
  33. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/nash_md/nash_md_config.py +46 -0
  34. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/nash_md/nash_md_trainer.py +555 -0
  35. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/online_dpo/__init__.py +19 -0
  36. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/online_dpo/online_dpo_config.py +398 -0
  37. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/online_dpo/online_dpo_trainer.py +1445 -0
  38. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/openenv/__init__.py +18 -0
  39. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/openenv/utils.py +214 -0
  40. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/orpo/__init__.py +19 -0
  41. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/orpo/orpo_config.py +124 -0
  42. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/orpo/orpo_trainer.py +1030 -0
  43. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/papo/__init__.py +17 -0
  44. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/papo/papo_config.py +73 -0
  45. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/papo/papo_trainer.py +354 -0
  46. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/ppo/__init__.py +30 -0
  47. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/ppo/modeling_value_head.py +1007 -0
  48. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/ppo/ppo_config.py +280 -0
  49. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/ppo/ppo_trainer.py +1031 -0
  50. tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/prm/__init__.py +19 -0
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/distillation/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .distillation_config import DistillationConfig
16
+ from .distillation_trainer import DistillationTrainer
17
+
18
+
19
+ __all__ = ["DistillationConfig", "DistillationTrainer"]
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/distillation/distillation.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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
+ # /// script
16
+ # dependencies = [
17
+ # "trl",
18
+ # "peft",
19
+ # "trackio",
20
+ # "kernels",
21
+ # ]
22
+ # ///
23
+
24
+ # docstyle-ignore
25
+ """
26
+ # Full training (off-policy only, lmbda=0):
27
+ ```
28
+ python trl/experimental/distillation/distillation.py \
29
+ --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
30
+ --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \
31
+ --dataset_name trl-lib/chatbot_arena_completions \
32
+ --learning_rate 2e-5 \
33
+ --per_device_train_batch_size 4 \
34
+ --gradient_accumulation_steps 8 \
35
+ --lmbda 0.0 \
36
+ --output_dir distilled-model \
37
+ --num_train_epochs 1
38
+ ```
39
+
40
+ # Mixed on/off-policy (lmbda=0.5):
41
+ ```
42
+ python trl/experimental/distillation/distillation.py \
43
+ --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
44
+ --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \
45
+ --dataset_name trl-lib/chatbot_arena_completions \
46
+ --learning_rate 2e-5 \
47
+ --per_device_train_batch_size 4 \
48
+ --gradient_accumulation_steps 8 \
49
+ --lmbda 0.5 \
50
+ --beta 0.5 \
51
+ --output_dir distilled-model \
52
+ --num_train_epochs 1
53
+ ```
54
+
55
+ # LoRA:
56
+ ```
57
+ python trl/experimental/distillation/distillation.py \
58
+ --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
59
+ --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \
60
+ --dataset_name trl-lib/chatbot_arena_completions \
61
+ --learning_rate 2e-4 \
62
+ --per_device_train_batch_size 4 \
63
+ --gradient_accumulation_steps 8 \
64
+ --lmbda 0.0 \
65
+ --output_dir distilled-model \
66
+ --num_train_epochs 1 \
67
+ --use_peft \
68
+ --lora_r 64 \
69
+ --lora_alpha 16
70
+ ```
71
+ """
72
+
73
+ import argparse
74
+ import os
75
+
76
+
77
+ # Enable logging in a Hugging Face Space
78
+ os.environ.setdefault("TRACKIO_SPACE_ID", "trl-trackio")
79
+
80
+
81
+ def main(script_args, training_args, model_args):
82
+ from datasets import load_dataset
83
+ from transformers import GenerationConfig
84
+
85
+ from trl import (
86
+ LogCompletionsCallback,
87
+ get_kbit_device_map,
88
+ get_peft_config,
89
+ get_quantization_config,
90
+ )
91
+ from trl.experimental.distillation import DistillationTrainer
92
+
93
+ ################
94
+ # Model init kwargs
95
+ ################
96
+ quantization_config = get_quantization_config(model_args)
97
+ model_kwargs = dict(
98
+ revision=model_args.model_revision,
99
+ trust_remote_code=model_args.trust_remote_code,
100
+ attn_implementation=model_args.attn_implementation,
101
+ torch_dtype=model_args.dtype,
102
+ use_cache=False if training_args.gradient_checkpointing else True,
103
+ device_map=get_kbit_device_map() if quantization_config is not None else None,
104
+ quantization_config=quantization_config,
105
+ )
106
+ training_args.model_init_kwargs = model_kwargs
107
+
108
+ teacher_model_kwargs = dict(
109
+ revision=training_args.teacher_model_revision,
110
+ trust_remote_code=model_args.trust_remote_code,
111
+ attn_implementation=model_args.attn_implementation,
112
+ torch_dtype=model_args.dtype,
113
+ use_cache=True,
114
+ device_map=get_kbit_device_map() if quantization_config is not None else None,
115
+ quantization_config=quantization_config,
116
+ )
117
+ if training_args.teacher_model_init_kwargs is not None:
118
+ teacher_model_kwargs.update(training_args.teacher_model_init_kwargs)
119
+ training_args.teacher_model_init_kwargs = teacher_model_kwargs
120
+
121
+ ################
122
+ # Dataset
123
+ ################
124
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
125
+
126
+ ################
127
+ # Training
128
+ ################
129
+ eval_dataset = None
130
+ if training_args.eval_strategy != "no":
131
+ if script_args.dataset_test_split in dataset:
132
+ eval_dataset = dataset[script_args.dataset_test_split]
133
+ elif "validation" in dataset:
134
+ eval_dataset = dataset["validation"]
135
+ elif "dev" in dataset:
136
+ eval_dataset = dataset["dev"]
137
+
138
+ trainer = DistillationTrainer(
139
+ model=model_args.model_name_or_path,
140
+ teacher_model=training_args.teacher_model_name_or_path,
141
+ args=training_args,
142
+ train_dataset=dataset[script_args.dataset_train_split],
143
+ eval_dataset=eval_dataset,
144
+ peft_config=get_peft_config(model_args),
145
+ )
146
+
147
+ if training_args.eval_strategy != "no":
148
+ generation_config = GenerationConfig(
149
+ max_new_tokens=training_args.max_completion_length, do_sample=True, temperature=training_args.temperature
150
+ )
151
+ completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8)
152
+ trainer.add_callback(completions_callback)
153
+
154
+ trainer.train()
155
+
156
+ # Save and push to Hub
157
+ trainer.save_model(training_args.output_dir)
158
+ if training_args.push_to_hub:
159
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
160
+
161
+
162
+ def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None):
163
+ from trl import ModelConfig, ScriptArguments, TrlParser
164
+ from trl.experimental.distillation import DistillationConfig
165
+
166
+ dataclass_types = (ScriptArguments, DistillationConfig, ModelConfig)
167
+ if subparsers is not None:
168
+ parser = subparsers.add_parser(
169
+ "distillation", help="Run the distillation training script", dataclass_types=dataclass_types
170
+ )
171
+ else:
172
+ parser = TrlParser(dataclass_types, prog=prog)
173
+ return parser
174
+
175
+
176
+ if __name__ == "__main__":
177
+ parser = make_parser()
178
+ script_args, training_args, model_args = parser.parse_args_and_config(fail_with_unknown_args=False)
179
+ main(script_args, training_args, model_args)
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/distillation/distillation_config.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 warnings
16
+ from dataclasses import dataclass, field
17
+ from typing import Any
18
+
19
+ from ...trainer.base_config import _BaseConfig
20
+
21
+
22
+ @dataclass
23
+ class DistillationConfig(_BaseConfig):
24
+ # docstyle-ignore
25
+ r"""
26
+ Configuration class for the [`DistillationTrainer`].
27
+
28
+ Extends [`~transformers.TrainingArguments`] with parameters specific to knowledge distillation. This config is
29
+ independent of [`SFTConfig`] — all necessary fields are declared here.
30
+
31
+ Using [`~transformers.HfArgumentParser`] we can turn this class into
32
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
33
+ command line.
34
+
35
+ Parameters:
36
+ > Parameters that control the model
37
+
38
+ model_init_kwargs (`dict[str, Any]`, *optional*):
39
+ Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the
40
+ trainer is provided as a string.
41
+ max_length (`int` or `None`, *optional*, defaults to `1024`):
42
+ Maximum total sequence length (prompt + completion) for tokenization and truncation.
43
+
44
+ > Parameters that control the distillation
45
+
46
+ temperature (`float`, *optional*, defaults to `1.0`):
47
+ Temperature for sampling during generation and for computing the distillation loss. Higher values produce
48
+ softer probability distributions.
49
+ lmbda (`float`, *optional*, defaults to `0.5`):
50
+ Probability of using on-policy (student-generated) data for each gradient accumulation slice. A value of
51
+ `0.0` means fully off-policy (dataset completions only), `1.0` means fully on-policy.
52
+ beta (`float`, *optional*, defaults to `0.5`):
53
+ Interpolation coefficient for the Generalized Jensen-Shannon Divergence loss. When `0.0`, the loss is the
54
+ forward KL divergence. When `1.0`, the loss is the reverse KL divergence. When `0.5`, it is the standard
55
+ JSD.
56
+ reverse_kl_top_1_mode (`str`, *optional*, defaults to `"sampled"`):
57
+ Selection rule for the reverse-KL top-1 token when `beta > 0` and `loss_top_k == 1`. `"sampled"` uses the
58
+ actual completion token in the batch. `"argmax"` uses the student's highest-probability token. This
59
+ setting does not affect the forward-KL support, which always uses the teacher's top-1 token. Ignored when
60
+ `beta == 0` or `loss_top_k != 1`.
61
+ max_completion_length (`int`, *optional*, defaults to `256`):
62
+ Maximum number of tokens to generate per completion during on-policy generation.
63
+ disable_dropout (`bool`, *optional*, defaults to `True`):
64
+ Whether to disable dropout in the student model during training.
65
+
66
+ > Parameters that control the teacher model
67
+
68
+ teacher_model_name_or_path (`str` or `None`, *optional*):
69
+ Model name or path for the teacher model. Used when the teacher is loaded locally.
70
+ teacher_model_revision (`str` or `None`, *optional*):
71
+ Model revision of the teacher model (e.g., branch name, tag, or commit hash).
72
+ teacher_model_init_kwargs (`dict[str, Any]` or `None`, *optional*):
73
+ Keyword arguments passed to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model
74
+ from a string.
75
+ use_teacher_server (`bool`, *optional*, defaults to `False`):
76
+ Whether to use an external vLLM teacher server instead of a local teacher model.
77
+ teacher_model_server_url (`str` or `None`, *optional*):
78
+ Base URL of a vLLM server hosting the teacher model (e.g., `"http://localhost:8000"`). When set, teacher
79
+ logprobs are fetched from the server instead of running a local forward pass when `use_teacher_server=True`.
80
+ loss_top_k (`int`, *optional*, defaults to `0`):
81
+ Number of top tokens to use when computing the JSD/KL loss. Both student and teacher distributions are
82
+ restricted to these K tokens and re-normalized before computing divergence. If 0, the full vocabulary
83
+ is used. For local teachers, the general support rule is teacher top-k for forward KL, student top-k for
84
+ reverse KL, and the union for mixed JSD. When `beta > 0` and `loss_top_k == 1`, the forward support still
85
+ uses the teacher's top-1 token, while the reverse top-1 token is controlled by `reverse_kl_top_1_mode`.
86
+ When `use_teacher_server=True`, the pure forward path (`beta=0`) requires this to be positive and uses the
87
+ teacher's top-k logprobs for the forward term. When `beta > 0`, server-backed distillation requires
88
+ `loss_top_k == 1` and only supports `"sampled"` reverse top-1 tokens.
89
+ loss_add_tail (`bool`, *optional*, defaults to `True`):
90
+ Whether to append a tail bucket that represents the remaining probability mass outside the selected top-k
91
+ support when computing the loss.
92
+
93
+ > Parameters that control on-policy generation
94
+
95
+ num_generations (`int`, *optional*, defaults to `1`):
96
+ Number of completions to generate per prompt during on-policy generation.
97
+ generation_batch_size (`int` or `None`, *optional*):
98
+ Number of unique prompts per worker per optimizer step. If `None`, computed from
99
+ `(per_device_train_batch_size * gradient_accumulation_steps) // num_generations`.
100
+ top_p (`float`, *optional*, defaults to `0.95`):
101
+ Top-p (nucleus) sampling parameter for on-policy generation.
102
+ top_k (`int`, *optional*, defaults to `0`):
103
+ Top-k sampling parameter for on-policy generation. `0` disables top-k filtering.
104
+
105
+ > Parameters that control vLLM for student generation
106
+
107
+ use_vllm (`bool`, *optional*, defaults to `False`):
108
+ Whether to use vLLM for generating on-policy completions from the student model.
109
+ vllm_mode (`str`, *optional*, defaults to `"colocate"`):
110
+ Mode for student vLLM integration. Either `"server"` or `"colocate"`.
111
+ vllm_server_base_url (`str` or `None`, *optional*):
112
+ Base URL for the student vLLM server. If provided, `vllm_server_host` and `vllm_server_port` are ignored.
113
+ vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
114
+ Host of the student vLLM server.
115
+ vllm_server_port (`int`, *optional*, defaults to `8001`):
116
+ Port of the student vLLM server.
117
+ vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
118
+ Timeout for connecting to the student vLLM server.
119
+ vllm_group_port (`int`, *optional*, defaults to `51216`):
120
+ Port for the vLLM weight-update group (NCCL communicator).
121
+ vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.9`):
122
+ GPU memory utilization for the colocated student vLLM engine.
123
+ vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
124
+ Tensor parallel size for the colocated student vLLM engine.
125
+ vllm_max_model_length (`int` or `None`, *optional*):
126
+ Maximum model sequence length for the colocated vLLM engine.
127
+ vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
128
+ Model implementation backend for vLLM. Use `"vllm"` or `"transformers"`.
129
+ vllm_structured_outputs_regex (`str` or `None`, *optional*):
130
+ Regex pattern for vLLM structured outputs.
131
+ vllm_sync_frequency (`int`, *optional*, defaults to `1`):
132
+ Frequency (in training steps) to synchronize student model weights to the vLLM engine.
133
+ vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`):
134
+ Enable vLLM sleep mode to offload student weights during the optimizer step.
135
+
136
+ > Parameters that control logging
137
+
138
+ log_completions (`bool`, *optional*, defaults to `False`):
139
+ Whether to log a sample of (prompt, completion) pairs periodically.
140
+ log_completions_steps (`int`, *optional*, defaults to `100`):
141
+ Number of steps between logging completions. Only used if `log_completions` is `True`.
142
+ num_completions_to_print (`int` or `None`, *optional*):
143
+ Number of completions to print. If `None`, all completions are logged.
144
+ """
145
+
146
+ _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs", "teacher_model_init_kwargs"]
147
+
148
+ # Model
149
+ model_init_kwargs: dict[str, Any] | str | None = field(
150
+ default=None,
151
+ metadata={
152
+ "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument "
153
+ "of the trainer is provided as a string."
154
+ },
155
+ )
156
+ max_length: int | None = field(
157
+ default=1024,
158
+ metadata={"help": "Maximum total sequence length (prompt + completion) for tokenization and truncation."},
159
+ )
160
+
161
+ # Overridden defaults
162
+ learning_rate: float = field(
163
+ default=1e-7,
164
+ metadata={"help": "The initial learning rate for AdamW."},
165
+ )
166
+
167
+ # Distillation core
168
+ temperature: float = field(
169
+ default=1.0,
170
+ metadata={
171
+ "help": "Temperature for sampling and loss computation. Higher values produce softer distributions."
172
+ },
173
+ )
174
+ lmbda: float = field(
175
+ default=0.5,
176
+ metadata={
177
+ "help": "Probability of using on-policy (student-generated) data per gradient accumulation slice. "
178
+ "0.0 = fully off-policy, 1.0 = fully on-policy."
179
+ },
180
+ )
181
+ beta: float = field(
182
+ default=0.5,
183
+ metadata={
184
+ "help": "Interpolation coefficient for the Generalized JSD loss. "
185
+ "0.0 = forward KL, 0.5 = JSD, 1.0 = reverse KL."
186
+ },
187
+ )
188
+ reverse_kl_top_1_mode: str = field(
189
+ default="sampled",
190
+ metadata={
191
+ "help": "Reverse-KL top-1 token selection when beta > 0 and loss_top_k == 1. "
192
+ "Use 'sampled' for the actual completion token or 'argmax' for the student's top-1 token. "
193
+ "The forward-KL support always uses the teacher's top-1 token. Ignored when beta == 0 or loss_top_k != 1."
194
+ },
195
+ )
196
+ max_completion_length: int = field(
197
+ default=256,
198
+ metadata={"help": "Maximum number of tokens to generate per completion."},
199
+ )
200
+ max_prompt_length: int | None = field(
201
+ default=None,
202
+ metadata={
203
+ "help": "Maximum number of tokens for the prompt. If None, auto-computed as "
204
+ "max_length - max_completion_length. Prompts are truncated according to the "
205
+ "tokenizer's truncation_side setting."
206
+ },
207
+ )
208
+ disable_dropout: bool = field(
209
+ default=True,
210
+ metadata={"help": "Whether to disable dropout in the student model during training."},
211
+ )
212
+
213
+ # Teacher model (local)
214
+ teacher_model_name_or_path: str | None = field(
215
+ default=None,
216
+ metadata={"help": "Model name or path for the teacher model."},
217
+ )
218
+ teacher_model_revision: str | None = field(
219
+ default=None,
220
+ metadata={"help": "Model revision of the teacher model (e.g., branch name, tag, or commit hash)."},
221
+ )
222
+ teacher_model_init_kwargs: dict[str, Any] | str | None = field(
223
+ default=None,
224
+ metadata={
225
+ "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained` when instantiating the teacher."
226
+ },
227
+ )
228
+
229
+ # Teacher model (external vLLM server)
230
+ use_teacher_server: bool = field(
231
+ default=False,
232
+ metadata={"help": "Whether to use an external vLLM teacher server instead of a local teacher model."},
233
+ )
234
+ teacher_model_server_url: str | None = field(
235
+ default=None,
236
+ metadata={
237
+ "help": 'Base URL of a vLLM server hosting the teacher model (e.g., "http://localhost:8000"). '
238
+ "Required when use_teacher_server=True."
239
+ },
240
+ )
241
+ loss_top_k: int = field(
242
+ default=0,
243
+ metadata={
244
+ "help": "Number of top tokens to use when computing the JSD/KL loss. "
245
+ "Both student and teacher distributions are restricted to these K tokens "
246
+ "(selected based on beta: teacher's top-k for forward KL, student's top-k for reverse KL, "
247
+ "union of both for JSD) and re-normalized before computing divergence. "
248
+ "If 0, the full vocabulary is used (slower but exact). "
249
+ "When beta > 0 and loss_top_k == 1, the forward support still uses the teacher's top-1 token, "
250
+ "while the reverse top-1 token is controlled by reverse_kl_top_1_mode. "
251
+ "When use_teacher_server=True, beta=0 requires loss_top_k > 0 and uses the teacher's top-k "
252
+ "logprobs for the forward term. When beta > 0, server-backed distillation requires loss_top_k == 1 "
253
+ "and only supports 'sampled' reverse top-1 tokens."
254
+ },
255
+ )
256
+ loss_add_tail: bool = field(
257
+ default=True,
258
+ metadata={
259
+ "help": "Whether to append a tail bucket representing the remaining probability mass outside the selected top-k support."
260
+ },
261
+ )
262
+
263
+ # On-policy generation
264
+ num_generations: int = field(
265
+ default=1,
266
+ metadata={"help": "Number of completions to generate per prompt during on-policy generation."},
267
+ )
268
+ generation_batch_size: int | None = field(
269
+ default=None,
270
+ metadata={
271
+ "help": "Number of unique prompts per worker per optimizer step. "
272
+ "If None, computed from (per_device_train_batch_size * gradient_accumulation_steps) // num_generations."
273
+ },
274
+ )
275
+ top_p: float = field(
276
+ default=0.95,
277
+ metadata={"help": "Top-p (nucleus) sampling parameter for on-policy generation."},
278
+ )
279
+ top_k: int = field(
280
+ default=0,
281
+ metadata={"help": "Top-k sampling parameter for on-policy generation. 0 disables top-k filtering."},
282
+ )
283
+
284
+ # vLLM for student generation
285
+ use_vllm: bool = field(
286
+ default=False,
287
+ metadata={"help": "Whether to use vLLM for generating on-policy completions from the student model."},
288
+ )
289
+ vllm_mode: str = field(
290
+ default="colocate",
291
+ metadata={"help": 'Mode for student vLLM integration. Either "server" or "colocate".'},
292
+ )
293
+ vllm_server_base_url: str | None = field(
294
+ default=None,
295
+ metadata={"help": "Base URL for the student vLLM server."},
296
+ )
297
+ vllm_server_host: str = field(
298
+ default="0.0.0.0",
299
+ metadata={"help": "Host of the student vLLM server."},
300
+ )
301
+ vllm_server_port: int = field(
302
+ default=8001,
303
+ metadata={"help": "Port of the student vLLM server."},
304
+ )
305
+ vllm_server_timeout: float = field(
306
+ default=240.0,
307
+ metadata={"help": "Timeout for connecting to the student vLLM server."},
308
+ )
309
+ vllm_group_port: int = field(
310
+ default=51216,
311
+ metadata={"help": "Port for the vLLM weight-update group (NCCL communicator)."},
312
+ )
313
+ vllm_gpu_memory_utilization: float = field(
314
+ default=0.9,
315
+ metadata={"help": "GPU memory utilization for the colocated student vLLM engine."},
316
+ )
317
+ vllm_tensor_parallel_size: int = field(
318
+ default=1,
319
+ metadata={"help": "Tensor parallel size for the colocated student vLLM engine."},
320
+ )
321
+ vllm_max_model_length: int | None = field(
322
+ default=None,
323
+ metadata={"help": "Maximum model sequence length for the colocated vLLM engine."},
324
+ )
325
+ vllm_model_impl: str = field(
326
+ default="vllm",
327
+ metadata={"help": 'Model implementation backend for vLLM. Use "vllm" or "transformers".'},
328
+ )
329
+ vllm_structured_outputs_regex: str | None = field(
330
+ default=None,
331
+ metadata={"help": "Regex pattern for vLLM structured outputs."},
332
+ )
333
+ vllm_sync_frequency: int = field(
334
+ default=1,
335
+ metadata={"help": "Frequency (in training steps) to synchronize student weights to the vLLM engine."},
336
+ )
337
+ vllm_enable_sleep_mode: bool = field(
338
+ default=False,
339
+ metadata={"help": "Enable vLLM sleep mode to offload student weights during the optimizer step."},
340
+ )
341
+
342
+ # W&B
343
+ wandb_entity: str | None = field(
344
+ default=None,
345
+ metadata={"help": "The W&B entity to store runs under."},
346
+ )
347
+ wandb_project: str | None = field(
348
+ default=None,
349
+ metadata={"help": "The W&B project to store runs under."},
350
+ )
351
+ wandb_run_group: str | None = field(
352
+ default=None,
353
+ metadata={"help": "The W&B group to store runs under."},
354
+ )
355
+
356
+ # Logging
357
+ log_completions: bool = field(
358
+ default=False,
359
+ metadata={"help": "Whether to log a sample of (prompt, completion) pairs periodically."},
360
+ )
361
+ log_completions_steps: int = field(
362
+ default=100,
363
+ metadata={"help": "Number of steps between logging completions."},
364
+ )
365
+ num_completions_to_print: int | None = field(
366
+ default=None,
367
+ metadata={"help": "Number of completions to print. If None, all completions are logged."},
368
+ )
369
+
370
+ def __post_init__(self):
371
+ super().__post_init__()
372
+
373
+ if self.lmbda < 0.0 or self.lmbda > 1.0:
374
+ raise ValueError(f"lmbda must be in [0.0, 1.0], got {self.lmbda}.")
375
+ if self.beta < 0.0 or self.beta > 1.0:
376
+ raise ValueError(f"beta must be in [0.0, 1.0], got {self.beta}.")
377
+ if self.reverse_kl_top_1_mode not in {"sampled", "argmax"}:
378
+ raise ValueError("reverse_kl_top_1_mode must be one of: 'sampled', 'argmax'")
379
+
380
+ if self.max_length is not None and self.max_completion_length >= self.max_length:
381
+ raise ValueError(
382
+ f"max_completion_length ({self.max_completion_length}) must be smaller than "
383
+ f"max_length ({self.max_length}) to leave room for the prompt."
384
+ )
385
+
386
+ if self.max_prompt_length is None and self.max_length is not None:
387
+ self.max_prompt_length = self.max_length - self.max_completion_length
388
+
389
+ if self.num_generations < 1:
390
+ raise ValueError(f"num_generations must be at least 1, got {self.num_generations}.")
391
+
392
+ local_sequence_batch_size = self.per_device_train_batch_size * self.gradient_accumulation_steps
393
+ if self.generation_batch_size is None:
394
+ self.generation_batch_size = local_sequence_batch_size // self.num_generations
395
+ if self.generation_batch_size < 1:
396
+ raise ValueError(f"generation_batch_size must be at least 1, got {self.generation_batch_size}.")
397
+ if self.generation_batch_size * self.num_generations != local_sequence_batch_size:
398
+ raise ValueError(
399
+ "generation_batch_size * num_generations must equal per_device_train_batch_size * "
400
+ f"gradient_accumulation_steps. Got {self.generation_batch_size} * {self.num_generations} != "
401
+ f"{self.per_device_train_batch_size} * {self.gradient_accumulation_steps}."
402
+ )
403
+
404
+ if self.use_teacher_server and self.use_liger_kernel:
405
+ raise ValueError(
406
+ "use_liger_kernel=True is not supported with use_teacher_server=True because the Liger loss path "
407
+ "requires a local teacher model."
408
+ )
409
+ if self.use_teacher_server and (
410
+ self.teacher_model_server_url is None or not self.teacher_model_server_url.strip()
411
+ ):
412
+ raise ValueError("teacher_model_server_url must be set when use_teacher_server=True.")
413
+
414
+ if self.use_teacher_server and self.beta == 0 and self.loss_top_k < 1:
415
+ raise ValueError(
416
+ f"loss_top_k must be positive when using use_teacher_server=True with beta=0 "
417
+ f"(got loss_top_k={self.loss_top_k}). The pure forward server path only has access to the "
418
+ f"teacher's top-k logprobs, so it cannot compute the exact full-vocabulary loss when loss_top_k=0."
419
+ )
420
+ if self.use_teacher_server and self.reverse_kl_top_1_mode == "argmax":
421
+ raise ValueError(
422
+ "reverse_kl_top_1_mode='argmax' is not supported with use_teacher_server=True because the server "
423
+ "cannot provide teacher logprobs for arbitrary student-selected tokens."
424
+ )
425
+ if self.use_teacher_server and self.beta > 0 and self.loss_top_k != 1:
426
+ raise ValueError(
427
+ f"loss_top_k must be 1 when using use_teacher_server=True with beta>0 "
428
+ f"(got loss_top_k={self.loss_top_k}). Mixed forward/reverse distillation with an external teacher "
429
+ "is only implemented for top-1 support."
430
+ )
431
+ if self.reverse_kl_top_1_mode != "sampled" and (self.beta == 0 or self.loss_top_k != 1):
432
+ warnings.warn(
433
+ f"reverse_kl_top_1_mode='{self.reverse_kl_top_1_mode}' has no effect when beta={self.beta} "
434
+ f"and loss_top_k={self.loss_top_k}. It only applies when beta > 0 and loss_top_k == 1.",
435
+ UserWarning,
436
+ stacklevel=2,
437
+ )
438
+
439
+ if self.num_generations > 1 and self.lmbda < 1.0:
440
+ warnings.warn(
441
+ f"num_generations={self.num_generations} with lmbda={self.lmbda} means off-policy batches include "
442
+ f"{self.num_generations} copies of each sample. Consider lmbda=1.0 when num_generations > 1.",
443
+ UserWarning,
444
+ stacklevel=2,
445
+ )
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/distillation/distillation_trainer.py ADDED
@@ -0,0 +1,1687 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 random
16
+ import textwrap
17
+ import warnings
18
+ from collections import defaultdict
19
+ from collections.abc import Callable
20
+ from contextlib import nullcontext
21
+ from functools import partial
22
+ from typing import Any, Optional
23
+
24
+ import torch
25
+ import torch.distributed as dist
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+ from accelerate.utils import DistributedType, broadcast_object_list, gather_object
29
+ from datasets import Dataset
30
+ from torch.utils.data import DataLoader
31
+ from transformers import AutoTokenizer, TrainerCallback
32
+ from transformers.data.data_collator import DataCollator
33
+ from transformers.feature_extraction_utils import FeatureExtractionMixin
34
+ from transformers.generation.configuration_utils import GenerationConfig
35
+ from transformers.image_processing_utils import BaseImageProcessor
36
+ from transformers.modeling_utils import PreTrainedModel
37
+ from transformers.processing_utils import ProcessorMixin
38
+ from transformers.tokenization_utils_base import PreTrainedTokenizerBase
39
+ from transformers.trainer_utils import EvalPrediction, seed_worker
40
+ from transformers.utils import (
41
+ is_liger_kernel_available,
42
+ is_peft_available,
43
+ is_rich_available,
44
+ )
45
+
46
+ from ...extras.profiling import profiling_decorator
47
+ from ...generation.vllm_generation import VLLMGeneration
48
+ from ...import_utils import is_vllm_available
49
+ from ...models import prepare_deepspeed
50
+ from ...models.utils import unwrap_model_for_generation
51
+ from ...trainer.base_trainer import _BaseTrainer
52
+ from ...trainer.utils import (
53
+ RepeatSampler,
54
+ create_model_from_path,
55
+ disable_dropout_in_model,
56
+ pad,
57
+ split_tensor_dict,
58
+ )
59
+ from .distillation_config import DistillationConfig
60
+
61
+
62
+ if is_peft_available():
63
+ from peft import PeftConfig, get_peft_model
64
+
65
+ if is_liger_kernel_available():
66
+ from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss
67
+
68
+ if is_rich_available():
69
+ from rich.console import Console
70
+ from rich.panel import Panel
71
+ from rich.table import Table
72
+ from rich.text import Text
73
+
74
+
75
+ def _print_completions_sample(prompts: list[str], completions: list[str], step: int, num_samples: int = None) -> None:
76
+ """Print a sample of prompt-completion pairs using rich."""
77
+ if not is_rich_available():
78
+ return
79
+
80
+ console = Console()
81
+ table = Table(show_header=True, header_style="bold white", expand=True)
82
+ table.add_column("Prompt", style="bright_yellow")
83
+ table.add_column("Completion", style="bright_green")
84
+
85
+ if num_samples is not None:
86
+ if num_samples >= len(prompts):
87
+ num_samples = None
88
+ elif num_samples <= 0:
89
+ return
90
+
91
+ if num_samples is not None:
92
+ indices = random.sample(range(len(prompts)), num_samples)
93
+ prompts = [prompts[i] for i in indices]
94
+ completions = [completions[i] for i in indices]
95
+
96
+ for prompt, completion in zip(prompts, completions, strict=True):
97
+ table.add_row(Text(prompt), Text(completion))
98
+ table.add_section()
99
+
100
+ panel = Panel(table, expand=False, title=f"Step {step}", border_style="bold white")
101
+ console.print(panel)
102
+
103
+
104
+ def _add_tail_bucket(log_probs, valid_mask):
105
+ """Append a (K+1)-th tail element: log(1 - sum(exp(top_k_logps))).
106
+
107
+ This creates a proper probability distribution over K+1 elements, preventing trivial zero loss when top_k is small
108
+ (especially top_k=1).
109
+ """
110
+ log_sum = torch.logsumexp(log_probs, dim=-1, keepdim=True)
111
+ log_sum = torch.clamp(log_sum, max=-1e-7) # ensure sum < 1
112
+ tail = torch.log(-torch.expm1(log_sum)) # log(1 - exp(log_sum))
113
+ tail_mask = torch.ones_like(valid_mask[..., :1], dtype=torch.bool)
114
+ return torch.cat([log_probs, tail], dim=-1), torch.cat([valid_mask, tail_mask], dim=-1)
115
+
116
+
117
+ def _jsd_divergence(student_log_probs, teacher_log_probs, beta, support_mask=None):
118
+ """Compute JSD (or forward/reverse KL) from log-probability tensors.
119
+
120
+ When *support_mask* is not None, uses manual computation with masked positions zeroed. When None, uses
121
+ ``F.kl_div``.
122
+ """
123
+ if support_mask is not None:
124
+ safe_student = torch.where(support_mask, student_log_probs, torch.zeros_like(student_log_probs))
125
+ safe_teacher = torch.where(support_mask, teacher_log_probs, torch.zeros_like(teacher_log_probs))
126
+ student_probs = torch.where(support_mask, student_log_probs.exp(), torch.zeros_like(student_log_probs))
127
+ teacher_probs = torch.where(support_mask, teacher_log_probs.exp(), torch.zeros_like(teacher_log_probs))
128
+
129
+ if beta == 0:
130
+ return torch.nan_to_num(teacher_probs * (safe_teacher - safe_student), nan=0.0)
131
+ elif beta == 1:
132
+ return torch.nan_to_num(student_probs * (safe_student - safe_teacher), nan=0.0)
133
+ else:
134
+ beta_t = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device)
135
+ tiny = torch.finfo(student_probs.dtype).tiny
136
+ mixture_probs = (1 - beta_t) * student_probs + beta_t * teacher_probs
137
+ safe_mixture = torch.where(
138
+ support_mask,
139
+ torch.log(mixture_probs.clamp_min(tiny)),
140
+ torch.zeros_like(student_log_probs),
141
+ )
142
+ kl_teacher = torch.nan_to_num(teacher_probs * (safe_teacher - safe_mixture), nan=0.0)
143
+ kl_student = torch.nan_to_num(student_probs * (safe_student - safe_mixture), nan=0.0)
144
+ return beta_t * kl_teacher + (1 - beta_t) * kl_student
145
+ else:
146
+ if beta == 0:
147
+ return F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True)
148
+ elif beta == 1:
149
+ return F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True)
150
+ else:
151
+ beta_t = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device)
152
+ mixture_log_probs = torch.logsumexp(
153
+ torch.stack([student_log_probs + torch.log1p(-beta_t), teacher_log_probs + torch.log(beta_t)]),
154
+ dim=0,
155
+ )
156
+ kl_teacher = F.kl_div(mixture_log_probs, teacher_log_probs, reduction="none", log_target=True)
157
+ kl_student = F.kl_div(mixture_log_probs, student_log_probs, reduction="none", log_target=True)
158
+ return beta_t * kl_teacher + (1 - beta_t) * kl_student
159
+
160
+
161
+ def build_teacher_request_inputs(
162
+ input_ids: torch.Tensor,
163
+ attention_mask: torch.Tensor,
164
+ prompt_attention_mask: torch.Tensor | None = None,
165
+ labels: torch.Tensor | None = None,
166
+ ) -> tuple[list[list[int]], list[int], list[int]]:
167
+ """Trim padded batch tensors into per-sample sequences for teacher-server requests."""
168
+
169
+ if input_ids.shape != attention_mask.shape:
170
+ raise ValueError(
171
+ f"input_ids and attention_mask must have the same shape, got {input_ids.shape} and {attention_mask.shape}."
172
+ )
173
+
174
+ input_ids_cpu = input_ids.detach().cpu()
175
+ attention_mask_cpu = attention_mask.detach().cpu().bool()
176
+
177
+ if prompt_attention_mask is not None:
178
+ prompt_lengths = prompt_attention_mask.detach().cpu().sum(dim=1).to(torch.long)
179
+ else:
180
+ if labels is None:
181
+ raise ValueError("labels are required when prompt_attention_mask is not provided.")
182
+ if labels.shape != input_ids.shape:
183
+ raise ValueError(f"labels must match input_ids shape, got {labels.shape} and {input_ids.shape}.")
184
+ full_lengths = attention_mask_cpu.sum(dim=1).to(torch.long)
185
+ completion_lengths = (labels.detach().cpu() != -100).sum(dim=1).to(torch.long)
186
+ prompt_lengths = full_lengths - completion_lengths
187
+
188
+ trimmed_input_ids: list[list[int]] = []
189
+ prompt_lengths_list: list[int] = []
190
+ completion_lengths_list: list[int] = []
191
+
192
+ for row, mask, prompt_length in zip(input_ids_cpu, attention_mask_cpu, prompt_lengths, strict=True):
193
+ trimmed_row = row[mask]
194
+ prompt_len = int(prompt_length.item())
195
+ if prompt_len < 0 or prompt_len > trimmed_row.numel():
196
+ raise ValueError(
197
+ f"Invalid prompt length {prompt_len} for trimmed sequence of length {trimmed_row.numel()}."
198
+ )
199
+ trimmed_input_ids.append(trimmed_row.tolist())
200
+ prompt_lengths_list.append(prompt_len)
201
+ completion_lengths_list.append(int(trimmed_row.numel()) - prompt_len)
202
+
203
+ return trimmed_input_ids, prompt_lengths_list, completion_lengths_list
204
+
205
+
206
+ class _DistillationCollator:
207
+ """Data collator for the distillation trainer with independent prompt/completion budgets.
208
+
209
+ Unlike ``DataCollatorForChatML``, this collator tokenizes prompts and completions separately so that long
210
+ completions can never truncate the prompt to empty. It also handles prompt-only data (no assistant completions) for
211
+ pure on-policy distillation (``lmbda=1``).
212
+ """
213
+
214
+ def __init__(
215
+ self,
216
+ tokenizer: "PreTrainedTokenizerBase",
217
+ max_length: int,
218
+ max_prompt_length: int,
219
+ messages_key: str = "messages",
220
+ ignore_index: int = -100,
221
+ ):
222
+ self.tokenizer = tokenizer
223
+ self.max_length = max_length
224
+ self.max_prompt_length = max_prompt_length
225
+ self.messages_key = messages_key
226
+ self.ignore_index = ignore_index
227
+
228
+ if tokenizer.pad_token_id is None:
229
+ raise ValueError("The tokenizer does not have a pad token. Please set `pad_token_id` in the tokenizer.")
230
+
231
+ def __call__(self, examples: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
232
+ all_input_ids: list[list[int]] = []
233
+ all_labels: list[list[int]] = []
234
+ all_prompt_ids: list[list[int]] = []
235
+
236
+ for example in examples:
237
+ messages = example[self.messages_key]
238
+
239
+ # Split: prompt = everything before the last assistant turn, completion = last assistant turn
240
+ has_completion = len(messages) > 1 and messages[-1].get("role") == "assistant"
241
+ prompt_messages = messages[:-1] if has_completion else messages
242
+
243
+ # Tokenize prompt with its own budget using the tokenizer's truncation side
244
+ formatted_prompt = self.tokenizer.apply_chat_template(
245
+ prompt_messages, tokenize=False, add_generation_prompt=True
246
+ )
247
+ prompt_ids = self.tokenizer(
248
+ formatted_prompt,
249
+ truncation=True,
250
+ max_length=self.max_prompt_length,
251
+ padding=False,
252
+ add_special_tokens=False,
253
+ )["input_ids"]
254
+
255
+ if has_completion:
256
+ # Tokenize the full message (prompt + completion) without truncation first
257
+ formatted_full = self.tokenizer.apply_chat_template(
258
+ messages, tokenize=False, add_generation_prompt=False
259
+ )
260
+ full_ids = self.tokenizer(formatted_full, truncation=False, padding=False, add_special_tokens=False)[
261
+ "input_ids"
262
+ ]
263
+
264
+ # Identify completion tokens: everything after the prompt in the full sequence.
265
+ # Use the un-truncated prompt length as the split point.
266
+ formatted_prompt_ids = self.tokenizer(
267
+ formatted_prompt, truncation=False, padding=False, add_special_tokens=False
268
+ )["input_ids"]
269
+ completion_ids = full_ids[len(formatted_prompt_ids) :]
270
+
271
+ # Trim completion so prompt + completion <= max_length
272
+ max_comp = self.max_length - len(prompt_ids)
273
+ if max_comp > 0 and len(completion_ids) > max_comp:
274
+ completion_ids = completion_ids[:max_comp]
275
+ elif max_comp <= 0:
276
+ completion_ids = []
277
+
278
+ input_ids = prompt_ids + completion_ids
279
+ labels = [self.ignore_index] * len(prompt_ids) + list(completion_ids)
280
+ else:
281
+ # Prompt-only: no completion to train on (on-policy will generate one)
282
+ input_ids = list(prompt_ids)
283
+ labels = [self.ignore_index] * len(prompt_ids)
284
+
285
+ all_input_ids.append(input_ids)
286
+ all_labels.append(labels)
287
+ all_prompt_ids.append(list(prompt_ids))
288
+
289
+ # Convert to tensors and left-pad
290
+ pad_id = self.tokenizer.pad_token_id
291
+ input_ids_t = pad(
292
+ [torch.tensor(ids, dtype=torch.long) for ids in all_input_ids],
293
+ padding_side="left",
294
+ padding_value=pad_id,
295
+ )
296
+ attention_mask_t = pad(
297
+ [torch.ones(len(ids), dtype=torch.long) for ids in all_input_ids],
298
+ padding_side="left",
299
+ padding_value=0,
300
+ )
301
+ labels_t = pad(
302
+ [torch.tensor(lab, dtype=torch.long) for lab in all_labels],
303
+ padding_side="left",
304
+ padding_value=self.ignore_index,
305
+ )
306
+ prompts_t = pad(
307
+ [torch.tensor(ids, dtype=torch.long) for ids in all_prompt_ids],
308
+ padding_side="left",
309
+ padding_value=pad_id,
310
+ )
311
+ prompt_mask_t = pad(
312
+ [torch.ones(len(ids), dtype=torch.long) for ids in all_prompt_ids],
313
+ padding_side="left",
314
+ padding_value=0,
315
+ )
316
+
317
+ return {
318
+ "input_ids": input_ids_t,
319
+ "attention_mask": attention_mask_t,
320
+ "labels": labels_t,
321
+ "prompts": prompts_t,
322
+ "prompt_attention_mask": prompt_mask_t,
323
+ }
324
+
325
+
326
+ class _RepeatBatchDataLoader:
327
+ """Repeats each collated batch ``repeat_count`` times without re-collation.
328
+
329
+ ``RepeatSampler`` with ``repeat_count > 1`` causes the DataLoader to re-collate (re-tokenize) the same examples on
330
+ every repeat, which is wasteful. This wrapper instead keeps ``repeat_count=1`` in the sampler and repeats the
331
+ already-collated tensor dict, avoiding redundant tokenization.
332
+ """
333
+
334
+ def __init__(self, dataloader, repeat_count: int):
335
+ self.dataloader = dataloader
336
+ self.repeat_count = repeat_count
337
+
338
+ def __iter__(self):
339
+ for batch in self.dataloader:
340
+ for _ in range(self.repeat_count):
341
+ yield batch
342
+
343
+ def __len__(self):
344
+ return len(self.dataloader) * self.repeat_count
345
+
346
+ def set_epoch(self, epoch: int):
347
+ if hasattr(self.dataloader, "set_epoch"):
348
+ self.dataloader.set_epoch(epoch)
349
+
350
+ def __getattr__(self, attr):
351
+ return getattr(self.dataloader, attr)
352
+
353
+
354
+ class DistillationTrainer(_BaseTrainer):
355
+ """
356
+ Trainer for knowledge distillation from a teacher model to a student model.
357
+
358
+ Supports:
359
+ - Generalized JSD loss (forward KL, reverse KL, or interpolated JSD via `beta`)
360
+ - On-policy / off-policy mixing via `lmbda` (buffered across gradient accumulation)
361
+ - Local teacher model or external teacher via vLLM server
362
+ - Student on-policy generation via vLLM or model.generate()
363
+ - Liger kernel for memory-efficient fused JSD loss
364
+ """
365
+
366
+ _tag_names = ["trl", "distillation"]
367
+ _name = "Distillation"
368
+ _paper = {
369
+ "title": "On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes",
370
+ "id": "2306.13649",
371
+ # docstyle-ignore
372
+ "citation": textwrap.dedent("""\
373
+ @inproceedings{agarwal2024on-policy,
374
+ title = {{On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes}},
375
+ author = {Rishabh Agarwal and Nino Vieillard and Yongchao Zhou and Piotr Stanczyk and Sabela Ramos Garea and Matthieu Geist and Olivier Bachem},
376
+ year = 2024,
377
+ booktitle = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024},
378
+ publisher = {OpenReview.net},
379
+ url = {https://openreview.net/forum?id=3zKtaqxLhW},
380
+ }"""),
381
+ }
382
+
383
+ def __init__(
384
+ self,
385
+ model: PreTrainedModel | nn.Module | str | None = None,
386
+ teacher_model: PreTrainedModel | nn.Module | str = None,
387
+ args: DistillationConfig | None = None,
388
+ data_collator: DataCollator | None = None, # type: ignore
389
+ train_dataset: Dataset | None = None,
390
+ eval_dataset: Dataset | dict[str, Dataset] | None = None,
391
+ processing_class: PreTrainedTokenizerBase
392
+ | BaseImageProcessor
393
+ | FeatureExtractionMixin
394
+ | ProcessorMixin
395
+ | None = None,
396
+ compute_metrics: Callable[[EvalPrediction], dict] | None = None,
397
+ callbacks: list[TrainerCallback] | None = None,
398
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
399
+ preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
400
+ peft_config: Optional["PeftConfig"] = None,
401
+ ):
402
+ if args is None:
403
+ args = DistillationConfig(output_dir="tmp_distillation")
404
+
405
+ # ── Student model loading ──
406
+ model_init_kwargs = args.model_init_kwargs or {}
407
+ if isinstance(model_init_kwargs, str):
408
+ import json
409
+
410
+ model_init_kwargs = json.loads(model_init_kwargs)
411
+ teacher_model_init_kwargs = args.teacher_model_init_kwargs or {}
412
+ if isinstance(teacher_model_init_kwargs, str):
413
+ import json
414
+
415
+ teacher_model_init_kwargs = json.loads(teacher_model_init_kwargs)
416
+ if isinstance(model, str):
417
+ model_name_or_path = model
418
+ model = create_model_from_path(model, **model_init_kwargs)
419
+ else:
420
+ model_name_or_path = model.config._name_or_path if model is not None else None
421
+
422
+ # ── Processing class (tokenizer) ──
423
+ if processing_class is None and model_name_or_path is not None:
424
+ processing_class = AutoTokenizer.from_pretrained(model_name_or_path)
425
+ if processing_class is not None:
426
+ if getattr(processing_class, "pad_token", None) is None:
427
+ processing_class.pad_token = processing_class.eos_token
428
+
429
+ # ── PEFT ──
430
+ if peft_config is not None:
431
+ model = get_peft_model(model, peft_config)
432
+
433
+ # ── Data collator ──
434
+ if data_collator is None:
435
+ data_collator = _DistillationCollator(
436
+ tokenizer=processing_class,
437
+ max_length=args.max_length,
438
+ max_prompt_length=args.max_prompt_length,
439
+ )
440
+
441
+ # ── Liger fused JSD loss ──
442
+ self.use_liger_loss = False
443
+ if args.use_liger_kernel:
444
+ self.liger_jsd_loss = LigerFusedLinearJSDLoss(
445
+ beta=args.beta,
446
+ ignore_index=-100,
447
+ temperature=args.temperature,
448
+ compiled=False,
449
+ weight_hard_loss=0.0,
450
+ weight_soft_loss=1.0,
451
+ )
452
+ self.use_liger_loss = True
453
+
454
+ # ── Teacher model setup ──
455
+ self.teacher_client = None
456
+ self.use_teacher_server = args.use_teacher_server
457
+ self.teacher_model_server_url = args.teacher_model_server_url
458
+ self._local_teacher_tokenizer_matches_student = True
459
+ if self.use_teacher_server:
460
+ from ...generation.vllm_client import VLLMClient
461
+
462
+ self.teacher_client = VLLMClient(base_url=self.teacher_model_server_url, connection_timeout=60.0)
463
+ teacher_model = None
464
+ elif teacher_model is not None:
465
+ if args.teacher_model_init_kwargs is not None and not isinstance(teacher_model, str):
466
+ raise ValueError(
467
+ "You passed teacher_model_init_kwargs to the config, but your teacher_model is already "
468
+ "instantiated."
469
+ )
470
+
471
+ teacher_model_name_or_path = (
472
+ teacher_model
473
+ if isinstance(teacher_model, str)
474
+ else getattr(getattr(teacher_model, "config", None), "_name_or_path", None)
475
+ )
476
+ if teacher_model_name_or_path is None:
477
+ raise ValueError(
478
+ "DistillationTrainer requires a local teacher model with `config._name_or_path` set so its "
479
+ "tokenizer can be validated against the student tokenizer."
480
+ )
481
+
482
+ teacher_tokenizer_kwargs = {}
483
+ teacher_revision = teacher_model_init_kwargs.get("revision", args.teacher_model_revision)
484
+ if teacher_revision is not None:
485
+ teacher_tokenizer_kwargs["revision"] = teacher_revision
486
+ if teacher_model_init_kwargs.get("trust_remote_code") is not None:
487
+ teacher_tokenizer_kwargs["trust_remote_code"] = teacher_model_init_kwargs["trust_remote_code"]
488
+ teacher_processing_class = AutoTokenizer.from_pretrained(
489
+ teacher_model_name_or_path, **teacher_tokenizer_kwargs
490
+ )
491
+ if getattr(teacher_processing_class, "pad_token", None) is None:
492
+ teacher_processing_class.pad_token = teacher_processing_class.eos_token
493
+ self._local_teacher_tokenizer_matches_student = self._local_teacher_tokenizers_match(
494
+ processing_class, teacher_processing_class
495
+ )
496
+ if not self._local_teacher_tokenizer_matches_student:
497
+ warnings.warn(
498
+ "DistillationTrainer's built-in local-teacher loss assumes the student and teacher share the "
499
+ "same tokenizer. The loaded local teacher tokenizer does not match the student tokenizer, so "
500
+ "the teacher weights will be left unchanged for subclass overrides. Direct use of the base "
501
+ "DistillationTrainer with this local teacher remains unsupported.",
502
+ UserWarning,
503
+ stacklevel=2,
504
+ )
505
+
506
+ if isinstance(teacher_model, str):
507
+ torch_dtype = teacher_model_init_kwargs.get("torch_dtype")
508
+ teacher_model_init_kwargs["torch_dtype"] = (
509
+ torch_dtype if torch_dtype in ["auto", None] else getattr(torch, torch_dtype)
510
+ )
511
+
512
+ if isinstance(teacher_model, str):
513
+ init_kwargs = dict(teacher_model_init_kwargs)
514
+ if args.teacher_model_revision is not None:
515
+ init_kwargs.setdefault("revision", args.teacher_model_revision)
516
+ if "torch_dtype" in init_kwargs and "dtype" not in init_kwargs:
517
+ init_kwargs["dtype"] = init_kwargs.pop("torch_dtype")
518
+ teacher_model = create_model_from_path(teacher_model, **init_kwargs)
519
+
520
+ # Trainer does not need to remove unused columns — the collator handles raw data
521
+ args.remove_unused_columns = False
522
+
523
+ # ── Call _BaseTrainer.__init__ (which is transformers.Trainer.__init__) ──
524
+ super().__init__(
525
+ model=model,
526
+ args=args,
527
+ data_collator=data_collator,
528
+ train_dataset=train_dataset,
529
+ eval_dataset=eval_dataset,
530
+ processing_class=processing_class,
531
+ compute_metrics=compute_metrics,
532
+ callbacks=callbacks,
533
+ optimizers=optimizers,
534
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
535
+ )
536
+
537
+ # ── Prepare teacher model (after super().__init__ so accelerator is ready) ──
538
+ if teacher_model is not None:
539
+ if self._local_teacher_tokenizer_matches_student:
540
+ teacher_model.resize_token_embeddings(self.model.config.vocab_size)
541
+ if self.is_deepspeed_enabled:
542
+ self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator)
543
+ else:
544
+ self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True)
545
+ else:
546
+ self.teacher_model = None
547
+
548
+ if args.disable_dropout:
549
+ disable_dropout_in_model(self.model)
550
+
551
+ # ── Store config values ──
552
+ self.lmbda = args.lmbda
553
+ self.beta = args.beta
554
+ self.temperature = args.temperature
555
+ self.top_p = args.top_p
556
+ self.num_generations = args.num_generations
557
+ self.reverse_kl_top_1_mode = args.reverse_kl_top_1_mode
558
+ self.loss_top_k = args.loss_top_k
559
+ self.loss_add_tail = args.loss_add_tail
560
+
561
+ # ── Buffer state ──
562
+ self._buffered_inputs = None
563
+ self._buffered_on_policy_flags = None
564
+ self._buffered_text_logs = None
565
+ self._buffer_step = 0
566
+
567
+ # ── Loss tracking ──
568
+ self._on_policy_loss_total = 0.0
569
+ self._off_policy_loss_total = 0.0
570
+ self._on_policy_step_equiv = 0.0
571
+ self._off_policy_step_equiv = 0.0
572
+
573
+ # ── Generation config ──
574
+ generation_kwargs = {
575
+ "max_new_tokens": args.max_completion_length,
576
+ "temperature": args.temperature,
577
+ "top_p": args.top_p,
578
+ "do_sample": True,
579
+ "top_k": args.top_k,
580
+ "pad_token_id": self.processing_class.pad_token_id,
581
+ }
582
+ self.generation_config = GenerationConfig(**generation_kwargs)
583
+ self.generation_kwargs = generation_kwargs
584
+ if (
585
+ hasattr(self.model.generation_config, "eos_token_id")
586
+ and self.model.generation_config.eos_token_id is not None
587
+ ):
588
+ self.generation_config.eos_token_id = self.model.generation_config.eos_token_id
589
+
590
+ # ── Metrics & Logging ──
591
+ self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
592
+ self._total_train_tokens = 0
593
+ self.log_completions = args.log_completions
594
+ self.log_completions_steps = args.log_completions_steps
595
+ self.num_completions_to_print = args.num_completions_to_print
596
+
597
+ self._textual_logs = {
598
+ "prompt": [],
599
+ "completion": [],
600
+ }
601
+
602
+ # ── vLLM for student generation ──
603
+ self.use_vllm = args.use_vllm
604
+ if self.use_vllm:
605
+ if not is_vllm_available():
606
+ raise ImportError(
607
+ "vLLM is not available and use_vllm is set to True. Please install vLLM with "
608
+ "`pip install vllm` to use it."
609
+ )
610
+ self.vllm_generation = VLLMGeneration(
611
+ model=self.model,
612
+ accelerator=self.accelerator,
613
+ is_fsdp_enabled=self.is_fsdp_enabled,
614
+ processing_class=self.processing_class,
615
+ mode=args.vllm_mode,
616
+ structured_outputs_regex=args.vllm_structured_outputs_regex,
617
+ server_base_url=args.vllm_server_base_url,
618
+ server_host=args.vllm_server_host,
619
+ server_port=args.vllm_server_port,
620
+ group_port=args.vllm_group_port,
621
+ server_timeout=args.vllm_server_timeout,
622
+ tensor_parallel_size=args.vllm_tensor_parallel_size,
623
+ gpu_memory_utilization=args.vllm_gpu_memory_utilization,
624
+ max_model_length=args.vllm_max_model_length,
625
+ max_num_seqs=args.per_device_train_batch_size * args.gradient_accumulation_steps,
626
+ enable_sleep_mode=args.vllm_enable_sleep_mode,
627
+ model_impl=args.vllm_model_impl,
628
+ temperature=args.temperature,
629
+ top_p=args.top_p,
630
+ top_k=args.top_k,
631
+ max_completion_length=args.max_completion_length,
632
+ logprobs=None,
633
+ )
634
+ self.vllm_sync_frequency = args.vllm_sync_frequency
635
+ self._last_vllm_sync_step = -1
636
+
637
+ @staticmethod
638
+ def _local_teacher_tokenizers_match(
639
+ student_processing_class: PreTrainedTokenizerBase,
640
+ teacher_processing_class: PreTrainedTokenizerBase,
641
+ ) -> bool:
642
+ """Check whether the student and local teacher tokenizers share the same vocabulary."""
643
+ return student_processing_class.get_vocab() == teacher_processing_class.get_vocab()
644
+
645
+ def _raise_if_local_teacher_tokenizer_mismatch(self) -> None:
646
+ """Guard the base local-teacher JSD path, while still allowing subclass overrides."""
647
+ if self.teacher_model is not None and not self._local_teacher_tokenizer_matches_student:
648
+ raise ValueError(
649
+ "DistillationTrainer's built-in local-teacher loss only supports student/teacher pairs that use "
650
+ "the same tokenizer. Use a same-tokenizer local teacher, set `use_teacher_server=True`, or "
651
+ "override the local teacher loss path in a subclass."
652
+ )
653
+
654
+ def _compute_prompt_length(self, inputs: dict[str, torch.Tensor | Any]) -> int:
655
+ """Compute the earliest prompt boundary that still includes every completion token in the batch."""
656
+ if inputs.get("labels") is not None:
657
+ attention_mask = inputs["attention_mask"]
658
+ labels = inputs["labels"]
659
+ full_lengths = attention_mask.sum(dim=1)
660
+ completion_lengths = (labels != -100).sum(dim=1)
661
+ return int((full_lengths - completion_lengths).min().item())
662
+ return inputs["prompts"].shape[1]
663
+
664
+ def _get_completion_lengths(self, generated_tokens: torch.Tensor, prompt_width: int) -> torch.Tensor:
665
+ """Infer per-sample completion lengths from generated tokens."""
666
+ completion_tokens = generated_tokens[:, prompt_width:]
667
+ pad_token_id = self.processing_class.pad_token_id
668
+ eos_token_id = self.generation_config.eos_token_id
669
+ if eos_token_id is None:
670
+ eos_token_ids = set()
671
+ elif isinstance(eos_token_id, int):
672
+ eos_token_ids = {eos_token_id}
673
+ else:
674
+ eos_token_ids = set(eos_token_id)
675
+ pad_equals_eos = pad_token_id is not None and pad_token_id in eos_token_ids
676
+
677
+ completion_lengths = []
678
+ for row in completion_tokens.tolist():
679
+ if pad_equals_eos and eos_token_ids:
680
+ completion_length = len(row)
681
+ for idx, token_id in enumerate(row):
682
+ if token_id in eos_token_ids:
683
+ completion_length = idx + 1
684
+ break
685
+ elif pad_token_id is not None:
686
+ completion_length = len(row)
687
+ while completion_length > 0 and row[completion_length - 1] == pad_token_id:
688
+ completion_length -= 1
689
+ else:
690
+ completion_length = len(row)
691
+ completion_lengths.append(completion_length)
692
+
693
+ return torch.tensor(completion_lengths, device=generated_tokens.device, dtype=torch.long)
694
+
695
+ # ──────────────────────────────────────────────────────────────────────
696
+ # Dataset / Dataloader
697
+ # ──────────────────────────────────────────────────────────────────────
698
+
699
+ def _set_signature_columns_if_needed(self):
700
+ super()._set_signature_columns_if_needed()
701
+ extra_columns = ["prompts", "prompt_attention_mask", "messages", "chat_template_kwargs", "tools"]
702
+ if self._signature_columns is None:
703
+ self._signature_columns = extra_columns
704
+ else:
705
+ for col in extra_columns:
706
+ if col not in self._signature_columns:
707
+ self._signature_columns.append(col)
708
+
709
+ def _get_train_sampler(self, dataset=None):
710
+ if dataset is None:
711
+ dataset = self.train_dataset
712
+ return RepeatSampler(
713
+ data_source=dataset,
714
+ mini_repeat_count=self.num_generations,
715
+ batch_size=self.args.generation_batch_size * self.accelerator.num_processes,
716
+ repeat_count=1,
717
+ shuffle=True,
718
+ seed=self.args.seed,
719
+ )
720
+
721
+ def get_train_dataloader(self):
722
+ """
723
+ Override to load one generation batch per optimizer window.
724
+
725
+ The dataloader yields batches of size `per_device_train_batch_size * gradient_accumulation_steps`.
726
+ RepeatSampler ensures each generation batch is repeated `gradient_accumulation_steps` times so the Trainer's
727
+ loop iterates the correct number of times.
728
+ """
729
+ if self.train_dataset is None:
730
+ raise ValueError("Trainer: training requires a train_dataset.")
731
+
732
+ train_dataset = self.train_dataset
733
+ data_collator = self.data_collator
734
+
735
+ dataloader_params = {
736
+ "batch_size": self._train_batch_size * self.args.gradient_accumulation_steps,
737
+ "collate_fn": data_collator,
738
+ "num_workers": self.args.dataloader_num_workers,
739
+ "pin_memory": self.args.dataloader_pin_memory,
740
+ "persistent_workers": self.args.dataloader_persistent_workers,
741
+ }
742
+
743
+ if not isinstance(train_dataset, torch.utils.data.IterableDataset):
744
+ dataloader_params["sampler"] = self._get_train_sampler()
745
+ dataloader_params["drop_last"] = self.args.dataloader_drop_last
746
+ dataloader_params["worker_init_fn"] = partial(
747
+ seed_worker,
748
+ num_workers=self.args.dataloader_num_workers,
749
+ rank=self.args.process_index,
750
+ )
751
+ if self.args.dataloader_num_workers > 0:
752
+ dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor
753
+
754
+ base_dataloader = self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params))
755
+ return _RepeatBatchDataLoader(base_dataloader, repeat_count=self.args.gradient_accumulation_steps)
756
+
757
+ # ──────────────────────────────────────────────────────────────────────
758
+ # Buffering: on/off-policy mixing across gradient accumulation steps
759
+ # ──────────────────────────────────────────────────────────────────────
760
+
761
+ @profiling_decorator
762
+ def _prepare_inputs(self, generation_batch: dict[str, torch.Tensor | Any]) -> dict[str, torch.Tensor | Any]:
763
+ if not self.model.training:
764
+ return generation_batch
765
+
766
+ buffer_steps = self.args.gradient_accumulation_steps
767
+ if self._buffer_step % buffer_steps == 0 or self._buffered_inputs is None:
768
+ self._fill_buffer(generation_batch, buffer_steps)
769
+
770
+ slice_idx = self._buffer_step % buffer_steps
771
+ inputs = self._buffered_inputs[slice_idx]
772
+ self._buffer_step += 1
773
+ return inputs
774
+
775
+ @profiling_decorator
776
+ def _fill_buffer(self, generation_batch: dict[str, torch.Tensor | Any], buffer_steps: int):
777
+ """Split batch into slices and decide which are on-policy (student-generated) vs off-policy."""
778
+ slices = split_tensor_dict(generation_batch, buffer_steps)
779
+
780
+ # Decide on-policy flags (synchronized across processes)
781
+ if self.accelerator.is_main_process:
782
+ on_policy_flags = [random.random() <= self.lmbda for _ in range(buffer_steps)]
783
+ else:
784
+ on_policy_flags = [False] * buffer_steps
785
+ on_policy_flags = broadcast_object_list(on_policy_flags, from_process=0)
786
+
787
+ self._buffered_inputs = [None] * buffer_steps
788
+ self._buffered_on_policy_flags = on_policy_flags
789
+ self._buffered_text_logs = [None] * buffer_steps
790
+
791
+ # Store off-policy slices directly
792
+ on_policy_indices = []
793
+ for i, is_on_policy in enumerate(on_policy_flags):
794
+ if is_on_policy:
795
+ on_policy_indices.append(i)
796
+ else:
797
+ self._buffered_inputs[i] = slices[i]
798
+
799
+ # Generate student completions for on-policy slices
800
+ if on_policy_indices:
801
+ self._generate_student_completions(slices, on_policy_indices)
802
+
803
+ # Gather on-policy text logs once per optimizer step (all processes must participate)
804
+ if self.log_completions:
805
+ on_policy_prompts = []
806
+ on_policy_completions = []
807
+ for i in on_policy_indices:
808
+ if self._buffered_text_logs[i] is not None:
809
+ prompts, completions = self._buffered_text_logs[i]
810
+ on_policy_prompts.extend(prompts)
811
+ on_policy_completions.extend(completions)
812
+ self._textual_logs["prompt"].extend(gather_object(on_policy_prompts))
813
+ self._textual_logs["completion"].extend(gather_object(on_policy_completions))
814
+
815
+ @profiling_decorator
816
+ def _generate_student_completions(self, slices: list[dict[str, torch.Tensor | Any]], on_policy_indices: list[int]):
817
+ """Generate completions from the student model for on-policy training."""
818
+ if not self.use_vllm:
819
+ self._generate_with_model(slices, on_policy_indices)
820
+ return
821
+
822
+ # Collect all prompts across on-policy slices, stripping left-padding so vLLM
823
+ # receives only real prompt token IDs (like GRPO trainer).
824
+ local_prompts = []
825
+ local_slice_indices = []
826
+ pad_token_id = self.processing_class.pad_token_id
827
+ for slice_idx in on_policy_indices:
828
+ prompt_mask = slices[slice_idx].get("prompt_attention_mask")
829
+ for i, prompt in enumerate(slices[slice_idx]["prompts"]):
830
+ if prompt_mask is not None:
831
+ prompt = prompt[prompt_mask[i].bool()]
832
+ elif pad_token_id is not None:
833
+ first_non_pad = (prompt != pad_token_id).nonzero(as_tuple=True)[0]
834
+ if len(first_non_pad) > 0:
835
+ prompt = prompt[first_non_pad[0] :]
836
+ local_prompts.append(prompt)
837
+ local_slice_indices.append(slice_idx)
838
+
839
+ # Sync student weights to vLLM if needed
840
+ if (
841
+ self.state.global_step != self._last_vllm_sync_step
842
+ and self.state.global_step % self.vllm_sync_frequency == 0
843
+ ):
844
+ self.vllm_generation.sync_weights()
845
+ self._last_vllm_sync_step = self.state.global_step
846
+
847
+ # Generate completions — pass token IDs directly, no text decoding
848
+ prompt_ids_list = [p.tolist() for p in local_prompts]
849
+ _, completion_ids, _, _ = self.vllm_generation.generate(
850
+ prompts=prompt_ids_list, images=None, num_generations=self.num_generations
851
+ )
852
+
853
+ # Process completions into the buffer
854
+ self._store_completions_in_buffer(
855
+ slices, on_policy_indices, local_slice_indices, local_prompts, completion_ids
856
+ )
857
+
858
+ def _generate_with_model(self, slices: list[dict[str, torch.Tensor | Any]], on_policy_indices: list[int]):
859
+ """Fallback generation using model.generate() (no vLLM)."""
860
+ with unwrap_model_for_generation(
861
+ self.model, self.accelerator, generation_kwargs=self.generation_kwargs
862
+ ) as unwrapped_model:
863
+ for slice_idx in on_policy_indices:
864
+ slice_inputs = slices[slice_idx]
865
+ generated_outputs = unwrapped_model.generate(
866
+ input_ids=slice_inputs["prompts"],
867
+ attention_mask=slice_inputs.get("prompt_attention_mask", None),
868
+ generation_config=self.generation_config,
869
+ return_dict_in_generate=True,
870
+ )
871
+ generated_tokens = generated_outputs.sequences
872
+ batch_size = generated_tokens.size(0)
873
+ device = generated_tokens.device
874
+ pad_token_id = self.processing_class.pad_token_id
875
+ prompt_width = slice_inputs["prompts"].shape[1]
876
+ prompt_mask = slice_inputs.get("prompt_attention_mask")
877
+ if prompt_mask is not None:
878
+ prompt_token_lengths = prompt_mask.sum(dim=1)
879
+ else:
880
+ prompt_token_lengths = torch.full((batch_size,), prompt_width, dtype=torch.long, device=device)
881
+ completion_lengths = self._get_completion_lengths(generated_tokens, prompt_width)
882
+ new_attention_mask, new_labels = self._build_sequence_batch(
883
+ generated_tokens, prompt_width, prompt_token_lengths, completion_lengths
884
+ )
885
+
886
+ # Decode for logging
887
+ prompt_texts = []
888
+ completion_texts = []
889
+ for idx in range(batch_size):
890
+ prompt_tokens = slice_inputs["prompts"][idx]
891
+ if prompt_mask is not None:
892
+ prompt_tokens = prompt_tokens[prompt_mask[idx].bool()]
893
+ elif pad_token_id is not None:
894
+ prompt_tokens = prompt_tokens[prompt_tokens != pad_token_id]
895
+ prompt_texts.append(
896
+ self.processing_class.decode(prompt_tokens.tolist(), skip_special_tokens=False)
897
+ )
898
+ length = prompt_width
899
+ completion_length = int(completion_lengths[idx].item())
900
+ completion_texts.append(
901
+ self.processing_class.decode(
902
+ generated_tokens[idx, length : length + completion_length].tolist(),
903
+ skip_special_tokens=False,
904
+ )
905
+ )
906
+
907
+ updated = dict(slice_inputs)
908
+ updated["input_ids"] = generated_tokens
909
+ updated["attention_mask"] = new_attention_mask
910
+ updated["labels"] = new_labels
911
+
912
+ self._buffered_inputs[slice_idx] = updated
913
+ self._buffered_text_logs[slice_idx] = (prompt_texts, completion_texts)
914
+
915
+ def _store_completions_in_buffer(
916
+ self,
917
+ slices: list[dict[str, torch.Tensor | Any]],
918
+ on_policy_indices: list[int],
919
+ local_slice_indices: list[int],
920
+ local_prompts: list[torch.Tensor],
921
+ completion_ids: list,
922
+ ):
923
+ """Process vLLM completions and store them in the buffer.
924
+
925
+ Uses original prompt token IDs directly (no decode/re-encode roundtrip), following the same approach as
926
+ GRPOTrainer.
927
+ """
928
+ device = self.accelerator.device
929
+ pad_token_id = self.processing_class.pad_token_id if self.processing_class.pad_token_id is not None else 0
930
+ max_completion_length = self.generation_config.max_new_tokens
931
+
932
+ # Group completions and prompt token IDs by slice
933
+ slice_completions = {idx: [] for idx in on_policy_indices}
934
+ slice_prompt_ids = {idx: [] for idx in on_policy_indices}
935
+ for i, slice_idx in enumerate(local_slice_indices):
936
+ slice_completions[slice_idx].append(completion_ids[i])
937
+ slice_prompt_ids[slice_idx].append(local_prompts[i])
938
+
939
+ for slice_idx in on_policy_indices:
940
+ slice_inputs = slices[slice_idx]
941
+ prompt_id_tensors = slice_prompt_ids[slice_idx]
942
+ prompt_width = max(len(p) for p in prompt_id_tensors)
943
+ prompt_token_lengths = torch.tensor([len(p) for p in prompt_id_tensors], device=device, dtype=torch.long)
944
+ prompt_attention_mask = (
945
+ torch.arange(prompt_width, device=device).unsqueeze(0)
946
+ >= (prompt_width - prompt_token_lengths).unsqueeze(1)
947
+ ).long()
948
+
949
+ # Left-pad prompt token IDs to the longest prompt in this slice
950
+ prompt_ids = torch.stack(
951
+ [F.pad(p, (prompt_width - len(p), 0), value=pad_token_id) for p in prompt_id_tensors]
952
+ ).to(device)
953
+
954
+ # Pad/truncate completions (right-pad to max_completion_length)
955
+ completion_tensors = []
956
+ completion_ids_for_text = []
957
+ completion_lengths = []
958
+ for comp_ids in slice_completions[slice_idx]:
959
+ t = torch.tensor(comp_ids, device=device)
960
+ if len(t) > max_completion_length:
961
+ t = t[:max_completion_length]
962
+ completion_ids_for_text.append(t.tolist())
963
+ completion_lengths.append(len(t))
964
+ if len(t) < max_completion_length:
965
+ padding = torch.full((max_completion_length - len(t),), pad_token_id, device=device, dtype=t.dtype)
966
+ t = torch.cat([t, padding])
967
+ completion_tensors.append(t)
968
+
969
+ completion_ids_padded = torch.stack(completion_tensors)
970
+ new_input_ids = torch.cat([prompt_ids, completion_ids_padded], dim=1)
971
+ completion_lengths = torch.tensor(completion_lengths, device=device, dtype=torch.long)
972
+ new_attention_mask, new_labels = self._build_sequence_batch(
973
+ new_input_ids, prompt_width, prompt_token_lengths, completion_lengths
974
+ )
975
+
976
+ # Decode for logging only
977
+ prompt_texts = self.processing_class.batch_decode(
978
+ prompt_id_tensors, skip_special_tokens=False, clean_up_tokenization_spaces=False
979
+ )
980
+ completion_texts = self.processing_class.batch_decode(
981
+ completion_ids_for_text, skip_special_tokens=False, clean_up_tokenization_spaces=False
982
+ )
983
+
984
+ updated = dict(slice_inputs)
985
+ updated["input_ids"] = new_input_ids
986
+ updated["attention_mask"] = new_attention_mask
987
+ updated["labels"] = new_labels
988
+ # Update prompts to match the new padding width so prompt_length is consistent
989
+ updated["prompts"] = prompt_ids
990
+ updated["prompt_attention_mask"] = prompt_attention_mask
991
+
992
+ self._buffered_inputs[slice_idx] = updated
993
+ self._buffered_text_logs[slice_idx] = (prompt_texts, completion_texts)
994
+
995
+ @staticmethod
996
+ def _build_sequence_batch(
997
+ new_input_ids: torch.Tensor,
998
+ prompt_width: int,
999
+ prompt_token_lengths: torch.Tensor,
1000
+ completion_lengths: torch.Tensor,
1001
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1002
+ """Build attention mask and labels from prompt/completion lengths."""
1003
+ prompt_token_lengths = prompt_token_lengths.to(device=new_input_ids.device, dtype=torch.long)
1004
+ completion_lengths = completion_lengths.to(device=new_input_ids.device, dtype=torch.long)
1005
+ positions = torch.arange(new_input_ids.shape[1], device=new_input_ids.device).unsqueeze(0)
1006
+ prompt_mask = (positions < prompt_width) & (positions >= (prompt_width - prompt_token_lengths).unsqueeze(1))
1007
+ completion_mask = (positions >= prompt_width) & (positions < (prompt_width + completion_lengths).unsqueeze(1))
1008
+ new_attention_mask = (prompt_mask | completion_mask).long()
1009
+
1010
+ new_labels = torch.full_like(new_input_ids, -100)
1011
+ new_labels[completion_mask] = new_input_ids[completion_mask]
1012
+
1013
+ return new_attention_mask, new_labels
1014
+
1015
+ # ──────────────────────────────────────────────────────────────────────
1016
+ # Loss computation
1017
+ # ──────────────────────────────────────────────────────────────────────
1018
+
1019
+ @staticmethod
1020
+ def _reduce_divergence_loss(jsd, labels=None, reduction="batchmean"):
1021
+ """Reduce a per-token divergence tensor using the trainer's label mask semantics."""
1022
+ mask = None
1023
+ if labels is not None:
1024
+ mask = labels != -100
1025
+ jsd = jsd[mask]
1026
+
1027
+ if reduction == "batchmean":
1028
+ if labels is not None:
1029
+ num_tokens = mask.sum()
1030
+ if num_tokens == 0:
1031
+ return jsd.sum() * 0.0 # no completion tokens — return zero-grad scalar
1032
+ return jsd.sum() / num_tokens
1033
+ return jsd.sum() / jsd.size(0)
1034
+ elif reduction == "sum":
1035
+ return jsd.sum()
1036
+ elif reduction == "mean":
1037
+ return jsd.mean()
1038
+ else:
1039
+ return jsd
1040
+
1041
+ @staticmethod
1042
+ def generalized_jsd_loss(
1043
+ student_logits,
1044
+ teacher_logits,
1045
+ labels=None,
1046
+ beta=0.5,
1047
+ temperature=1.0,
1048
+ reduction="batchmean",
1049
+ top_k=0,
1050
+ add_tail=True,
1051
+ ):
1052
+ """
1053
+ Compute the generalized Jensen-Shannon Divergence loss for knowledge distillation.
1054
+
1055
+ Args:
1056
+ student_logits: Tensor of shape (batch_size, sequence_length, vocab_size).
1057
+ teacher_logits: Tensor of shape (batch_size, sequence_length, vocab_size).
1058
+ labels: Tensor of shape (batch_size, sequence_length) with -100 for positions to ignore.
1059
+ beta: Interpolation coefficient. 0.0 = forward KL, 1.0 = reverse KL.
1060
+ temperature: Softmax temperature.
1061
+ reduction: 'batchmean', 'sum', 'mean', or 'none'.
1062
+ top_k: Number of top tokens to restrict the loss to. The support set depends on beta:
1063
+ beta=0 (forward KL) uses teacher's top-k, beta=1 (reverse KL) uses student's top-k, 0<beta<1 (JSD) uses
1064
+ the union of both. Distributions are re-normalized over the selected support. If 0, the full vocabulary
1065
+ is used.
1066
+ add_tail: Whether to append a tail bucket representing the remaining probability mass
1067
+ outside the selected top-k support.
1068
+
1069
+ Returns:
1070
+ Scalar loss tensor.
1071
+ """
1072
+ student_logits = student_logits / temperature
1073
+ teacher_logits = teacher_logits / temperature
1074
+
1075
+ support_mask = None
1076
+
1077
+ if top_k > 0 and student_logits.size(-1) > top_k:
1078
+ neg_inf = torch.full((), float("-inf"), dtype=student_logits.dtype, device=student_logits.device)
1079
+ student_log_probs_full = F.log_softmax(student_logits, dim=-1)
1080
+ teacher_log_probs_full = F.log_softmax(teacher_logits, dim=-1)
1081
+
1082
+ if beta == 0:
1083
+ # Forward KL: teacher-selected support
1084
+ _, support = teacher_logits.topk(top_k, dim=-1)
1085
+ support_mask = torch.ones_like(support, dtype=torch.bool)
1086
+ elif beta == 1:
1087
+ # Reverse KL: student-selected support
1088
+ _, support = student_logits.topk(top_k, dim=-1)
1089
+ support_mask = torch.ones_like(support, dtype=torch.bool)
1090
+ else:
1091
+ # JSD: union of both supports (concatenate + deduplicate)
1092
+ _, student_top = student_logits.topk(top_k, dim=-1)
1093
+ _, teacher_top = teacher_logits.topk(top_k, dim=-1)
1094
+ support = torch.cat([teacher_top, student_top], dim=-1)
1095
+ support_mask = torch.ones(support.shape, dtype=torch.bool, device=support.device)
1096
+ for i in range(1, support.shape[-1]):
1097
+ prev_matches = support[..., i : i + 1] == support[..., :i]
1098
+ prev_valid = support_mask[..., :i]
1099
+ support_mask[..., i] &= ~(prev_matches & prev_valid).any(dim=-1)
1100
+ support = torch.where(support_mask, support, torch.zeros_like(support))
1101
+
1102
+ student_support_logps = student_log_probs_full.gather(-1, support)
1103
+ teacher_support_logps = teacher_log_probs_full.gather(-1, support)
1104
+
1105
+ # Mask invalid (duplicate) positions with -inf
1106
+ student_topk_logps = torch.where(support_mask, student_support_logps, neg_inf)
1107
+ teacher_topk_logps = torch.where(support_mask, teacher_support_logps, neg_inf)
1108
+
1109
+ if add_tail:
1110
+ # Add tail bucket: append log(1 - sum(exp(top_k_logps))) to preserve
1111
+ # the remaining probability mass outside the top-k. This prevents trivial
1112
+ # zero loss when top_k is small (especially top_k=1).
1113
+ base_support_mask = support_mask
1114
+ student_log_probs, support_mask = _add_tail_bucket(student_topk_logps, base_support_mask)
1115
+ teacher_log_probs, _ = _add_tail_bucket(teacher_topk_logps, base_support_mask)
1116
+ else:
1117
+ student_log_probs = student_topk_logps - torch.logsumexp(student_topk_logps, dim=-1, keepdim=True)
1118
+ teacher_log_probs = teacher_topk_logps - torch.logsumexp(teacher_topk_logps, dim=-1, keepdim=True)
1119
+ else:
1120
+ student_log_probs = F.log_softmax(student_logits, dim=-1)
1121
+ teacher_log_probs = F.log_softmax(teacher_logits, dim=-1)
1122
+
1123
+ jsd = _jsd_divergence(student_log_probs, teacher_log_probs, beta, support_mask)
1124
+ return DistillationTrainer._reduce_divergence_loss(jsd, labels=labels, reduction=reduction)
1125
+
1126
+ def _get_reverse_kl_top_1_tokens(
1127
+ self, student_scores: torch.Tensor, completion_tokens: torch.Tensor
1128
+ ) -> torch.Tensor:
1129
+ """Return the reverse-KL top-1 token IDs for the mixed top-1 loss path.
1130
+
1131
+ Args:
1132
+ student_scores: Any (B, T, V) tensor whose argmax selects the student's top token
1133
+ (logits or log-probs — both are order-preserving).
1134
+ completion_tokens: (B, T) actual token IDs in the completion.
1135
+ """
1136
+ if self.reverse_kl_top_1_mode == "argmax":
1137
+ return student_scores.argmax(dim=-1)
1138
+ return completion_tokens
1139
+
1140
+ def _compute_sparse_top_1_divergence_loss(
1141
+ self,
1142
+ student_log_probs: torch.Tensor,
1143
+ teacher_top1_token_ids: torch.Tensor,
1144
+ teacher_top1_logprobs: torch.Tensor,
1145
+ reverse_token_ids: torch.Tensor,
1146
+ reverse_teacher_logprobs: torch.Tensor,
1147
+ labels: torch.Tensor,
1148
+ ) -> torch.Tensor:
1149
+ """Compute exact generalized JSD/KL on top-1 support for the mixed beta>0 path."""
1150
+ neg_inf = torch.full((), float("-inf"), dtype=student_log_probs.dtype, device=student_log_probs.device)
1151
+
1152
+ if self.beta == 1:
1153
+ support = reverse_token_ids.unsqueeze(-1)
1154
+ support_mask = torch.ones_like(support, dtype=torch.bool)
1155
+ teacher_support_logprobs = reverse_teacher_logprobs.unsqueeze(-1)
1156
+ else:
1157
+ teacher_support = teacher_top1_token_ids.unsqueeze(-1)
1158
+ reverse_support = reverse_token_ids.unsqueeze(-1)
1159
+ support = torch.cat([teacher_support, reverse_support], dim=-1)
1160
+ support_mask = torch.ones_like(support, dtype=torch.bool)
1161
+ support_mask[..., 1] = support[..., 1] != support[..., 0]
1162
+ teacher_support_logprobs = torch.stack([teacher_top1_logprobs, reverse_teacher_logprobs], dim=-1)
1163
+ support = torch.where(support_mask, support, torch.zeros_like(support))
1164
+
1165
+ student_support_logprobs = student_log_probs.gather(-1, support)
1166
+ student_support_logprobs = torch.where(support_mask, student_support_logprobs, neg_inf)
1167
+ teacher_support_logprobs = torch.where(support_mask, teacher_support_logprobs, neg_inf)
1168
+
1169
+ if self.loss_add_tail:
1170
+ base_support_mask = support_mask
1171
+ student_sparse_log_probs, support_mask = _add_tail_bucket(student_support_logprobs, base_support_mask)
1172
+ teacher_sparse_log_probs, _ = _add_tail_bucket(teacher_support_logprobs, base_support_mask)
1173
+ else:
1174
+ student_sparse_log_probs = student_support_logprobs - torch.logsumexp(
1175
+ student_support_logprobs, dim=-1, keepdim=True
1176
+ )
1177
+ teacher_sparse_log_probs = teacher_support_logprobs - torch.logsumexp(
1178
+ teacher_support_logprobs, dim=-1, keepdim=True
1179
+ )
1180
+
1181
+ jsd = _jsd_divergence(student_sparse_log_probs, teacher_sparse_log_probs, self.beta, support_mask)
1182
+ return self._reduce_divergence_loss(jsd, labels=labels, reduction="batchmean")
1183
+
1184
+ def _compute_local_sparse_top_1_divergence_loss(
1185
+ self,
1186
+ student_logits: torch.Tensor,
1187
+ teacher_logits: torch.Tensor,
1188
+ completion_tokens: torch.Tensor,
1189
+ labels: torch.Tensor,
1190
+ ) -> torch.Tensor:
1191
+ """Compute the mixed top-1 loss for a local teacher using gathered full-logit probabilities."""
1192
+ student_log_probs = F.log_softmax(student_logits / self.temperature, dim=-1)
1193
+ teacher_log_probs = F.log_softmax(teacher_logits / self.temperature, dim=-1)
1194
+
1195
+ teacher_top1_token_ids = teacher_logits.argmax(dim=-1)
1196
+ teacher_top1_logprobs = teacher_log_probs.gather(dim=-1, index=teacher_top1_token_ids.unsqueeze(-1)).squeeze(
1197
+ -1
1198
+ )
1199
+ reverse_token_ids = self._get_reverse_kl_top_1_tokens(student_logits, completion_tokens)
1200
+ reverse_teacher_logprobs = teacher_log_probs.gather(dim=-1, index=reverse_token_ids.unsqueeze(-1)).squeeze(-1)
1201
+
1202
+ return self._compute_sparse_top_1_divergence_loss(
1203
+ student_log_probs=student_log_probs,
1204
+ teacher_top1_token_ids=teacher_top1_token_ids,
1205
+ teacher_top1_logprobs=teacher_top1_logprobs,
1206
+ reverse_token_ids=reverse_token_ids,
1207
+ reverse_teacher_logprobs=reverse_teacher_logprobs,
1208
+ labels=labels,
1209
+ )
1210
+
1211
+ def _get_teacher_logits(self, inputs: dict[str, torch.Tensor | Any]) -> torch.Tensor:
1212
+ """Get teacher logits — dispatches between local model and external server."""
1213
+ if self.teacher_model is not None:
1214
+ self.teacher_model.eval()
1215
+ with torch.no_grad():
1216
+ return self.teacher_model(
1217
+ input_ids=inputs["input_ids"],
1218
+ attention_mask=inputs["attention_mask"],
1219
+ ).logits
1220
+ elif self.use_teacher_server:
1221
+ raise NotImplementedError(
1222
+ "Fetching full teacher logits with use_teacher_server=True is not supported. "
1223
+ "Server-backed distillation only supports per-token logprobs via "
1224
+ "`_get_teacher_token_logprobs_from_server`."
1225
+ )
1226
+ else:
1227
+ raise ValueError("No teacher model or teacher server configured.")
1228
+
1229
+ def _get_teacher_token_logprobs_from_server(
1230
+ self,
1231
+ inputs: dict[str, torch.Tensor | Any],
1232
+ aligned_prompt_length: int,
1233
+ ) -> dict[str, torch.Tensor]:
1234
+ """Fetch per-token teacher logprobs from an external vLLM server.
1235
+
1236
+ Returns a dict with:
1237
+ ``actual_logprobs`` – (batch, completion_length) teacher log-prob for the actual
1238
+ token at each position (for reverse KL).
1239
+ ``topk_logprobs`` – (batch, completion_length, K) teacher top-k sorted logprobs
1240
+ (for forward KL).
1241
+ ``topk_token_ids`` – (batch, completion_length, K) corresponding token IDs.
1242
+ """
1243
+ import numpy as np
1244
+
1245
+ input_ids = inputs["input_ids"]
1246
+ batch_size = input_ids.shape[0]
1247
+ sequences, prompt_lengths, completion_lengths = build_teacher_request_inputs(
1248
+ input_ids,
1249
+ inputs["attention_mask"],
1250
+ prompt_attention_mask=inputs.get("prompt_attention_mask"),
1251
+ labels=inputs.get("labels"),
1252
+ )
1253
+
1254
+ # The pure forward server path can use the requested teacher top-k support.
1255
+ # When beta > 0, config validation restricts the server-backed path to top-1.
1256
+ requested_top_k = self.loss_top_k
1257
+ result = self.teacher_client.get_sequence_logprobs(
1258
+ sequences=sequences,
1259
+ prompt_lengths=prompt_lengths,
1260
+ top_logprobs=requested_top_k,
1261
+ temperature=self.temperature,
1262
+ )
1263
+ K = requested_top_k
1264
+
1265
+ device = input_ids.device
1266
+ labels = inputs.get("labels")
1267
+ if labels is None:
1268
+ raise ValueError("labels are required to align teacher-server logprobs with the student loss tensors.")
1269
+
1270
+ # The student loss slices tensors in padded-sequence coordinates starting at `aligned_prompt_length`.
1271
+ # Place each teacher completion into that same coordinate system by locating the first non-masked completion
1272
+ # token in `labels`. This works for both left-padded off-policy batches and on-policy batches where
1273
+ # completions are right-padded after a fixed-width prompt block.
1274
+ completion_offsets = []
1275
+ label_mask = labels != -100
1276
+ for sample_mask, comp_len in zip(label_mask, completion_lengths, strict=True):
1277
+ if comp_len == 0:
1278
+ completion_offsets.append(0)
1279
+ continue
1280
+ completion_start = int(torch.nonzero(sample_mask, as_tuple=False)[0].item())
1281
+ completion_offsets.append(completion_start - aligned_prompt_length)
1282
+
1283
+ # Size the output tensors to tightly fit the teacher logprobs. Using the full padded
1284
+ # sequence length would include padding positions with -inf teacher logprobs, producing
1285
+ # inf in the forward pass and NaN gradients in the backward pass (0 * inf = NaN).
1286
+ completion_length = max(
1287
+ (offset + len(lps) for offset, lps in zip(completion_offsets, result["logprobs"], strict=True)),
1288
+ default=0,
1289
+ )
1290
+
1291
+ # actual_logprobs: (B, T) — teacher logprob for the actual token
1292
+ def _actual_to_tensor(key):
1293
+ arr = np.full((batch_size, completion_length), float("-inf"), dtype=np.float32)
1294
+ for i, (offset, seq_lps) in enumerate(zip(completion_offsets, result[key], strict=True)):
1295
+ if seq_lps:
1296
+ vals = np.array(seq_lps, dtype=np.float32) # (comp_len_i, 1)
1297
+ arr[i, offset : offset + vals.shape[0]] = vals[:, 0]
1298
+ return torch.from_numpy(arr).to(device)
1299
+
1300
+ # topk: (B, T, K)
1301
+ def _topk_to_tensor(key, k, np_dtype, fill):
1302
+ arr = np.full((batch_size, completion_length, k), fill, dtype=np_dtype)
1303
+ for i, (offset, seq_vals) in enumerate(zip(completion_offsets, result[key], strict=True)):
1304
+ if seq_vals:
1305
+ vals = np.array(seq_vals, dtype=np_dtype) # (comp_len_i, k)
1306
+ arr[i, offset : offset + vals.shape[0], :] = vals
1307
+ return torch.from_numpy(arr).to(device)
1308
+
1309
+ return {
1310
+ "actual_logprobs": _actual_to_tensor("actual_logprobs"),
1311
+ "topk_logprobs": _topk_to_tensor("logprobs", K, np.float32, float("-inf")),
1312
+ "topk_token_ids": _topk_to_tensor("logprob_token_ids", K, np.int64, 0),
1313
+ }
1314
+
1315
+ def _compute_server_sparse_top_1_divergence_loss(
1316
+ self,
1317
+ teacher_result: dict[str, torch.Tensor],
1318
+ student_log_probs: torch.Tensor,
1319
+ completion_tokens: torch.Tensor,
1320
+ labels: torch.Tensor,
1321
+ ) -> torch.Tensor:
1322
+ """Compute exact sparse top-1 generalized JSD/KL from server-provided teacher logprobs.
1323
+
1324
+ Args:
1325
+ teacher_result: dict with ``actual_logprobs`` (B, T), ``topk_logprobs`` (B, T, K),
1326
+ ``topk_token_ids`` (B, T, K).
1327
+ student_log_probs: (B, T, V) student log-softmax over vocabulary.
1328
+ completion_tokens: (B, T) actual token IDs in the completion.
1329
+ labels: (B, T) with -100 for positions to ignore.
1330
+ """
1331
+ topk_teacher_lps = teacher_result["topk_logprobs"] # (B, T, 1)
1332
+ topk_token_ids = teacher_result["topk_token_ids"] # (B, T, 1)
1333
+ actual_teacher_lps = teacher_result["actual_logprobs"] # (B, T)
1334
+ required = labels != -100
1335
+
1336
+ missing_actual = required & ~torch.isfinite(actual_teacher_lps)
1337
+ if missing_actual.any():
1338
+ missing_count = int(missing_actual.sum().item())
1339
+ total_required = int(required.sum().item())
1340
+ raise ValueError(
1341
+ "Teacher server is missing actual-token logprobs for required reverse-KL positions: "
1342
+ f"{missing_count}/{total_required}."
1343
+ )
1344
+ if self.beta < 1:
1345
+ teacher_top1_logprobs = topk_teacher_lps.squeeze(-1)
1346
+ missing_top1 = required & ~torch.isfinite(teacher_top1_logprobs)
1347
+ if missing_top1.any():
1348
+ missing_count = int(missing_top1.sum().item())
1349
+ total_required = int(required.sum().item())
1350
+ raise ValueError(
1351
+ "Teacher server is missing top-1 logprobs for required forward-KL positions: "
1352
+ f"{missing_count}/{total_required}."
1353
+ )
1354
+
1355
+ # Server path only supports "sampled" mode — config validation enforces this, but we guard
1356
+ # explicitly so future relaxations of the config check don't silently change behaviour.
1357
+ reverse_token_ids = self._get_reverse_kl_top_1_tokens(student_log_probs, completion_tokens)
1358
+ return self._compute_sparse_top_1_divergence_loss(
1359
+ student_log_probs=student_log_probs,
1360
+ teacher_top1_token_ids=topk_token_ids.squeeze(-1),
1361
+ teacher_top1_logprobs=topk_teacher_lps.squeeze(-1),
1362
+ reverse_token_ids=reverse_token_ids,
1363
+ reverse_teacher_logprobs=actual_teacher_lps,
1364
+ labels=labels,
1365
+ )
1366
+
1367
+ def _compute_server_forward_kl_loss(
1368
+ self,
1369
+ teacher_result: dict[str, torch.Tensor],
1370
+ student_log_probs: torch.Tensor,
1371
+ labels: torch.Tensor,
1372
+ ) -> torch.Tensor:
1373
+ """Compute sparse forward KL from server-provided teacher top-k logprobs (beta==0 path).
1374
+
1375
+ Args:
1376
+ teacher_result: dict with ``topk_logprobs`` (B, T, K) and ``topk_token_ids`` (B, T, K).
1377
+ student_log_probs: (B, T, V) student log-softmax over vocabulary.
1378
+ labels: (B, T) with -100 for positions to ignore.
1379
+ """
1380
+ teacher_topk_logprobs = teacher_result["topk_logprobs"]
1381
+ teacher_topk_token_ids = teacher_result["topk_token_ids"]
1382
+ valid = teacher_topk_logprobs > float("-inf")
1383
+ neg_inf = torch.full((), float("-inf"), dtype=student_log_probs.dtype, device=student_log_probs.device)
1384
+ student_topk_logprobs = student_log_probs.gather(dim=-1, index=teacher_topk_token_ids)
1385
+ student_topk_logprobs = torch.where(valid, student_topk_logprobs, neg_inf)
1386
+ teacher_topk_logprobs = torch.where(valid, teacher_topk_logprobs, neg_inf)
1387
+
1388
+ if self.loss_add_tail:
1389
+ base_support_mask = valid
1390
+ student_sparse_log_probs, support_mask = _add_tail_bucket(student_topk_logprobs, base_support_mask)
1391
+ teacher_sparse_log_probs, _ = _add_tail_bucket(teacher_topk_logprobs, base_support_mask)
1392
+ else:
1393
+ support_mask = valid
1394
+ student_sparse_log_probs = student_topk_logprobs - torch.logsumexp(
1395
+ student_topk_logprobs, dim=-1, keepdim=True
1396
+ )
1397
+ teacher_sparse_log_probs = teacher_topk_logprobs - torch.logsumexp(
1398
+ teacher_topk_logprobs, dim=-1, keepdim=True
1399
+ )
1400
+
1401
+ jsd = _jsd_divergence(
1402
+ student_sparse_log_probs,
1403
+ teacher_sparse_log_probs,
1404
+ beta=0.0,
1405
+ support_mask=support_mask,
1406
+ )
1407
+ return self._reduce_divergence_loss(jsd, labels=labels, reduction="batchmean")
1408
+
1409
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
1410
+ self._raise_if_local_teacher_tokenizer_mismatch()
1411
+
1412
+ if self.use_liger_loss:
1413
+ loss = self._compute_liger_loss(model, inputs)
1414
+ return (loss, None) if return_outputs else loss
1415
+
1416
+ # Student forward pass
1417
+ student_outputs = model(
1418
+ input_ids=inputs["input_ids"],
1419
+ attention_mask=inputs["attention_mask"],
1420
+ )
1421
+ prompt_length = self._compute_prompt_length(inputs)
1422
+ labels = inputs["labels"][:, prompt_length:]
1423
+ completion_tokens = inputs["input_ids"][:, prompt_length:]
1424
+
1425
+ if self.use_teacher_server:
1426
+ # Server path: token-level divergence using teacher logprobs.
1427
+ # The server returns:
1428
+ # actual_logprobs – (B, T) teacher log p(x_actual) (for reverse KL)
1429
+ # topk_logprobs – (B, T, K) teacher top-k sorted logprobs (for forward KL)
1430
+ # topk_token_ids – (B, T, K) corresponding token IDs
1431
+ teacher_result = self._get_teacher_token_logprobs_from_server(inputs, prompt_length)
1432
+
1433
+ student_logits = student_outputs.logits[:, prompt_length - 1 : -1, :]
1434
+ student_log_probs = F.log_softmax(student_logits / self.temperature, dim=-1)
1435
+
1436
+ comp_len = teacher_result["actual_logprobs"].shape[1]
1437
+ completion_tokens = completion_tokens[:, :comp_len]
1438
+ trimmed_labels = labels[:, :comp_len]
1439
+
1440
+ if self.beta > 0:
1441
+ loss = self._compute_server_sparse_top_1_divergence_loss(
1442
+ teacher_result=teacher_result,
1443
+ student_log_probs=student_log_probs[:, :comp_len, :],
1444
+ completion_tokens=completion_tokens,
1445
+ labels=trimmed_labels,
1446
+ )
1447
+ else:
1448
+ loss = self._compute_server_forward_kl_loss(
1449
+ teacher_result=teacher_result,
1450
+ student_log_probs=student_log_probs[:, :comp_len, :],
1451
+ labels=trimmed_labels,
1452
+ )
1453
+ else:
1454
+ # Local teacher: exact full-vocabulary loss except for the shared mixed top-1 path.
1455
+ teacher_logits = self._get_teacher_logits(inputs)
1456
+ student_logits = student_outputs.logits[:, prompt_length - 1 : -1, :]
1457
+ teacher_logits = teacher_logits[:, prompt_length - 1 : -1, :]
1458
+ if self.beta > 0 and self.loss_top_k == 1:
1459
+ loss = self._compute_local_sparse_top_1_divergence_loss(
1460
+ student_logits=student_logits,
1461
+ teacher_logits=teacher_logits,
1462
+ completion_tokens=completion_tokens,
1463
+ labels=labels,
1464
+ )
1465
+ else:
1466
+ loss = self.generalized_jsd_loss(
1467
+ student_logits=student_logits,
1468
+ teacher_logits=teacher_logits,
1469
+ labels=labels,
1470
+ beta=self.beta,
1471
+ temperature=self.temperature,
1472
+ top_k=self.loss_top_k,
1473
+ add_tail=self.loss_add_tail,
1474
+ )
1475
+
1476
+ return (loss, student_outputs) if return_outputs else loss
1477
+
1478
+ def _compute_liger_loss(self, model, inputs):
1479
+ """Memory-efficient JSD using Liger kernel (operates on hidden states, not full logits)."""
1480
+ unwrapped_student = self.accelerator.unwrap_model(model)
1481
+ if hasattr(unwrapped_student, "get_decoder") and unwrapped_student.get_decoder() is not None:
1482
+ base_student = unwrapped_student.get_decoder()
1483
+ else:
1484
+ base_student = getattr(
1485
+ unwrapped_student, getattr(unwrapped_student, "base_model_prefix", "model"), unwrapped_student
1486
+ )
1487
+
1488
+ student_outputs = base_student(
1489
+ input_ids=inputs["input_ids"],
1490
+ attention_mask=inputs["attention_mask"],
1491
+ use_cache=False,
1492
+ )
1493
+
1494
+ self.teacher_model.eval()
1495
+ unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model)
1496
+ if hasattr(unwrapped_teacher, "get_decoder") and unwrapped_teacher.get_decoder() is not None:
1497
+ base_teacher = unwrapped_teacher.get_decoder()
1498
+ else:
1499
+ base_teacher = getattr(
1500
+ unwrapped_teacher, getattr(unwrapped_teacher, "base_model_prefix", "model"), unwrapped_teacher
1501
+ )
1502
+ with torch.no_grad():
1503
+ teacher_outputs = base_teacher(
1504
+ input_ids=inputs["input_ids"],
1505
+ attention_mask=inputs["attention_mask"],
1506
+ use_cache=False,
1507
+ )
1508
+
1509
+ student_hidden = student_outputs.last_hidden_state[:, :-1]
1510
+ teacher_hidden = teacher_outputs.last_hidden_state[:, :-1]
1511
+ del student_outputs, teacher_outputs
1512
+
1513
+ student_hidden = student_hidden.reshape(-1, student_hidden.shape[-1])
1514
+ teacher_hidden = teacher_hidden.reshape(-1, teacher_hidden.shape[-1])
1515
+
1516
+ labels_mask = inputs["labels"] != -100
1517
+ masked_input_ids = torch.where(labels_mask, inputs["input_ids"], torch.full_like(inputs["input_ids"], -100))
1518
+ true_labels = masked_input_ids[:, 1:].contiguous().reshape(-1)
1519
+
1520
+ student_head = unwrapped_student.get_output_embeddings()
1521
+ teacher_head = unwrapped_teacher.get_output_embeddings()
1522
+
1523
+ loss = self.liger_jsd_loss(
1524
+ student_input=student_hidden,
1525
+ student_weight=student_head.weight,
1526
+ teacher_input=teacher_hidden,
1527
+ teacher_weight=teacher_head.weight,
1528
+ true_labels=true_labels,
1529
+ student_bias=getattr(student_head, "bias", None),
1530
+ teacher_bias=getattr(teacher_head, "bias", None),
1531
+ )
1532
+
1533
+ del student_hidden, teacher_hidden, true_labels
1534
+ return loss
1535
+
1536
+ def _get_liger_zero3_lm_head_gather_ctx(self, model: nn.Module):
1537
+ """Context manager for gathering lm_head parameters under Liger + ZeRO-3."""
1538
+ if not self.use_liger_loss:
1539
+ return nullcontext()
1540
+
1541
+ deepspeed_plugin = self.accelerator.state.deepspeed_plugin
1542
+ if deepspeed_plugin is None or deepspeed_plugin.zero_stage != 3:
1543
+ return nullcontext()
1544
+
1545
+ import deepspeed
1546
+
1547
+ unwrapped_student = self.accelerator.unwrap_model(model)
1548
+ unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model)
1549
+ student_head = unwrapped_student.get_output_embeddings()
1550
+ teacher_head = unwrapped_teacher.get_output_embeddings()
1551
+ params = [student_head.weight, teacher_head.weight]
1552
+ if student_head.bias is not None:
1553
+ params.append(student_head.bias)
1554
+ if teacher_head.bias is not None:
1555
+ params.append(teacher_head.bias)
1556
+ return deepspeed.zero.GatheredParameters(params, modifier_rank=None)
1557
+
1558
+ # ──────────────────────────────────────────────────────────────────────
1559
+ # Training step & Logging
1560
+ # ──────────────────────────────────────────────────────────────────────
1561
+
1562
+ @profiling_decorator
1563
+ def training_step(
1564
+ self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None
1565
+ ) -> torch.Tensor:
1566
+ """Training step with on/off-policy loss tracking and completion stats."""
1567
+ buffer_steps = self.args.gradient_accumulation_steps
1568
+
1569
+ with self._get_liger_zero3_lm_head_gather_ctx(model):
1570
+ loss = super().training_step(model, inputs, num_items_in_batch)
1571
+
1572
+ slice_idx = (self._buffer_step - 1) % buffer_steps
1573
+
1574
+ # Determine if this slice is on-policy
1575
+ is_on_policy = False
1576
+ if self._buffered_on_policy_flags is not None and slice_idx < len(self._buffered_on_policy_flags):
1577
+ is_on_policy = self._buffered_on_policy_flags[slice_idx]
1578
+
1579
+ # Track completion length stats — read from buffered inputs (which reflect on-policy generation)
1580
+ actual_inputs = self._buffered_inputs[slice_idx] if self._buffered_inputs is not None else inputs
1581
+ labels = actual_inputs.get("labels")
1582
+ if labels is not None:
1583
+ completion_lengths = (labels != -100).sum(dim=1).float()
1584
+ gathered_lengths = self.accelerator.gather(completion_lengths)
1585
+ mode = "train"
1586
+ prefix = "on_policy" if is_on_policy else "off_policy"
1587
+ self._metrics[mode][f"completions/{prefix}_mean_length"].append(gathered_lengths.mean().item())
1588
+ self._metrics[mode][f"completions/{prefix}_max_length"].append(gathered_lengths.max().item())
1589
+ self._metrics[mode][f"completions/{prefix}_min_length"].append(gathered_lengths.min().item())
1590
+
1591
+ # Log fraction of completions that hit max_completion_length (truncated)
1592
+ max_comp_len = getattr(self.generation_config, "max_new_tokens", None)
1593
+ if is_on_policy and max_comp_len is not None:
1594
+ truncated_frac = (gathered_lengths >= max_comp_len).float().mean().item()
1595
+ self._metrics[mode]["completions/truncated_fraction"].append(truncated_frac)
1596
+
1597
+ # Track loss per policy type
1598
+ loss_scalar = float(loss.detach())
1599
+ step_equiv = 1.0 / self.args.gradient_accumulation_steps
1600
+ if is_on_policy:
1601
+ self._on_policy_loss_total += loss_scalar
1602
+ self._on_policy_step_equiv += step_equiv
1603
+ else:
1604
+ self._off_policy_loss_total += loss_scalar
1605
+ self._off_policy_step_equiv += step_equiv
1606
+
1607
+ return loss
1608
+
1609
+ def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
1610
+ mode = "train" if self.model.training else "eval"
1611
+ metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()}
1612
+
1613
+ if mode == "train":
1614
+ # Aggregate on/off-policy losses across distributed processes
1615
+ device = self.accelerator.device if hasattr(self.accelerator, "device") else torch.device("cpu")
1616
+ vec = torch.tensor(
1617
+ [
1618
+ self._on_policy_loss_total,
1619
+ self._off_policy_loss_total,
1620
+ self._on_policy_step_equiv,
1621
+ self._off_policy_step_equiv,
1622
+ ],
1623
+ dtype=torch.float64,
1624
+ device=device,
1625
+ )
1626
+
1627
+ if (
1628
+ getattr(self.accelerator, "distributed_type", DistributedType.NO) != DistributedType.NO
1629
+ and dist.is_available()
1630
+ and dist.is_initialized()
1631
+ ):
1632
+ dist.all_reduce(vec, op=dist.ReduceOp.SUM)
1633
+
1634
+ on_sum, off_sum, on_eq, off_eq = vec.tolist()
1635
+ if on_eq > 0:
1636
+ logs["on_policy_loss"] = round(on_sum / on_eq, 4)
1637
+ if off_eq > 0:
1638
+ logs["off_policy_loss"] = round(off_sum / off_eq, 4)
1639
+
1640
+ self._on_policy_loss_total = self._off_policy_loss_total = 0.0
1641
+ self._on_policy_step_equiv = self._off_policy_step_equiv = 0.0
1642
+
1643
+ if mode == "eval":
1644
+ metrics = {f"eval_{key}": val for key, val in metrics.items()}
1645
+
1646
+ logs = {**logs, **metrics}
1647
+ super().log(logs, start_time)
1648
+ self._metrics[mode].clear()
1649
+
1650
+ # Log completions to console and wandb
1651
+ should_log_completions = (
1652
+ self.log_completions
1653
+ and self.state.global_step > 0
1654
+ and self.state.global_step % self.log_completions_steps == 0
1655
+ )
1656
+
1657
+ if should_log_completions and self.accelerator.is_main_process:
1658
+ prompts = list(self._textual_logs["prompt"])
1659
+ completions = list(self._textual_logs["completion"])
1660
+
1661
+ if prompts:
1662
+ _print_completions_sample(prompts, completions, self.state.global_step, self.num_completions_to_print)
1663
+
1664
+ # Log as a wandb Table
1665
+ if self.args.report_to and "wandb" in self.args.report_to:
1666
+ try:
1667
+ import wandb
1668
+
1669
+ if wandb.run is not None:
1670
+ import pandas as pd
1671
+
1672
+ table_data = {
1673
+ "step": [str(self.state.global_step)] * len(prompts),
1674
+ "prompt": prompts,
1675
+ "completion": completions,
1676
+ }
1677
+ df = pd.DataFrame(table_data)
1678
+ if self.num_completions_to_print and len(df) > self.num_completions_to_print:
1679
+ df = df.sample(n=self.num_completions_to_print, random_state=42)
1680
+ wandb.log({"completions": wandb.Table(dataframe=df)})
1681
+ except ImportError:
1682
+ pass
1683
+
1684
+ # Clear text logs on all processes after the logging interval
1685
+ if should_log_completions:
1686
+ self._textual_logs["prompt"].clear()
1687
+ self._textual_logs["completion"].clear()
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/dppo/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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
+
16
+ from .dppo_config import DPPOConfig
17
+ from .dppo_trainer import DPPOTrainer
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/dppo/dppo_config.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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, field
16
+ from typing import Literal
17
+
18
+ from ...trainer.grpo_config import GRPOConfig
19
+
20
+
21
+ @dataclass
22
+ class DPPOConfig(GRPOConfig):
23
+ """
24
+ Configuration class for DPPOTrainer.
25
+
26
+ DPPO (Divergence Proximal Policy Optimization) replaces PPO/GRPO's heuristic ratio-clipping with a principled trust
27
+ region based on direct policy divergence estimates.
28
+
29
+ Paper: "Rethinking the Trust Region in LLM Reinforcement Learning" (arXiv:2602.04879)
30
+
31
+ Args:
32
+ divergence_type (`Literal["binary_tv", "binary_kl", "topk_tv", "topk_kl"]`, *optional*, defaults to `"binary_tv"`):
33
+ Divergence approximation used for the trust-region mask. Binary variants use only per-token log-probs;
34
+ top-K variants require storing top-K token IDs and log-probs during rollout generation plus full logits
35
+ during training.
36
+
37
+ divergence_topk (`int`, *optional*, defaults to `20`):
38
+ K for top-K divergence approximations. Only used when `divergence_type` is `"topk_tv"` or `"topk_kl"`.
39
+
40
+ clip_ratio_c (`float`, *optional*, defaults to `20.0`):
41
+ Upper bound on the importance-sampling ratio for stability. The IS ratio is clamped to [0, clip_ratio_c].
42
+
43
+ epsilon (`float`, inherited from GRPOConfig, default overridden to `0.15`):
44
+ Divergence threshold δ_low. Tokens whose divergence exceeds this when the policy moves in the
45
+ advantage-decreasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL
46
+ divergence.
47
+
48
+ epsilon_high (`float`, inherited from GRPOConfig, default overridden to `0.15`):
49
+ Divergence threshold δ_high. Tokens whose divergence exceeds this when the policy moves in the
50
+ advantage-increasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL
51
+ divergence.
52
+ """
53
+
54
+ divergence_type: Literal["binary_tv", "binary_kl", "topk_tv", "topk_kl"] = field(
55
+ default="binary_tv",
56
+ metadata={
57
+ "help": "Divergence approximation used for the trust-region mask. Binary variants use only per-token "
58
+ "log-probs; top-K variants require storing top-K token IDs and log-probs during rollout generation plus "
59
+ "full logits during training."
60
+ },
61
+ )
62
+ divergence_topk: int = field(
63
+ default=20,
64
+ metadata={
65
+ "help": "K for top-K divergence approximations. Only used when `divergence_type` is `'topk_tv'` or "
66
+ "`'topk_kl'`."
67
+ },
68
+ )
69
+ clip_ratio_c: float = field(
70
+ default=20.0,
71
+ metadata={
72
+ "help": "Upper bound on the importance-sampling ratio for stability. The IS ratio is clamped to "
73
+ "[0, clip_ratio_c]."
74
+ },
75
+ )
76
+ epsilon: float = field(
77
+ default=0.15,
78
+ metadata={
79
+ "help": "Divergence threshold δ_low. Tokens whose divergence exceeds this when the policy moves in the "
80
+ "advantage-decreasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL "
81
+ "divergence."
82
+ },
83
+ )
84
+ epsilon_high: float = field(
85
+ default=0.15,
86
+ metadata={
87
+ "help": "Divergence threshold δ_high. Tokens whose divergence exceeds this when the policy moves in the "
88
+ "advantage-increasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL "
89
+ "divergence."
90
+ },
91
+ )
92
+
93
+ def __post_init__(self):
94
+ super().__post_init__()
95
+
96
+ if self.divergence_type not in ("binary_tv", "binary_kl", "topk_tv", "topk_kl"):
97
+ raise ValueError(
98
+ f"divergence_type must be one of 'binary_tv', 'binary_kl', 'topk_tv', 'topk_kl', "
99
+ f"got {self.divergence_type!r}"
100
+ )
101
+
102
+ if self.divergence_topk < 1:
103
+ raise ValueError(f"divergence_topk must be >= 1, got {self.divergence_topk}")
104
+
105
+ if self.clip_ratio_c <= 0:
106
+ raise ValueError(f"clip_ratio_c must be > 0, got {self.clip_ratio_c}")
107
+
108
+ if self.loss_type != "dapo":
109
+ raise ValueError(f"loss_type {self.loss_type} is not supported for DPPO")
110
+
111
+ if self.top_entropy_quantile != 1.0:
112
+ raise ValueError("top_entropy_quantile is not supported for DPPO")
113
+
114
+ if self.off_policy_mask_threshold is not None:
115
+ raise ValueError("off_policy_mask_threshold is not supported for DPPO")
116
+
117
+ if self.use_transformers_paged:
118
+ raise ValueError(
119
+ "DPPO requires sampled token logprobs from the generation backend. "
120
+ "Transformers paged (`use_transformers_paged=True`) does not support logprob extraction."
121
+ )
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/dppo/dppo_trainer.py ADDED
@@ -0,0 +1,1385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 asyncio
16
+ import copy
17
+ import math
18
+ import textwrap
19
+ from collections.abc import Callable
20
+ from contextlib import nullcontext
21
+ from copy import copy as shallow_copy
22
+ from typing import Any
23
+
24
+ import numpy as np
25
+ import torch
26
+ import transformers
27
+ from accelerate.utils import gather_object
28
+ from datasets import Dataset, IterableDataset
29
+ from packaging.version import Version
30
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
31
+ from transformers import (
32
+ PreTrainedModel,
33
+ PreTrainedTokenizerBase,
34
+ ProcessorMixin,
35
+ Trainer,
36
+ TrainerCallback,
37
+ )
38
+ from transformers.utils import is_peft_available
39
+
40
+ from ...chat_template_utils import parse_response
41
+ from ...data_utils import (
42
+ apply_chat_template,
43
+ is_conversational,
44
+ prepare_multimodal_messages,
45
+ )
46
+ from ...extras.profiling import profiling_context, profiling_decorator
47
+ from ...models import unwrap_model_for_generation
48
+ from ...models.utils import disable_gradient_checkpointing
49
+ from ...trainer.grpo_trainer import EnvironmentFactory, GRPOTrainer, RewardFunc, RolloutFunc
50
+ from ...trainer.utils import (
51
+ entropy_from_logits,
52
+ nanstd,
53
+ pad,
54
+ selective_log_softmax,
55
+ use_adapter,
56
+ )
57
+ from .dppo_config import DPPOConfig
58
+
59
+
60
+ if is_peft_available():
61
+ from peft import PeftConfig, PeftModel
62
+
63
+ SAFETY_CLAMP_MAX = 20
64
+
65
+
66
+ def _strip_padding(tensor: torch.Tensor, mask: torch.Tensor) -> list[list]:
67
+ """Remove padding from a batched tensor using a mask, returning a ragged list-of-lists."""
68
+ return [row[m].tolist() for row, m in zip(tensor, mask.bool(), strict=True)]
69
+
70
+
71
+ class DPPOTrainer(GRPOTrainer):
72
+ """
73
+ Trainer for Divergence Proximal Policy Optimization (DPPO).
74
+
75
+ DPPO replaces PPO/GRPO's heuristic ratio-clipping with a principled trust region based on direct policy divergence
76
+ estimates. PPO-style clipping masks tokens based on probability ratio π/μ, which over-penalizes low-probability
77
+ tokens and under-penalizes high-probability tokens. In contrast, DPPO masks based on direct approximation of policy
78
+ divergence (e.g TV or KL) ensuring updates stay within a theoretically grounded trust region.
79
+
80
+
81
+ Four divergence approximations are supported:
82
+ - `binary_tv`: Absolute probability difference |π(a) - μ(a)| (simplest)
83
+ - `binary_kl`: Bernoulli KL divergence between old and new token probabilities
84
+ - `topk_tv`: Total variation over the top-K tokens of the distribution
85
+ - `topk_kl`: KL divergence over the top-K tokens of the distribution
86
+
87
+ Args:
88
+ model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]):
89
+ Model to be trained. Can be either:
90
+
91
+ - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
92
+ path to a *directory* containing model weights saved using
93
+ [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
94
+ using `<ModelArchitecture>.from_pretrained` (where `<ModelArchitecture>` is derived from the model
95
+ config) with the keyword arguments in `args.model_init_kwargs`.
96
+ - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
97
+ - A [`~peft.PeftModel`] object. Only causal language models are supported.
98
+ reward_funcs (`RewardFunc | list[RewardFunc]`):
99
+ Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
100
+ functions with the prompts and completions and sum the rewards. Can be either:
101
+
102
+ - A single reward function, such as:
103
+ - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a
104
+ path to a *directory* containing model weights saved using
105
+ [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
106
+ using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the
107
+ keyword arguments in `args.model_init_kwargs`.
108
+ - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported.
109
+ - A custom reward function: The function is provided with the prompts and the generated completions,
110
+ plus any additional columns in the dataset. It should return a list of rewards. Custom reward
111
+ functions can be either synchronous or asynchronous and can also return `None` when the reward is
112
+ not applicable to those samples. This is useful for multi-task training where different reward
113
+ functions apply to different types of samples. When a reward function returns `None` for a sample,
114
+ that reward function is excluded from the reward calculation for that sample. For more details, see
115
+ [Using a custom reward
116
+ function](#using-a-custom-reward-function).
117
+
118
+ The trainer's state is also passed to the reward function. The trainer's state is an instance of
119
+ [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the
120
+ reward function's signature.
121
+ - A list of reward functions, where each item can independently be any of the above types. Mixing different
122
+ types within the list (e.g., a string model ID and a custom reward function) is allowed.
123
+ args ([`DPPOConfig`], *optional*):
124
+ Configuration for this trainer. If `None`, a default configuration is used.
125
+ train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
126
+ Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is
127
+ ignored. The format of the samples can be either:
128
+
129
+ - [Standard](dataset_formats#standard): Each sample contains plain text.
130
+ - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
131
+ and content).
132
+ eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
133
+ Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
134
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*):
135
+ Processing class used to process the data. The padding side must be set to "left". If `None`, the
136
+ processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A
137
+ padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token,
138
+ `tokenizer.eos_token` will be used as the default.
139
+ reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*):
140
+ Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:
141
+
142
+ - A single processing class: Used when `reward_funcs` contains only one reward function.
143
+ - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
144
+ If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is
145
+ `None`, the tokenizer for the model is automatically loaded using
146
+ [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward
147
+ functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes`
148
+ are ignored.
149
+ callbacks (list of [`~transformers.TrainerCallback`], *optional*):
150
+ List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
151
+ in [here](https://huggingface.co/docs/transformers/main_classes/callback).
152
+
153
+ If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
154
+ method.
155
+ optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`):
156
+ A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your
157
+ model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`.
158
+ peft_config ([`~peft.PeftConfig`], *optional*):
159
+ PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
160
+ tools (list of `Callable`, *optional*):
161
+ A list of callable tool functions (sync or async) that the model can invoke during generation. Each tool
162
+ should be a standard Python function with properly type-hinted arguments and return values, and a
163
+ Google-style docstring describing its purpose, arguments, and return value. For more details, see:
164
+ https://huggingface.co/docs/transformers/en/chat_extras#passing-tools. The model uses the function's name,
165
+ type hints, and docstring to determine how to call it. Ensure that the model's chat template supports tool
166
+ use and that it has been fine-tuned for tool calling.
167
+ rollout_func (`RolloutFunc`, *optional*):
168
+ Function to use for generating completions. It receives the list of prompts allocated to the current
169
+ process and the trainer instance. It must return a dict with `"prompt_ids"`, `"completion_ids"`, and
170
+ `"logprobs"` fields. Any other fields are forwarded to the reward functions. This feature is experimental
171
+ and may change or be removed at any time without prior notice.
172
+ """
173
+
174
+ _tag_names = ["trl", "dppo"]
175
+ _name = "DPPO"
176
+ _paper = {
177
+ "title": "Rethinking the Trust Region in LLM Reinforcement Learning",
178
+ "id": "2602.04879",
179
+ # docstyle-ignore
180
+ "citation": textwrap.dedent("""\
181
+ @article{qi2026rethinking,
182
+ title = {{Rethinking the Trust Region in LLM Reinforcement Learning}},
183
+ author = {Qi, Penghui and Zhou, Xiangxin and Liu, Zichen and Pang, Tianyu and Du, Chao and Lin, Min and Lee, Wee Sun},
184
+ journal = {arXiv preprint arXiv:2602.04879},
185
+ year = {2026}
186
+ }"""),
187
+ }
188
+
189
+ def __init__(
190
+ self,
191
+ model: "str | PreTrainedModel | PeftModel",
192
+ reward_funcs: RewardFunc | list[RewardFunc],
193
+ args: DPPOConfig | None = None,
194
+ train_dataset: Dataset | IterableDataset | None = None,
195
+ eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
196
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
197
+ reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None,
198
+ callbacks: list[TrainerCallback] | None = None,
199
+ optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
200
+ peft_config: "PeftConfig | None" = None,
201
+ tools: list[Callable] | None = None,
202
+ rollout_func: RolloutFunc | None = None,
203
+ environment_factory: EnvironmentFactory | None = None,
204
+ ):
205
+ if args is None:
206
+ model_name = model if isinstance(model, str) else model.config._name_or_path
207
+ model_name = model_name.split("/")[-1]
208
+ args = DPPOConfig(f"{model_name}-DPPO")
209
+
210
+ self.divergence_type = args.divergence_type
211
+ self.divergence_topk = args.divergence_topk
212
+ self.clip_ratio_c = args.clip_ratio_c
213
+
214
+ super().__init__(
215
+ model=model,
216
+ reward_funcs=reward_funcs,
217
+ args=args,
218
+ train_dataset=train_dataset,
219
+ eval_dataset=eval_dataset,
220
+ processing_class=processing_class,
221
+ reward_processing_classes=reward_processing_classes,
222
+ callbacks=callbacks,
223
+ optimizers=optimizers,
224
+ peft_config=peft_config,
225
+ tools=tools,
226
+ rollout_func=rollout_func,
227
+ environment_factory=environment_factory,
228
+ )
229
+
230
+ if self.divergence_type in ["topk_tv", "topk_kl"] and self.use_vllm:
231
+ self.vllm_generation.logprobs = self.divergence_topk
232
+
233
+ def _tokenize_prompts(self, prompts: list):
234
+ """Tokenize prompts and extract images/multimodal fields for generation."""
235
+ if is_conversational({"prompt": prompts[0]}):
236
+ images = []
237
+ has_images = False
238
+ for prompt in prompts:
239
+ prompt_images = []
240
+ for message in prompt:
241
+ if isinstance(message["content"], list):
242
+ for part in message["content"]:
243
+ if part["type"] == "image":
244
+ prompt_images.append(part["image"])
245
+ has_images = True
246
+ images.append(prompt_images if prompt_images else None)
247
+ images = images if has_images else None
248
+
249
+ # We pass padding=True to work around a bug introduced in transformers 5.2.0 in some processors
250
+ # (e.g. Qwen2.5-VL) that crash on batched unpadded input. We then unpad input_ids using attention_mask.
251
+ # See: https://github.com/huggingface/transformers/issues/44514
252
+ tokenized = self.processing_class.apply_chat_template(
253
+ conversation=prompts,
254
+ tools=self.tools or None, # `or None`: Llama bug: it renders tool boilerplate for tools=[]
255
+ chat_template=self.chat_template,
256
+ add_generation_prompt=True,
257
+ tokenize=True,
258
+ return_dict=True,
259
+ padding=True,
260
+ **self.chat_template_kwargs,
261
+ )
262
+ prompt_ids = [
263
+ [tok for tok, mask in zip(ids, attention_mask, strict=True) if mask]
264
+ for ids, attention_mask in zip(tokenized["input_ids"], tokenized["attention_mask"], strict=True)
265
+ ]
266
+ multimodal_fields = {k: v for k, v in tokenized.items() if k not in ("input_ids", "attention_mask")}
267
+ else:
268
+ prompt_ids = self.processing_class(text=prompts)["input_ids"]
269
+ images = None
270
+ multimodal_fields = {}
271
+ return prompt_ids, images, multimodal_fields
272
+
273
+ def _generate_single_turn(self, prompt_ids, images, multimodal_fields):
274
+ """Generate completions, always extracting sampled token logprobs.
275
+
276
+ Returns:
277
+ 5-tuple of (prompt_ids, completion_ids, logprobs, topk_logprobs, topk_token_ids). topk_logprobs and
278
+ topk_token_ids are None when divergence_type is not topk.
279
+ """
280
+ device = self.accelerator.device
281
+ mode = "train" if self.model.training else "eval"
282
+ needs_topk = self.divergence_type in ["topk_tv", "topk_kl"]
283
+ K = self.divergence_topk
284
+
285
+ if self.use_vllm:
286
+ if self.state.global_step != self._last_loaded_step:
287
+ with profiling_context(self, "sync_weights"):
288
+ self.vllm_generation.sync_weights()
289
+ self._last_loaded_step = self.state.global_step
290
+
291
+ num_generations = self.num_generations if mode == "train" else self.num_generations_eval
292
+ prompt_ids, completion_ids, logprobs, logprob_token_ids = self.vllm_generation.generate(
293
+ prompts=prompt_ids,
294
+ images=images,
295
+ num_generations=num_generations,
296
+ profiler=profiling_context(self, "vLLM.generate"),
297
+ )
298
+
299
+ if needs_topk:
300
+ # vLLM returns up to K+1 entries sorted by rank (most probable first).
301
+ # The sampled token is always included but may be at any position.
302
+ # Per the paper, A'_t = TopK(μ, K) ∪ {a_t}. We keep exactly K slots: if the
303
+ # sampled token a_t is not in the top-K, it replaces the K-th ranked entry.
304
+ topk_logprobs = []
305
+ topk_token_ids = []
306
+ sampled_logprobs = []
307
+ for seq_lps, seq_tids, seq_cids in zip(logprobs, logprob_token_ids, completion_ids, strict=True):
308
+ seq_topk_lps, seq_topk_tids, seq_sampled = [], [], []
309
+ for step_lps, step_tids, sampled_tid in zip(seq_lps, seq_tids, seq_cids, strict=True):
310
+ idx = step_tids.index(sampled_tid)
311
+ seq_sampled.append(step_lps[idx])
312
+ # Take top-K entries, then ensure sampled token is present
313
+ tk_lps = step_lps[:K]
314
+ tk_tids = step_tids[:K]
315
+ if sampled_tid not in tk_tids:
316
+ tk_lps[-1] = step_lps[idx]
317
+ tk_tids[-1] = sampled_tid
318
+ seq_topk_lps.append(tk_lps)
319
+ seq_topk_tids.append(tk_tids)
320
+ topk_logprobs.append(seq_topk_lps)
321
+ topk_token_ids.append(seq_topk_tids)
322
+ sampled_logprobs.append(seq_sampled)
323
+ else:
324
+ sampled_logprobs = [[step_lps[0] for step_lps in seq_lps] for seq_lps in logprobs]
325
+ topk_logprobs = None
326
+ topk_token_ids = None
327
+
328
+ return prompt_ids, completion_ids, sampled_logprobs, topk_logprobs, topk_token_ids
329
+ else:
330
+ prompt_tensors = [torch.tensor(ids) for ids in prompt_ids]
331
+ padded_ids = pad(prompt_tensors, padding_value=self.pad_token_id, padding_side="left")
332
+ attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left")
333
+ generate_inputs = {"input_ids": padded_ids, "attention_mask": attention_mask}
334
+ for key, value in multimodal_fields.items():
335
+ if isinstance(value, torch.Tensor):
336
+ generate_inputs[key] = value
337
+ elif isinstance(value, list) and value and isinstance(value[0], list):
338
+ generate_inputs[key] = pad([torch.tensor(x) for x in value], padding_value=0, padding_side="left")
339
+ else:
340
+ generate_inputs[key] = torch.tensor(np.array(value))
341
+ generate_inputs = Trainer._prepare_inputs(self, generate_inputs)
342
+
343
+ gen_config = shallow_copy(self.generation_config)
344
+ gen_config.output_logits = True
345
+ gen_config.return_dict_in_generate = True
346
+
347
+ with (
348
+ profiling_context(self, "transformers.generate"),
349
+ unwrap_model_for_generation(
350
+ self.model_wrapped,
351
+ self.accelerator,
352
+ gather_deepspeed3_params=self.args.ds3_gather_for_generation,
353
+ generation_kwargs=self.generation_kwargs,
354
+ ) as unwrapped_model,
355
+ torch.no_grad(),
356
+ FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(),
357
+ ):
358
+ gen_output = unwrapped_model.generate(**generate_inputs, generation_config=gen_config)
359
+
360
+ prompt_ids_tensor, prompt_mask = generate_inputs["input_ids"], generate_inputs["attention_mask"]
361
+ prompt_length = prompt_ids_tensor.size(1)
362
+ completion_ids = gen_output.sequences[:, prompt_length:]
363
+
364
+ sampled_chunks = []
365
+ topk_logps_chunks = [] if needs_topk else None
366
+ topk_ids_chunks = [] if needs_topk else None
367
+
368
+ for t, logits_t in enumerate(gen_output.logits):
369
+ # logits_t: (B, V)
370
+ logits_t = logits_t / self.temperature
371
+
372
+ # exact sampled-token logprob without allocating (B, V) log_softmax output
373
+ logZ_t = torch.logsumexp(logits_t, dim=-1, keepdim=True)
374
+ sampled_ids_t = completion_ids[:, t : t + 1]
375
+ sampled_lp_t = logits_t.gather(-1, sampled_ids_t) - logZ_t
376
+ sampled_chunks.append(sampled_lp_t.cpu())
377
+
378
+ if needs_topk:
379
+ topk_logits_t, topk_ids_t = torch.topk(logits_t, k=K, dim=-1) # (B, K), (B, K)
380
+ topk_lp_t = topk_logits_t - logZ_t
381
+
382
+ # Ensure sampled token is included in A'_t = TopK ∪ {a_t}
383
+ missing = ~(topk_ids_t == sampled_ids_t).any(dim=-1)
384
+ if missing.any():
385
+ topk_ids_t = topk_ids_t.clone()
386
+ topk_lp_t = topk_lp_t.clone()
387
+ topk_ids_t[missing, -1] = sampled_ids_t[missing, 0]
388
+ topk_lp_t[missing, -1] = sampled_lp_t[missing, 0]
389
+
390
+ topk_ids_chunks.append(topk_ids_t.cpu())
391
+ topk_logps_chunks.append(topk_lp_t.cpu())
392
+
393
+ # Mask everything after the first EOS token
394
+ is_eos = completion_ids == self.eos_token_id
395
+ has_eos = is_eos.any(dim=1)
396
+ eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device)
397
+ eos_idx[has_eos] = is_eos.int().argmax(dim=1)[has_eos]
398
+ sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1)
399
+ completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int()
400
+ prompt_mask_cpu = prompt_mask.bool().cpu()
401
+ completion_mask_cpu = completion_mask.bool().cpu()
402
+
403
+ prompt_ids_out = _strip_padding(prompt_ids_tensor.cpu(), prompt_mask_cpu)
404
+ completion_ids_out = _strip_padding(completion_ids.cpu(), completion_mask_cpu)
405
+ logprobs_out = _strip_padding(torch.cat(sampled_chunks, dim=1), completion_mask_cpu)
406
+ if needs_topk:
407
+ topk_logprobs = _strip_padding(torch.stack(topk_logps_chunks, dim=1), completion_mask_cpu)
408
+ topk_token_ids = _strip_padding(torch.stack(topk_ids_chunks, dim=1), completion_mask_cpu)
409
+ else:
410
+ topk_logprobs = None
411
+ topk_token_ids = None
412
+
413
+ return prompt_ids_out, completion_ids_out, logprobs_out, topk_logprobs, topk_token_ids
414
+
415
+ def _tool_call_loop(
416
+ self, prompts, prompt_ids, completion_ids, completions, logprobs, topk_logprobs, topk_token_ids
417
+ ):
418
+ """Tool execution loop that also threads top-K logprob data alongside logprobs.
419
+
420
+ Mirrors GRPOTrainer._tool_call_loop but additionally concatenates topk_logprobs and topk_token_ids the same way
421
+ logprobs is concatenated: real data for model-generated tokens, zero-padding for tool-result tokens. When topk
422
+ data is None (binary divergence), behaves identically to the parent.
423
+ """
424
+ K = self.divergence_topk
425
+ has_topk = topk_logprobs is not None
426
+
427
+ tool_calls = [completion[0].get("tool_calls") for completion in completions]
428
+ idxs_with_tool = [idx for idx, tool_call in enumerate(tool_calls) if tool_call]
429
+ tool_calls = [tool_calls[idx] for idx in idxs_with_tool]
430
+ tool_mask = [[1] * len(ids) for ids in completion_ids]
431
+ tool_call_count = 0
432
+ tool_failure_count = 0
433
+ iteration_num = 0
434
+ while idxs_with_tool and iteration_num < self.max_tool_calling_iterations:
435
+ prompt_completion_tools = [prompts[i] for i in idxs_with_tool]
436
+
437
+ for idx in range(len(idxs_with_tool)):
438
+ idx_with_tool = idxs_with_tool[idx]
439
+ tool_call_list = tool_calls[idx]
440
+ prompt_completion_tool = prompt_completion_tools[idx]
441
+ sync_tool_dict = self._sync_tool_dicts[idx_with_tool]
442
+ async_tool_dict = self._async_tool_dicts[idx_with_tool]
443
+ prompt_completion_tool.append(completions[idx_with_tool][-1])
444
+ async_coros = []
445
+ tool_call_results = []
446
+ for tool_call in tool_call_list:
447
+ tool_call_count += 1
448
+ if tool_call["type"] == "function":
449
+ function = tool_call["function"]
450
+ name = function["name"]
451
+ try:
452
+ if name in sync_tool_dict:
453
+ tool_call_results.append((name, sync_tool_dict[name](**function["arguments"])))
454
+ elif name in async_tool_dict:
455
+ async_coros.append((name, async_tool_dict[name](**function["arguments"])))
456
+ else:
457
+ raise ValueError(f"Tool {name} not found.")
458
+ except Exception as err:
459
+ tool_failure_count += 1
460
+ tool_call_results.append((name, {"error": str(err)}))
461
+ else:
462
+ tool_failure_count += 1
463
+ name = tool_call.get("name", "unknown")
464
+ tool_call_results.append((name, {"error": f"Unsupported tool call type: {tool_call['type']}"}))
465
+
466
+ if async_coros:
467
+
468
+ async def _run_async_tools(async_coros):
469
+ coros = [coro for _, coro in async_coros]
470
+ results = await asyncio.gather(*coros, return_exceptions=True)
471
+ return [(name, result) for (name, _), result in zip(async_coros, results, strict=False)]
472
+
473
+ async_results = asyncio.run_coroutine_threadsafe(
474
+ _run_async_tools(async_coros), self.async_loop
475
+ ).result()
476
+
477
+ for name, result in async_results:
478
+ if isinstance(result, Exception):
479
+ tool_failure_count += 1
480
+ tool_call_results.append((name, {"error": str(result)}))
481
+ else:
482
+ tool_call_results.append((name, result))
483
+
484
+ for name, result in tool_call_results:
485
+ tool_message = {"role": "tool", "name": name, "content": str(result)}
486
+ prompt_completion_tool.append(tool_message)
487
+ completions[idx_with_tool].append(tool_message)
488
+
489
+ # Tokenize and filter samples whose length exceeds max allowed length
490
+ pct_ids = self.processing_class.apply_chat_template(
491
+ prompt_completion_tools,
492
+ tools=self.tools or None, # `or None`: Llama bug: it renders tool boilerplate for tools=[]
493
+ chat_template=self.chat_template,
494
+ add_generation_prompt=True,
495
+ tokenize=True,
496
+ return_dict=False,
497
+ **self.chat_template_kwargs,
498
+ )
499
+ if self.use_vllm and self.vllm_mode == "colocate":
500
+ max_model_len = self.vllm_generation.llm.llm_engine.model_config.max_model_len
501
+ elif not self.use_vllm:
502
+ max_model_len = self.model.config.max_position_embeddings
503
+ else:
504
+ raise NotImplementedError(
505
+ f"Unsupported mode detected: use_vllm={self.use_vllm}, vllm_mode={self.vllm_mode}"
506
+ )
507
+ overlong = [len(pct) >= max_model_len for pct in pct_ids]
508
+ for idx in range(len(idxs_with_tool)):
509
+ idx_with_tool = idxs_with_tool[idx]
510
+ if overlong[idx]:
511
+ prompt_length = len(prompt_ids[idx_with_tool])
512
+ ct = pct_ids[idx][prompt_length : prompt_length + self.max_completion_length]
513
+ completion_ids[idx_with_tool] = ct
514
+ tool_mask[idx_with_tool] += [1] * (len(ct) - len(tool_mask[idx_with_tool]))
515
+ if logprobs is not None:
516
+ logprobs[idx_with_tool] += [0.0] * (len(ct) - len(logprobs[idx_with_tool]))
517
+ if has_topk:
518
+ topk_logprobs[idx_with_tool] += [[0.0] * K] * (len(ct) - len(topk_logprobs[idx_with_tool]))
519
+ topk_token_ids[idx_with_tool] += [[0] * K] * (len(ct) - len(topk_token_ids[idx_with_tool]))
520
+
521
+ idxs_with_tool = [idx for idx, o in zip(idxs_with_tool, overlong, strict=True) if not o]
522
+ prompt_completion_tools = [pct for pct, o in zip(prompt_completion_tools, overlong, strict=True) if not o]
523
+ if not idxs_with_tool:
524
+ break
525
+
526
+ # Generate new completions after tool execution
527
+ pct_prompt_ids, pct_images, pct_multimodal_fields = self._tokenize_prompts(prompt_completion_tools)
528
+ (
529
+ prompt_completion_tool_ids,
530
+ post_tool_ids,
531
+ post_tool_logprobs,
532
+ post_tool_topk_logprobs,
533
+ post_tool_topk_token_ids,
534
+ ) = self._generate_single_turn(pct_prompt_ids, pct_images, pct_multimodal_fields)
535
+
536
+ # Sanity check: chat template must be prefix-preserving
537
+ for idx in range(len(idxs_with_tool)):
538
+ idx_with_tool = idxs_with_tool[idx]
539
+ pct = prompt_completion_tool_ids[idx]
540
+ if prompt_ids[idx_with_tool] != pct[: len(prompt_ids[idx_with_tool])]:
541
+ raise ValueError(
542
+ "The chat template is not prefix-preserving. Please update it to use a prefix-preserving "
543
+ "format."
544
+ )
545
+
546
+ # Truncate so that pct[len(prompt_ids[idx]):] + post_tool does not exceed max_completion_length
547
+ for idx in range(len(idxs_with_tool)):
548
+ idx_with_tool = idxs_with_tool[idx]
549
+ prompt_len = len(prompt_ids[idx_with_tool])
550
+ completion_tool_ids = prompt_completion_tool_ids[idx][prompt_len:]
551
+ excess_length = len(completion_tool_ids) + len(post_tool_ids[idx]) - self.max_completion_length
552
+ if excess_length > 0:
553
+ post_tool_ids[idx] = post_tool_ids[idx][:-excess_length]
554
+ if logprobs is not None:
555
+ post_tool_logprobs[idx] = post_tool_logprobs[idx][:-excess_length]
556
+ if has_topk and post_tool_topk_logprobs is not None:
557
+ post_tool_topk_logprobs[idx] = post_tool_topk_logprobs[idx][:-excess_length]
558
+ post_tool_topk_token_ids[idx] = post_tool_topk_token_ids[idx][:-excess_length]
559
+ excess_length = len(completion_tool_ids) + len(post_tool_ids[idx]) - self.max_completion_length
560
+ if excess_length > 0:
561
+ prompt_completion_tool_ids[idx] = prompt_completion_tool_ids[idx][:-excess_length]
562
+
563
+ # Update tool_mask and logprobs: tool result tokens get 0/0.0, post-tool model tokens get 1/real values
564
+ for idx in range(len(idxs_with_tool)):
565
+ idx_with_tool = idxs_with_tool[idx]
566
+ prompt_completion_tool_length = len(prompt_completion_tool_ids[idx])
567
+ prompt_length = len(prompt_ids[idx_with_tool])
568
+ completion_length = len(completion_ids[idx_with_tool])
569
+ post_tool_length = len(post_tool_ids[idx])
570
+ tool_length = prompt_completion_tool_length - prompt_length - completion_length
571
+ tool_mask[idx_with_tool] += [0] * tool_length + [1] * post_tool_length
572
+ if logprobs is not None:
573
+ logprobs[idx_with_tool] += [0.0] * tool_length + post_tool_logprobs[idx]
574
+ if has_topk:
575
+ topk_pad = [[0.0] * K] * tool_length
576
+ tid_pad = [[0] * K] * tool_length
577
+ post_topk_lp = post_tool_topk_logprobs[idx] if post_tool_topk_logprobs is not None else []
578
+ post_topk_tid = post_tool_topk_token_ids[idx] if post_tool_topk_token_ids is not None else []
579
+ topk_logprobs[idx_with_tool] += topk_pad + post_topk_lp
580
+ topk_token_ids[idx_with_tool] += tid_pad + post_topk_tid
581
+
582
+ # Update completion_ids with the new completions (after tool execution)
583
+ for idx in range(len(idxs_with_tool)):
584
+ idx_with_tool = idxs_with_tool[idx]
585
+ prompt_length = len(prompt_ids[idx_with_tool])
586
+ pct = prompt_completion_tool_ids[idx]
587
+ completion_ids[idx_with_tool] = pct[prompt_length:] + post_tool_ids[idx]
588
+
589
+ # Decode post-tool completions
590
+ post_tool_completions = [
591
+ parse_response(self.processing_class, ids) if ids else {} for ids in post_tool_ids
592
+ ]
593
+
594
+ for idx in range(len(idxs_with_tool)):
595
+ idx_with_tool = idxs_with_tool[idx]
596
+ if post_tool_completions[idx]:
597
+ completions[idx_with_tool].append(post_tool_completions[idx])
598
+
599
+ # Check for further tool calls
600
+ tool_calls = [completion.get("tool_calls") for completion in post_tool_completions]
601
+ idxs_with_tool = [idx for idx, tool_call in zip(idxs_with_tool, tool_calls, strict=True) if tool_call]
602
+ tool_calls = [tool_call for tool_call in tool_calls if tool_call]
603
+ iteration_num += 1
604
+
605
+ return (
606
+ tool_mask,
607
+ completions,
608
+ completion_ids,
609
+ logprobs,
610
+ topk_logprobs,
611
+ topk_token_ids,
612
+ tool_call_count,
613
+ tool_failure_count,
614
+ )
615
+
616
+ def _generate(self, prompts: list):
617
+ """Generate completions, handling tool calls, and thread top-K logprob data through the full pipeline.
618
+
619
+ Returns:
620
+ 9-tuple of (prompt_ids, completion_ids, tool_mask, completions, total_completion_tokens, logprobs,
621
+ topk_logprobs, topk_token_ids, extra_fields).
622
+ """
623
+ device = self.accelerator.device
624
+ mode = "train" if self.model.training else "eval"
625
+ needs_topk = self.divergence_type in ["topk_tv", "topk_kl"]
626
+
627
+ # Copy the prompts to avoid modifying the original list
628
+ prompts = copy.deepcopy(prompts)
629
+
630
+ if self.rollout_func is not None:
631
+ # Keep vLLM weights in sync for custom rollouts that rely on vLLM utilities.
632
+ if self.use_vllm and self.state.global_step != self._last_loaded_step:
633
+ with profiling_context(self, "sync_weights"):
634
+ self.vllm_generation.sync_weights()
635
+ self._last_loaded_step = self.state.global_step
636
+
637
+ # Pass prompts to rollout_func preserving structured messages.
638
+ # Chat templating must happen inside rollout_func, at the backend boundary, so that
639
+ # multimodal content (images, typed content blocks) is not lost before rollout logic runs.
640
+ output = self.rollout_func(prompts, self)
641
+ required_keys = {"prompt_ids", "completion_ids", "logprobs"}
642
+ missing_keys = required_keys - output.keys()
643
+ if missing_keys:
644
+ missing_keys_list = sorted(missing_keys)
645
+ raise ValueError(f"rollout_func must return keys {missing_keys_list} in its output dict.")
646
+ extra_fields = {k: v for k, v in output.items() if k not in required_keys}
647
+ prompt_ids = output["prompt_ids"]
648
+ completion_ids = output["completion_ids"]
649
+ logprobs = output["logprobs"]
650
+ topk_logprobs = extra_fields.pop("topk_logprobs", None)
651
+ topk_token_ids = extra_fields.pop("topk_token_ids", None)
652
+ if needs_topk and (topk_logprobs is None or topk_token_ids is None):
653
+ raise ValueError(
654
+ "rollout_func must return keys ['topk_logprobs', 'topk_token_ids'] when divergence_type is "
655
+ f"{self.divergence_type!r}."
656
+ )
657
+ else:
658
+ prompt_ids, images, multimodal_fields = self._tokenize_prompts(prompts)
659
+ prompt_ids, completion_ids, logprobs, topk_logprobs, topk_token_ids = self._generate_single_turn(
660
+ prompt_ids, images, multimodal_fields
661
+ )
662
+ extra_fields = {}
663
+
664
+ # Decode completions. It's important to use `parse_response` when possible, because it handles tool calls.
665
+ if is_conversational({"prompt": prompts[0]}):
666
+ if (
667
+ Version(transformers.__version__) >= Version("5.0.0") # parse_response added in v5
668
+ and isinstance(self.processing_class, PreTrainedTokenizerBase) # doesn't work with processors
669
+ and hasattr(self.processing_class, "response_schema") # attribute not set by default for now
670
+ and self.processing_class.response_schema is not None # only works if the tokenizer has a schema
671
+ ):
672
+ completions = [[parse_response(self.processing_class, ids)] for ids in completion_ids]
673
+ else:
674
+ contents = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
675
+ completions = [[{"role": "assistant", "content": content}] for content in contents]
676
+ else:
677
+ completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
678
+
679
+ # Extract tool calls from the completions and (possibly) execute them
680
+ if self.tools:
681
+ (
682
+ tool_mask,
683
+ completions,
684
+ completion_ids,
685
+ logprobs,
686
+ topk_logprobs,
687
+ topk_token_ids,
688
+ tool_call_count,
689
+ tool_failure_count,
690
+ ) = self._tool_call_loop(
691
+ prompts, prompt_ids, completion_ids, completions, logprobs, topk_logprobs, topk_token_ids
692
+ )
693
+ else:
694
+ tool_mask = extra_fields.pop("env_mask", None)
695
+
696
+ # Get completion length per sequence, used for logging
697
+ prompt_lengths = torch.tensor([len(ids) for ids in prompt_ids], device=device)
698
+ if tool_mask is not None:
699
+ completion_lengths = torch.tensor([sum(mask) for mask in tool_mask], device=device)
700
+ else:
701
+ completion_lengths = torch.tensor([len(ids) for ids in completion_ids], device=device)
702
+ agg_prompt_lengths = self.accelerator.gather(prompt_lengths)
703
+ agg_completion_lengths = self.accelerator.gather(completion_lengths)
704
+ total_prompt_tokens = agg_prompt_lengths.sum()
705
+ total_completion_tokens = agg_completion_lengths.sum()
706
+
707
+ if mode == "train":
708
+ self.state.num_input_tokens_seen += (total_prompt_tokens + total_completion_tokens).item()
709
+ self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen]
710
+
711
+ self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item())
712
+ self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item())
713
+ self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item())
714
+
715
+ eos_and_pad = [self.eos_token_id, self.pad_token_id]
716
+ is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids], device=device)
717
+ agg_is_truncated = self.accelerator.gather(is_truncated)
718
+ self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item())
719
+ term_completion_lengths = agg_completion_lengths[~agg_is_truncated]
720
+ if len(term_completion_lengths) == 0:
721
+ term_completion_lengths = torch.zeros(1, device=device)
722
+ self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item())
723
+ self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item())
724
+ self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item())
725
+
726
+ if self.tools:
727
+ agg_tool_call_count = self.accelerator.gather(torch.tensor(tool_call_count, device=device)).sum()
728
+ tool_call_frequency = (agg_tool_call_count / len(agg_prompt_lengths)).item()
729
+ self._metrics[mode]["tools/call_frequency"].append(tool_call_frequency)
730
+ agg_tool_failure_count = self.accelerator.gather(torch.tensor(tool_failure_count, device=device)).sum()
731
+ failure_frequency = (
732
+ (agg_tool_failure_count / agg_tool_call_count).item() if agg_tool_call_count > 0 else 0.0
733
+ )
734
+ self._metrics[mode]["tools/failure_frequency"].append(failure_frequency)
735
+
736
+ return (
737
+ prompt_ids,
738
+ completion_ids,
739
+ tool_mask,
740
+ completions,
741
+ total_completion_tokens,
742
+ logprobs,
743
+ topk_logprobs,
744
+ topk_token_ids,
745
+ extra_fields,
746
+ )
747
+
748
+ @profiling_decorator
749
+ def _get_per_token_logps_with_topk(
750
+ self,
751
+ model,
752
+ input_ids,
753
+ attention_mask,
754
+ logits_to_keep,
755
+ topk_token_ids,
756
+ batch_size=None,
757
+ compute_entropy=False,
758
+ pixel_values=None,
759
+ image_grid_thw=None,
760
+ num_images=None,
761
+ pixel_attention_mask=None,
762
+ image_sizes=None,
763
+ token_type_ids=None,
764
+ mm_token_type_ids=None,
765
+ ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor]:
766
+ """Compute per-token log-probs, (optionally) entropies, and top-K log-probs in one forward pass.
767
+
768
+ Evaluates the current policy's log-probs at the rollout's top-K token IDs from the same forward pass used for
769
+ per_token_logps, avoiding an extra model call.
770
+
771
+ Args:
772
+ topk_token_ids: Rollout policy's top-K token IDs, shape (B, T, K). The current policy's
773
+ log-probs are evaluated at these positions.
774
+
775
+ Returns:
776
+ Tuple of (per_token_logps, entropies, current_topk_logps).
777
+ """
778
+ batch_size = batch_size or input_ids.size(0)
779
+ all_logps = []
780
+ all_entropies = []
781
+ all_topk_logps = []
782
+
783
+ for start in range(0, input_ids.size(0), batch_size):
784
+ end = start + batch_size
785
+ input_ids_batch = input_ids[start:end]
786
+ attention_mask_batch = attention_mask[start:end]
787
+
788
+ model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch}
789
+ if image_grid_thw is not None and pixel_values is not None:
790
+ rows_per_image = image_grid_thw.prod(dim=-1)
791
+ rows_per_sample = torch.split(rows_per_image, num_images)
792
+ rows_per_sample = torch.stack([s.sum() for s in rows_per_sample])
793
+ cum_rows = torch.cat([torch.tensor([0], device=rows_per_sample.device), rows_per_sample.cumsum(0)])
794
+ row_start, row_end = cum_rows[start].item(), cum_rows[end].item()
795
+ model_inputs["pixel_values"] = pixel_values[row_start:row_end]
796
+ cum_imgs = torch.tensor([0] + num_images).cumsum(0)
797
+ img_start, img_end = cum_imgs[start], cum_imgs[end]
798
+ model_inputs["image_grid_thw"] = image_grid_thw[img_start:img_end]
799
+ elif pixel_values is not None:
800
+ model_inputs["pixel_values"] = pixel_values[start:end]
801
+ if pixel_attention_mask is not None:
802
+ model_inputs["pixel_attention_mask"] = pixel_attention_mask[start:end]
803
+ if image_sizes is not None:
804
+ model_inputs["image_sizes"] = image_sizes[start:end]
805
+ if token_type_ids is not None:
806
+ model_inputs["token_type_ids"] = token_type_ids[start:end]
807
+ if mm_token_type_ids is not None:
808
+ model_inputs["mm_token_type_ids"] = mm_token_type_ids[start:end]
809
+
810
+ if "logits_to_keep" in self.model_kwarg_keys:
811
+ model_inputs["logits_to_keep"] = logits_to_keep + 1
812
+
813
+ model_inputs["use_cache"] = False
814
+
815
+ logits = model(**model_inputs).logits
816
+ logits = logits[:, :-1, :]
817
+ logits = logits[:, -logits_to_keep:, :]
818
+ logits = logits / self.temperature
819
+
820
+ completion_ids = input_ids_batch[:, -logits_to_keep:]
821
+ logps = selective_log_softmax(logits, completion_ids)
822
+ all_logps.append(logps)
823
+
824
+ if compute_entropy:
825
+ with torch.no_grad():
826
+ entropies = entropy_from_logits(logits)
827
+ all_entropies.append(entropies)
828
+
829
+ with torch.no_grad():
830
+ topk_logps = selective_log_softmax(logits, topk_token_ids[start:end])
831
+ all_topk_logps.append(topk_logps)
832
+
833
+ logps = torch.cat(all_logps, dim=0)
834
+ entropies = torch.cat(all_entropies, dim=0) if compute_entropy else None
835
+ topk_logps = torch.cat(all_topk_logps, dim=0)
836
+ return logps, entropies, topk_logps
837
+
838
+ def _generate_and_score_completions(
839
+ self, inputs: list[dict[str, torch.Tensor | Any]]
840
+ ) -> dict[str, torch.Tensor | Any]:
841
+ device = self.accelerator.device
842
+ mode = "train" if self.model.training else "eval"
843
+
844
+ prompts = [x["prompt"] for x in inputs]
845
+
846
+ if self.environments:
847
+ for prompt, environment, reset_kwargs in zip(prompts, self.environments, inputs, strict=True):
848
+ observation = environment.reset(**reset_kwargs)
849
+ if observation is None:
850
+ continue
851
+ prompt[-1]["content"] += observation
852
+
853
+ if "images" in inputs[0]:
854
+ images = [example.get("images") for example in inputs]
855
+ elif "image" in inputs[0]:
856
+ images = [[example.get("image")] if example.get("image") is not None else None for example in inputs]
857
+ else:
858
+ images = None
859
+ # Transformers requires at least one image in the batch, otherwise it throws an error
860
+ if images is not None and all(img_list == [] for img_list in images):
861
+ images = None
862
+
863
+ # If the prompts are conversational and the inputs contain images, we need to convert the prompts from
864
+ # [{"role": "user", "content": "What color is the sky?"}] to
865
+ # [{"role": "user", "content": [{"type": "image", "image": <Image>}, {"type": "text", "text": "What color is the sky?"}]}]
866
+ if images is not None:
867
+ if not is_conversational(inputs[0]):
868
+ raise ValueError(
869
+ "Multimodal training requires conversational prompts. It looks like the dataset contains "
870
+ "non-conversational inputs, likely because a chat template was applied before passing the dataset "
871
+ "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat "
872
+ "template internally."
873
+ )
874
+ prompts = [
875
+ prepare_multimodal_messages(prompt, images=image_list)
876
+ for prompt, image_list in zip(prompts, images, strict=True)
877
+ ]
878
+
879
+ (
880
+ prompt_ids_list,
881
+ completion_ids_list,
882
+ tool_mask_list,
883
+ completions,
884
+ num_items_in_batch,
885
+ sampling_per_token_logps_list,
886
+ topk_logprobs_list,
887
+ topk_token_ids_list,
888
+ extra_fields,
889
+ ) = self._generate(prompts)
890
+
891
+ # Convert lists of token IDs to padded tensors
892
+ prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list]
893
+ prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids]
894
+ prompt_ids = pad(
895
+ prompt_ids,
896
+ padding_value=self.pad_token_id,
897
+ padding_side="left",
898
+ pad_to_multiple_of=self.pad_to_multiple_of,
899
+ ).to(device=device)
900
+ prompt_mask = pad(
901
+ prompt_mask, padding_value=0, padding_side="left", pad_to_multiple_of=self.pad_to_multiple_of
902
+ ).to(device=device)
903
+ completion_ids = [torch.tensor(ids) for ids in completion_ids_list]
904
+ completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids]
905
+ completion_ids = pad(
906
+ completion_ids,
907
+ padding_value=self.pad_token_id,
908
+ padding_side="right",
909
+ pad_to_multiple_of=self.pad_to_multiple_of,
910
+ ).to(device=device)
911
+ completion_mask = pad(
912
+ completion_mask, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of
913
+ ).to(device=device)
914
+ sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list]
915
+ sampling_per_token_logps = pad(
916
+ sampling_per_token_logps,
917
+ padding_value=0.0,
918
+ padding_side="right",
919
+ pad_to_multiple_of=self.pad_to_multiple_of,
920
+ ).to(device=device)
921
+ if tool_mask_list is not None:
922
+ tool_mask = [torch.tensor(mask) for mask in tool_mask_list]
923
+ tool_mask = pad(
924
+ tool_mask, padding_value=1, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of
925
+ ).to(device=device)
926
+ else:
927
+ tool_mask = None
928
+ if topk_logprobs_list is not None:
929
+ sampling_topk_logps = [torch.tensor(lp) for lp in topk_logprobs_list]
930
+ sampling_topk_logps = pad(
931
+ sampling_topk_logps,
932
+ padding_value=0.0,
933
+ padding_side="right",
934
+ pad_to_multiple_of=self.pad_to_multiple_of,
935
+ ).to(device=device)
936
+ sampling_topk_token_ids = [torch.tensor(tid, dtype=torch.long) for tid in topk_token_ids_list]
937
+ sampling_topk_token_ids = pad(
938
+ sampling_topk_token_ids,
939
+ padding_value=0,
940
+ padding_side="right",
941
+ pad_to_multiple_of=self.pad_to_multiple_of,
942
+ ).to(device=device)
943
+ else:
944
+ sampling_topk_logps = None
945
+ sampling_topk_token_ids = None
946
+
947
+ # If mask_truncated_completions is enabled, zero out truncated completions for attention and loss masking
948
+ if self.mask_truncated_completions:
949
+ eos_and_pad = [self.eos_token_id, self.pad_token_id]
950
+ is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device)
951
+ # Mask completion_mask for attention masking
952
+ completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int()
953
+ # Also mask tool_mask for consistency in multi-turn training
954
+ if tool_mask is not None:
955
+ tool_mask = tool_mask * (~is_truncated).unsqueeze(1).int()
956
+
957
+ # Concatenate prompt_mask with completion_mask for logit computation
958
+ prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C)
959
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C)
960
+
961
+ logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
962
+ batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size
963
+
964
+ num_images = [len(img_list) for img_list in images] if images is not None else None
965
+
966
+ # Get forward_kwargs for models with multimodal inputs
967
+ if images is not None:
968
+ prompts_text = [
969
+ apply_chat_template(
970
+ {"prompt": prompt}, self.processing_class, tools=self.tools, **self.chat_template_kwargs
971
+ )["prompt"]
972
+ for prompt in prompts
973
+ ]
974
+ prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt")
975
+ prompt_inputs = Trainer._prepare_inputs(self, prompt_inputs)
976
+ forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]}
977
+ else:
978
+ forward_kwargs = {}
979
+
980
+ # If token_type_ids are used, extend them with zeros for the completion part
981
+ if "token_type_ids" in forward_kwargs:
982
+ token_type_ids = forward_kwargs["token_type_ids"]
983
+ if self.pad_to_multiple_of is not None:
984
+ padding_size = prompt_ids.size(1) - token_type_ids.size(1)
985
+ if padding_size > 0:
986
+ token_type_ids = torch.cat(
987
+ [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1
988
+ )
989
+ forward_kwargs["token_type_ids"] = torch.cat(
990
+ [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1
991
+ )
992
+ # If mm_token_type_ids are used, extend them with zeros for the completion part
993
+ if "mm_token_type_ids" in forward_kwargs:
994
+ mm_token_type_ids = forward_kwargs["mm_token_type_ids"]
995
+ if self.pad_to_multiple_of is not None:
996
+ padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1)
997
+ if padding_size > 0:
998
+ mm_token_type_ids = torch.cat(
999
+ [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids],
1000
+ dim=1,
1001
+ )
1002
+ forward_kwargs["mm_token_type_ids"] = torch.cat(
1003
+ [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1
1004
+ )
1005
+
1006
+ # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a
1007
+ # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True").
1008
+ # Temporarily disable checkpointing to avoid this warning during inference.
1009
+ with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
1010
+ # Compute the per-token log probabilities for the reference model
1011
+ if self.beta != 0.0:
1012
+ if self.ref_model is not None:
1013
+ ref_per_token_logps, _ = self._get_per_token_logps_and_entropies(
1014
+ self.ref_model,
1015
+ prompt_completion_ids,
1016
+ attention_mask,
1017
+ logits_to_keep,
1018
+ batch_size=batch_size,
1019
+ num_images=num_images,
1020
+ **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
1021
+ )
1022
+ else:
1023
+ # When training a PEFT adapter, how we obtain the reference depends on the setup:
1024
+ # - New adapter: disabling adapters yields the base model.
1025
+ # - Re-training an existing adapter: an initial copy is loaded under the name "ref".
1026
+ model = self.accelerator.unwrap_model(self.model)
1027
+ with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None):
1028
+ ref_per_token_logps, _ = self._get_per_token_logps_and_entropies(
1029
+ self.model,
1030
+ prompt_completion_ids,
1031
+ attention_mask,
1032
+ logits_to_keep,
1033
+ batch_size=batch_size,
1034
+ num_images=num_images,
1035
+ **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
1036
+ )
1037
+ else:
1038
+ ref_per_token_logps = None
1039
+
1040
+ # Decode
1041
+ prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True)
1042
+ completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
1043
+
1044
+ # Merge extra_fields from rollout_func into inputs for reward functions
1045
+ if extra_fields:
1046
+ for i, inp in enumerate(inputs):
1047
+ for key, values in extra_fields.items():
1048
+ if isinstance(values, list) and i < len(values):
1049
+ inp[key] = values[i]
1050
+ elif not isinstance(values, list):
1051
+ inp[key] = values
1052
+
1053
+ # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is
1054
+ # important because rewards will be normalized per group, and completions are distributed. We will later slice
1055
+ # rewards_per_func to extract each process's subset.
1056
+ rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
1057
+ num_generations = self.num_generations if mode == "train" else self.num_generations_eval
1058
+
1059
+ if self.multi_objective_aggregation == "sum_then_normalize":
1060
+ # Apply weights to each reward function's output and sum
1061
+ rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
1062
+ mean_grouped_rewards = rewards.view(-1, num_generations).mean(dim=1)
1063
+ mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(num_generations, dim=0)
1064
+ if self.scale_rewards in ["group", "none"]:
1065
+ # If self.scale_rewards = "none", we'll only use std_rewards to check for zero std for logging
1066
+ if num_generations > 1:
1067
+ std_rewards = rewards.view(-1, num_generations).std(dim=1)
1068
+ std_rewards = std_rewards.repeat_interleave(num_generations, dim=0)
1069
+ else: # doesn't occur during training, but could occur in eval when num_generations_eval=1
1070
+ std_rewards = torch.zeros_like(rewards)
1071
+ elif self.scale_rewards == "batch":
1072
+ # Compute global std
1073
+ if rewards.numel() > 1:
1074
+ std_rewards = rewards.std().expand_as(rewards)
1075
+ else: # doesn't occur during training, but could occur in eval when num_generations_eval=batch_size=1
1076
+ std_rewards = torch.zeros_like(rewards)
1077
+ else:
1078
+ raise ValueError(
1079
+ f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'."
1080
+ )
1081
+
1082
+ advantages = rewards - mean_grouped_rewards
1083
+ if self.scale_rewards != "none":
1084
+ advantages = advantages / (std_rewards + 1e-4)
1085
+ is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging
1086
+
1087
+ elif self.multi_objective_aggregation == "normalize_then_sum":
1088
+ grouped = rewards_per_func.view(-1, num_generations, len(self.reward_funcs))
1089
+ mean_k = torch.nanmean(grouped, dim=1, keepdim=True)
1090
+ std_k = nanstd(grouped, dim=1, keepdim=True) if num_generations > 1 else torch.zeros_like(mean_k)
1091
+ reward_k = (grouped - mean_k) / (std_k + 1e-4)
1092
+ reward_k = reward_k.view(-1, len(self.reward_funcs))
1093
+ rewards = (reward_k * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
1094
+ std_rewards = rewards.std().expand_as(rewards) if rewards.numel() > 1 else torch.zeros_like(rewards)
1095
+ advantages = (rewards - rewards.mean()) / (std_rewards + 1e-4)
1096
+ is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging
1097
+
1098
+ else:
1099
+ raise ValueError(
1100
+ f"Invalid multi_objective_aggregation: {self.multi_objective_aggregation}. Must be "
1101
+ "'sum_then_normalize' or 'normalize_then_sum'."
1102
+ )
1103
+
1104
+ # Slice to keep only the local part of the data
1105
+ process_slice = slice(
1106
+ self.accelerator.process_index * len(prompts),
1107
+ (self.accelerator.process_index + 1) * len(prompts),
1108
+ )
1109
+ all_process_advantages = advantages.clone() # keep the aggregated advantages for logging
1110
+ advantages = advantages[process_slice]
1111
+
1112
+ # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values)
1113
+ for i, reward_func_name in enumerate(self.reward_func_names):
1114
+ mean_rewards = torch.nanmean(rewards_per_func[:, i]).item()
1115
+ self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards)
1116
+ std_func_rewards = nanstd(rewards_per_func[:, i]).item()
1117
+ self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards)
1118
+ rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1)
1119
+ self._metrics[mode]["reward"].append(rewards.mean().item())
1120
+ self._metrics[mode]["reward_std"].append(rewards.std().item())
1121
+ self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item())
1122
+
1123
+ # Log prompt and completion texts
1124
+ self._logs["prompt"].extend(gather_object(prompts_text))
1125
+ self._logs["completion"].extend(gather_object(completions_text))
1126
+ for i, name in enumerate(self.reward_func_names):
1127
+ self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist())
1128
+ self._logs["advantages"].extend(all_process_advantages.tolist())
1129
+
1130
+ # Flush user-logged extra columns (from log_extra), gathering across processes.
1131
+ # Keys must be sorted so that all ranks call gather_object in the same order, otherwise values
1132
+ # get mis-attributed across columns (dict insertion order may differ between processes).
1133
+ for column in sorted(self._pending_extra_logs):
1134
+ self._logs["extra"][column].extend(gather_object(self._pending_extra_logs[column]))
1135
+ self._pending_extra_logs.clear()
1136
+
1137
+ # Flush user-logged metrics (from log_metric), averaging across processes.
1138
+ # Keys must be sorted so that all ranks call accelerator.gather in the same order, otherwise values
1139
+ # get mis-attributed across metrics (dict insertion order may differ between processes).
1140
+ for name in sorted(self._pending_metrics):
1141
+ values = self._pending_metrics[name]
1142
+ local_mean = sum(values) / len(values)
1143
+ global_mean = self.accelerator.gather(torch.tensor(local_mean, device=device)).mean().item()
1144
+ self._metrics[mode][name].append(global_mean)
1145
+ self._pending_metrics.clear()
1146
+
1147
+ if images is not None:
1148
+ self._logs["images"].extend(gather_object(images))
1149
+
1150
+ output = {
1151
+ "prompt_ids": prompt_ids,
1152
+ "prompt_mask": prompt_mask,
1153
+ "completion_ids": completion_ids,
1154
+ "completion_mask": completion_mask,
1155
+ "advantages": advantages,
1156
+ "num_items_in_batch": num_items_in_batch,
1157
+ "sampling_per_token_logps": sampling_per_token_logps,
1158
+ }
1159
+ if ref_per_token_logps is not None:
1160
+ output["ref_per_token_logps"] = ref_per_token_logps
1161
+ if "pixel_values" in forward_kwargs:
1162
+ output["pixel_values"] = forward_kwargs["pixel_values"]
1163
+ if "image_grid_thw" in forward_kwargs:
1164
+ output["image_grid_thw"] = forward_kwargs["image_grid_thw"]
1165
+ if "pixel_attention_mask" in forward_kwargs:
1166
+ output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"]
1167
+ if "image_sizes" in forward_kwargs:
1168
+ output["image_sizes"] = forward_kwargs["image_sizes"]
1169
+ if "token_type_ids" in forward_kwargs:
1170
+ output["token_type_ids"] = forward_kwargs["token_type_ids"]
1171
+ if "mm_token_type_ids" in forward_kwargs:
1172
+ output["mm_token_type_ids"] = forward_kwargs["mm_token_type_ids"]
1173
+ if images is not None:
1174
+ output["num_images"] = num_images
1175
+ if tool_mask is not None:
1176
+ output["tool_mask"] = tool_mask
1177
+ if sampling_topk_logps is not None:
1178
+ output["sampling_topk_logps"] = sampling_topk_logps
1179
+ if sampling_topk_token_ids is not None:
1180
+ output["sampling_topk_token_ids"] = sampling_topk_token_ids
1181
+ return output
1182
+
1183
+ @torch.no_grad()
1184
+ def _compute_divergence_mask(
1185
+ self,
1186
+ per_token_logps,
1187
+ sampling_per_token_logps,
1188
+ advantages,
1189
+ completion_mask,
1190
+ current_topk_logps=None,
1191
+ sampling_topk_logps=None,
1192
+ ):
1193
+ """
1194
+ Compute a per-token trust-region mask based on the configured divergence type. Tokens where the policy has
1195
+ diverged too far from the sampling distribution (in a direction that would increase the loss) are masked out.
1196
+
1197
+ Args:
1198
+ per_token_logps (`torch.Tensor`):
1199
+ Log-probabilities of the current policy at the sampled tokens, shape `(B, T)`.
1200
+ sampling_per_token_logps (`torch.Tensor`):
1201
+ Log-probabilities of the sampling (rollout) policy at the sampled tokens, shape `(B, T)`.
1202
+ advantages (`torch.Tensor`):
1203
+ Per-token or per-sequence advantage estimates, broadcastable to `(B, T)`.
1204
+ completion_mask (`torch.Tensor`):
1205
+ Binary mask of shape `(B, T)` where `1` indicates valid completion tokens and `0` padding.
1206
+ current_topk_logps (`torch.Tensor` or `None`):
1207
+ Log-probabilities of the current policy at the rollout's top-K token IDs, shape `(B, T, K)`. Required
1208
+ when `divergence_type` is `"topk_tv"` or `"topk_kl"`.
1209
+ sampling_topk_logps (`torch.Tensor` or `None`):
1210
+ Log-probabilities of the sampling policy at the rollout's top-K token IDs, shape `(B, T, K)`. Required
1211
+ when `divergence_type` is `"topk_tv"` or `"topk_kl"`.
1212
+
1213
+ Returns:
1214
+ `torch.Tensor`:
1215
+ Float mask of shape `(B, T)` where `1.0` indicates tokens to keep and `0.0` tokens to mask out.
1216
+ """
1217
+ prob = torch.exp(per_token_logps)
1218
+ sampling_prob = torch.exp(sampling_per_token_logps)
1219
+
1220
+ delta_low = self.epsilon_low
1221
+ delta_high = self.epsilon_high
1222
+
1223
+ if self.divergence_type == "binary_tv":
1224
+ # TV = |π - μ|
1225
+ divergence = (prob - sampling_prob).abs()
1226
+ # Mask tokens where divergence > threshold AND policy moves away from trust region
1227
+ invalid_pos = (divergence > delta_high) & (prob > sampling_prob)
1228
+ invalid_neg = (divergence > delta_low) & (prob < sampling_prob)
1229
+ mask = torch.where(advantages > 0, ~invalid_pos, ~invalid_neg)
1230
+
1231
+ elif self.divergence_type == "binary_kl":
1232
+ # Bernoulli KL: D = μ log(μ/π) + (1-μ) log((1-μ)/(1-π))
1233
+ kl = sampling_prob * (sampling_per_token_logps - per_token_logps) + (1 - sampling_prob) * (
1234
+ torch.log1p(-sampling_prob.clamp(max=1 - 1e-7)) - torch.log1p(-prob.clamp(max=1 - 1e-7))
1235
+ )
1236
+
1237
+ invalid_pos = (kl > delta_high) & (prob > sampling_prob)
1238
+ invalid_neg = (kl > delta_low) & (prob < sampling_prob)
1239
+ mask = torch.where(advantages > 0, ~invalid_pos, ~invalid_neg)
1240
+
1241
+ elif self.divergence_type in ("topk_tv", "topk_kl"):
1242
+ current_topk_probs = torch.exp(current_topk_logps.float())
1243
+ rollout_topk_probs = torch.exp(sampling_topk_logps.float())
1244
+
1245
+ # Aggregate remaining probability mass outside top-K into a single rest bucket.
1246
+ rollout_rest = (1.0 - rollout_topk_probs.sum(dim=-1)).clamp(min=1e-12)
1247
+ current_rest = (1.0 - current_topk_probs.sum(dim=-1)).clamp(min=1e-12)
1248
+
1249
+ if self.divergence_type == "topk_tv":
1250
+ topk_tv = (current_topk_probs - rollout_topk_probs).abs().sum(dim=-1)
1251
+ rest_tv = (current_rest - rollout_rest).abs()
1252
+ divergence = (topk_tv + rest_tv) / 2.0
1253
+ else:
1254
+ topk_kl = (rollout_topk_probs * (sampling_topk_logps - current_topk_logps)).sum(dim=-1)
1255
+ rest_kl = rollout_rest * (rollout_rest.log() - current_rest.log())
1256
+ divergence = topk_kl + rest_kl
1257
+
1258
+ invalid_pos = (divergence > delta_high) & (prob > sampling_prob)
1259
+ invalid_neg = (divergence > delta_low) & (prob < sampling_prob)
1260
+ mask = torch.where(advantages > 0, ~invalid_pos, ~invalid_neg)
1261
+
1262
+ else:
1263
+ raise ValueError(f"Unknown divergence_type: {self.divergence_type}")
1264
+
1265
+ return mask.float() * completion_mask
1266
+
1267
+ def _compute_loss(self, model, inputs):
1268
+ # Compute per-token log probabilities for the model
1269
+ prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
1270
+ completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
1271
+ input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
1272
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
1273
+ logits_to_keep = completion_ids.size(1)
1274
+ mask = completion_mask if "tool_mask" not in inputs else completion_mask * inputs["tool_mask"]
1275
+
1276
+ forward_kwargs = {
1277
+ "pixel_values": inputs.get("pixel_values"),
1278
+ "image_grid_thw": inputs.get("image_grid_thw"),
1279
+ "num_images": inputs.get("num_images"),
1280
+ "pixel_attention_mask": inputs.get("pixel_attention_mask"),
1281
+ "image_sizes": inputs.get("image_sizes"),
1282
+ "token_type_ids": inputs.get("token_type_ids"),
1283
+ "mm_token_type_ids": inputs.get("mm_token_type_ids"),
1284
+ }
1285
+
1286
+ sampling_topk_token_ids = inputs.get("sampling_topk_token_ids")
1287
+ if self.divergence_type.startswith("topk_") and sampling_topk_token_ids is not None:
1288
+ per_token_logps, entropies, current_topk_logps = self._get_per_token_logps_with_topk(
1289
+ model,
1290
+ input_ids,
1291
+ attention_mask,
1292
+ logits_to_keep,
1293
+ topk_token_ids=sampling_topk_token_ids,
1294
+ compute_entropy=True,
1295
+ **forward_kwargs,
1296
+ )
1297
+ else:
1298
+ per_token_logps, entropies = self._get_per_token_logps_and_entropies(
1299
+ model,
1300
+ input_ids,
1301
+ attention_mask,
1302
+ logits_to_keep,
1303
+ compute_entropy=True,
1304
+ **forward_kwargs,
1305
+ )
1306
+ current_topk_logps = None
1307
+
1308
+ sampling_per_token_logps = inputs["sampling_per_token_logps"]
1309
+ sampling_topk_logps = inputs.get("sampling_topk_logps")
1310
+
1311
+ advantages = inputs["advantages"]
1312
+ if advantages.dim() == 1:
1313
+ advantages = advantages.unsqueeze(1)
1314
+
1315
+ # DPPO: compute IS ratio (clamped, detached) and divergence mask
1316
+ log_ratio = per_token_logps - sampling_per_token_logps
1317
+ ratio = torch.exp(log_ratio.clamp(max=math.log(self.clip_ratio_c))).detach()
1318
+ divergence_mask = self._compute_divergence_mask(
1319
+ per_token_logps,
1320
+ sampling_per_token_logps,
1321
+ advantages,
1322
+ mask,
1323
+ current_topk_logps=current_topk_logps,
1324
+ sampling_topk_logps=sampling_topk_logps,
1325
+ )
1326
+
1327
+ # DPPO loss: -advantages * ratio * mask * log_prob
1328
+ per_token_loss = -advantages * ratio * divergence_mask * per_token_logps
1329
+
1330
+ # KL divergence with reference model
1331
+ if self.beta != 0.0:
1332
+ ref_per_token_logps = inputs["ref_per_token_logps"]
1333
+ per_token_kl = (
1334
+ torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
1335
+ )
1336
+ per_token_loss = per_token_loss + self.beta * per_token_kl
1337
+
1338
+ mode = "train" if self.model.training else "eval"
1339
+ normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes
1340
+ loss = (per_token_loss * mask).sum() / normalizer
1341
+
1342
+ # Log metrics
1343
+ completion_token_count = mask.sum().clamp(min=1.0)
1344
+
1345
+ def masked_batch_mean(x):
1346
+ if x.shape[1] == 1:
1347
+ return x.mean()
1348
+ return (x * mask).sum() / completion_token_count
1349
+
1350
+ if self.beta != 0.0:
1351
+ mean_kl = masked_batch_mean(per_token_kl)
1352
+ self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
1353
+
1354
+ mean_entropy = masked_batch_mean(entropies)
1355
+ self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item())
1356
+
1357
+ prob_diff = (torch.exp(per_token_logps) - torch.exp(sampling_per_token_logps)).abs()
1358
+ self._metrics[mode]["prob_diff/mean"].append(
1359
+ self.accelerator.gather(masked_batch_mean(prob_diff)).nanmean().item()
1360
+ )
1361
+ per_seq_max = prob_diff.masked_fill(mask == 0, float("-inf")).max(dim=1).values
1362
+ per_seq_min = prob_diff.masked_fill(mask == 0, float("inf")).min(dim=1).values
1363
+ self._metrics[mode]["prob_diff/max"].append(self.accelerator.gather(per_seq_max).max().item())
1364
+ self._metrics[mode]["prob_diff/min"].append(self.accelerator.gather(per_seq_min).min().item())
1365
+
1366
+ self._metrics[mode]["advantages/mean"].append(advantages.mean().item())
1367
+ self._metrics[mode]["advantages/std"].append(advantages.std().item())
1368
+
1369
+ # Log divergence mask statistics (analogous to clip_ratio in GRPO)
1370
+ is_masked = (divergence_mask == 0) & (mask > 0)
1371
+ is_masked_pos = is_masked & (advantages > 0)
1372
+ is_masked_neg = is_masked & (advantages < 0)
1373
+
1374
+ mask_ratio_pos = masked_batch_mean(is_masked_pos.float())
1375
+ mask_ratio_neg = masked_batch_mean(is_masked_neg.float())
1376
+ mask_ratio = masked_batch_mean(is_masked.float())
1377
+
1378
+ gathered_mask_ratio_neg = self.accelerator.gather(mask_ratio_neg)
1379
+ self._metrics[mode]["mask_ratio/negative_adv_mean"].append(gathered_mask_ratio_neg.nanmean().item())
1380
+ gathered_mask_ratio_pos = self.accelerator.gather(mask_ratio_pos)
1381
+ self._metrics[mode]["mask_ratio/positive_adv_mean"].append(gathered_mask_ratio_pos.nanmean().item())
1382
+ gathered_mask_ratio = self.accelerator.gather(mask_ratio)
1383
+ self._metrics[mode]["mask_ratio/overall_mean"].append(gathered_mask_ratio.nanmean().item())
1384
+
1385
+ return loss
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gfpo/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .gfpo_config import GFPOConfig
16
+ from .gfpo_trainer import GFPOTrainer
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gfpo/gfpo_config.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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, field
16
+
17
+ from ...trainer.grpo_config import GRPOConfig as _GRPOConfig
18
+
19
+
20
+ @dataclass
21
+ class GFPOConfig(_GRPOConfig):
22
+ num_remains_in_group: int | None = field(
23
+ default=None,
24
+ metadata={
25
+ "help": "number inputs remains after group filter function, `'num_remains_in_group'` must be >=2 if given."
26
+ },
27
+ )
28
+
29
+ def __post_init__(self):
30
+ super().__post_init__()
31
+
32
+ if self.num_remains_in_group is not None and self.num_remains_in_group >= self.num_generations:
33
+ raise ValueError(
34
+ f"Number remains in Group {self.num_remains_in_group} must be less than num_generations : {self.num_generations}."
35
+ )
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gfpo/gfpo_trainer.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 logging
16
+ from collections.abc import Callable
17
+ from typing import Any
18
+
19
+ import torch
20
+ from accelerate.utils import gather_object
21
+
22
+ from ...data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages
23
+ from ...models.utils import disable_gradient_checkpointing
24
+ from ...trainer.grpo_trainer import GRPOTrainer as _GRPOTrainer
25
+ from ...trainer.utils import nanmax, nanmin, nanstd, pad
26
+
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ GroupFilterFunc = Callable[[list[list[Any]], list[list[Any]]], list[list[float]]]
31
+
32
+
33
+ class GFPOTrainer(_GRPOTrainer):
34
+ def __init__(
35
+ self,
36
+ model,
37
+ reward_funcs,
38
+ args=None,
39
+ train_dataset=None,
40
+ eval_dataset=None,
41
+ processing_class=None,
42
+ reward_processing_classes=None,
43
+ group_filter_func=None,
44
+ callbacks=None,
45
+ optimizers=(None, None),
46
+ peft_config=None,
47
+ ):
48
+ super().__init__(
49
+ model=model,
50
+ reward_funcs=reward_funcs,
51
+ args=args,
52
+ train_dataset=train_dataset,
53
+ eval_dataset=eval_dataset,
54
+ processing_class=processing_class,
55
+ reward_processing_classes=reward_processing_classes,
56
+ callbacks=callbacks,
57
+ optimizers=optimizers,
58
+ peft_config=peft_config,
59
+ )
60
+ self.group_filter_func = group_filter_func
61
+ self.num_remains_in_group = args.num_remains_in_group
62
+ if self.group_filter_func is None and self.num_remains_in_group is not None:
63
+ raise ValueError(
64
+ f"Group filter function must not be None when num_remains_in_group ({self.num_remains_in_group}) is given."
65
+ )
66
+ if self.group_filter_func is not None and self.num_remains_in_group is None:
67
+ logger.warning("Group filter function is not activated since num_remains_in_group is not set")
68
+
69
+ def _generate_and_score_completions(self, inputs):
70
+ device = self.accelerator.device
71
+ mode = "train" if self.model.training else "eval"
72
+
73
+ prompts = [x["prompt"] for x in inputs]
74
+
75
+ if "images" in inputs[0]:
76
+ images = [example.get("images") for example in inputs]
77
+ elif "image" in inputs[0]:
78
+ images = [[example.get("image")] if example.get("image") is not None else None for example in inputs]
79
+ else:
80
+ images = None
81
+ # Transformers requires at least one image in the batch, otherwise it throws an error
82
+ if images is not None and all(img_list == [] for img_list in images):
83
+ images = None
84
+
85
+ # If the prompts are conversational and the inputs contain images, we need to convert the prompts from
86
+ # [{"role": "user", "content": "What color is the sky?"}] to
87
+ # [{"role": "user", "content": [{"type": "image", "image": <Image>}, {"type": "text", "text": "What color is the sky?"}]}]
88
+ if images is not None:
89
+ if not is_conversational(inputs[0]):
90
+ raise ValueError(
91
+ "Multimodal training requires conversational prompts. It looks like the dataset contains "
92
+ "non-conversational inputs, likely because a chat template was applied before passing the dataset "
93
+ "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat "
94
+ "template internally."
95
+ )
96
+ prompts = [
97
+ prepare_multimodal_messages(prompt, images=image_list)
98
+ for prompt, image_list in zip(prompts, images, strict=True)
99
+ ]
100
+
101
+ dataset_images = images # preserve dataset images before _generate may overwrite
102
+ (
103
+ prompt_ids_list,
104
+ completion_ids_list,
105
+ tool_mask_list,
106
+ completions,
107
+ num_items_in_batch,
108
+ sampling_per_token_logps_list,
109
+ extra_fields,
110
+ images,
111
+ tool_images,
112
+ ) = self._generate(prompts)
113
+ if images is None:
114
+ images = dataset_images # restore dataset images (rollout_func path returns None)
115
+
116
+ # Convert lists of token IDs to padded tensors
117
+ prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list]
118
+ prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids]
119
+ prompt_ids = pad(
120
+ prompt_ids,
121
+ padding_value=self.pad_token_id,
122
+ padding_side="left",
123
+ pad_to_multiple_of=self.pad_to_multiple_of,
124
+ ).to(device=device)
125
+ prompt_mask = pad(
126
+ prompt_mask,
127
+ padding_value=0,
128
+ padding_side="left",
129
+ pad_to_multiple_of=self.pad_to_multiple_of,
130
+ ).to(device=device)
131
+ completion_ids = [torch.tensor(ids) for ids in completion_ids_list]
132
+ completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids]
133
+ completion_ids = pad(
134
+ completion_ids,
135
+ padding_value=self.pad_token_id,
136
+ padding_side="right",
137
+ pad_to_multiple_of=self.pad_to_multiple_of,
138
+ ).to(device=device)
139
+ completion_mask = pad(
140
+ completion_mask,
141
+ padding_value=0,
142
+ padding_side="right",
143
+ pad_to_multiple_of=self.pad_to_multiple_of,
144
+ ).to(device=device)
145
+ if sampling_per_token_logps_list is not None:
146
+ sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list]
147
+ sampling_per_token_logps = pad(
148
+ sampling_per_token_logps,
149
+ padding_value=0.0,
150
+ padding_side="right",
151
+ pad_to_multiple_of=self.pad_to_multiple_of,
152
+ ).to(device=device)
153
+ else:
154
+ sampling_per_token_logps = None
155
+
156
+ # If mask_truncated_completions is enabled, zero out truncated completions in completion_mask
157
+ if self.mask_truncated_completions:
158
+ eos_and_pad = [self.eos_token_id, self.pad_token_id]
159
+ is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device)
160
+ completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int()
161
+
162
+ # Concatenate prompt_mask with completion_mask for logit computation
163
+ prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C)
164
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C)
165
+
166
+ logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
167
+ batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size
168
+
169
+ num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None
170
+
171
+ # Get forward_kwargs for models with multimodal inputs
172
+ if images is not None:
173
+ prompts_text = [
174
+ apply_chat_template({"prompt": prompt}, self.processing_class)["prompt"] for prompt in prompts
175
+ ]
176
+ prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt")
177
+ prompt_inputs = super()._prepare_inputs(prompt_inputs)
178
+ forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]}
179
+ else:
180
+ forward_kwargs = {}
181
+
182
+ # If token_type_ids are used, extend them with zeros for the completion part
183
+ if "token_type_ids" in forward_kwargs:
184
+ token_type_ids = forward_kwargs["token_type_ids"]
185
+ if self.pad_to_multiple_of is not None:
186
+ # Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len
187
+ padding_size = prompt_ids.size(1) - token_type_ids.size(1)
188
+ if padding_size > 0:
189
+ token_type_ids = torch.cat(
190
+ [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1
191
+ )
192
+ forward_kwargs["token_type_ids"] = torch.cat(
193
+ [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1
194
+ )
195
+ # If mm_token_type_ids are used, extend them with zeros for the completion part
196
+ if "mm_token_type_ids" in forward_kwargs:
197
+ mm_token_type_ids = forward_kwargs["mm_token_type_ids"]
198
+ if self.pad_to_multiple_of is not None:
199
+ # Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len
200
+ padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1)
201
+ if padding_size > 0:
202
+ mm_token_type_ids = torch.cat(
203
+ [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids],
204
+ dim=1,
205
+ )
206
+ forward_kwargs["mm_token_type_ids"] = torch.cat(
207
+ [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1
208
+ )
209
+
210
+ # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a
211
+ # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True").
212
+ # Temporarily disable checkpointing to avoid this warning during inference.
213
+ with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
214
+ # If the generation and optimization steps are misaligned—i.e., if generation does not occur at the end of
215
+ # a full optimizer step (when gradient_accumulation_steps is not a multiple of generate_every)—then the
216
+ # samples may come from an earlier version of the model. In that case, we need to track old_per_token_logps
217
+ # for importance sampling. If the steps are aligned, importance sampling isn't necessary and we set
218
+ # old_per_token_logps to None.
219
+ # When using vLLM, we always compute old_per_token_logps for importance sampling, it was shown that the
220
+ # distribution mismatch between vLLM and the training model can be large and harm the training.
221
+ generate_every = self.args.steps_per_generation * self.num_iterations # generation frequency
222
+ if self.args.gradient_accumulation_steps % generate_every != 0 or (
223
+ self.use_vllm and self.vllm_importance_sampling_correction
224
+ ):
225
+ old_per_token_logps, _ = self._get_per_token_logps_and_entropies(
226
+ self.model,
227
+ prompt_completion_ids,
228
+ attention_mask,
229
+ logits_to_keep,
230
+ batch_size,
231
+ num_images=num_images,
232
+ **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
233
+ )
234
+ else:
235
+ old_per_token_logps = None
236
+
237
+ # Compute the importance sampling ratio when using vLLM, to correct for potential distribution mismatch
238
+ if self.use_vllm and self.vllm_importance_sampling_correction:
239
+ importance_sampling_ratio = torch.exp(old_per_token_logps - sampling_per_token_logps)
240
+ importance_sampling_ratio = torch.clamp(
241
+ importance_sampling_ratio, max=self.vllm_importance_sampling_cap
242
+ )
243
+
244
+ # Compute the per-token log probabilities for the reference model
245
+ if self.beta != 0.0:
246
+ if self.ref_model is not None:
247
+ ref_per_token_logps, _ = self._get_per_token_logps_and_entropies(
248
+ self.ref_model,
249
+ prompt_completion_ids,
250
+ attention_mask,
251
+ logits_to_keep,
252
+ batch_size=batch_size,
253
+ num_images=num_images,
254
+ **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
255
+ )
256
+ else:
257
+ with self.accelerator.unwrap_model(self.model).disable_adapter():
258
+ ref_per_token_logps, _ = self._get_per_token_logps_and_entropies(
259
+ self.model,
260
+ prompt_completion_ids,
261
+ attention_mask,
262
+ logits_to_keep,
263
+ batch_size=batch_size,
264
+ num_images=num_images,
265
+ **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
266
+ )
267
+ else:
268
+ ref_per_token_logps = None
269
+
270
+ # Decode
271
+ prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True)
272
+ completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
273
+ if is_conversational(inputs[0]):
274
+ completions = []
275
+ for prompt, completion in zip(prompts, completions_text, strict=True):
276
+ bootstrap = prompt.pop()["content"] if prompt[-1]["role"] == "assistant" else ""
277
+ if isinstance(bootstrap, list): # for VLM, the format might be [{"type": "text", "text": "..."}]
278
+ assert len(bootstrap) == 1 and bootstrap[0]["type"] == "text"
279
+ bootstrap = bootstrap[0]["text"]
280
+ completions.append([{"role": "assistant", "content": bootstrap + completion}])
281
+ else:
282
+ completions = completions_text
283
+
284
+ # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is
285
+ # important because rewards will be normalized per group, and completions are distributed. We will later slice
286
+ # rewards_per_func to extract each process's subset.
287
+ rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
288
+
289
+ # Apply weights to each reward function's output and sum
290
+ rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
291
+
292
+ num_in_group = self.num_generations
293
+ num_inputs_in_device = len(prompts)
294
+
295
+ if self.num_remains_in_group is not None and mode == "train":
296
+ num_in_group = self.num_remains_in_group
297
+
298
+ all_completions = gather_object(completions)
299
+
300
+ group_filter_scores = self.group_filter_func(
301
+ group_completions=[
302
+ all_completions[i : i + 1 * self.num_generations]
303
+ for i in range(len(all_completions) // self.num_generations)
304
+ ],
305
+ group_rewards=rewards.view(-1, self.num_generations).tolist(),
306
+ )
307
+ group_filter_scores = torch.tensor(group_filter_scores, device=device)
308
+
309
+ _, group_local_indices = torch.topk(group_filter_scores, self.num_remains_in_group, dim=-1)
310
+ group_row_offsets = torch.arange(0, len(all_completions), self.num_generations, device=device).unsqueeze(1)
311
+ group_global_indices = group_row_offsets + group_local_indices
312
+ group_global_indices = group_global_indices.flatten()
313
+
314
+ rewards = rewards[group_global_indices].contiguous()
315
+ rewards_per_func = rewards_per_func[group_global_indices, :].contiguous()
316
+
317
+ num_inputs_in_device = int(len(prompts) / self.num_generations * self.num_remains_in_group)
318
+
319
+ # Compute grouped-wise rewards
320
+ mean_grouped_rewards = rewards.view(-1, num_in_group).mean(dim=1)
321
+
322
+ # Normalize the rewards to compute the advantages
323
+ mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(num_in_group, dim=0)
324
+ advantages = rewards - mean_grouped_rewards
325
+
326
+ if self.scale_rewards in ["group", "none"]:
327
+ # If self.scale_rewards = "none", we'll still log group level std
328
+ std_rewards = rewards.view(-1, num_in_group).std(dim=1)
329
+ std_rewards = std_rewards.repeat_interleave(num_in_group, dim=0)
330
+ elif self.scale_rewards == "batch":
331
+ # Compute global std
332
+ std_rewards = rewards.std().expand_as(rewards)
333
+ else:
334
+ raise ValueError(
335
+ f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'."
336
+ )
337
+
338
+ is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards))
339
+ if self.scale_rewards != "none":
340
+ advantages = advantages / (std_rewards + 1e-4)
341
+
342
+ # Slice to keep only the local part of the data
343
+ process_slice = slice(
344
+ self.accelerator.process_index * num_inputs_in_device,
345
+ (self.accelerator.process_index + 1) * num_inputs_in_device,
346
+ )
347
+ all_process_advantages = advantages.clone() # keep the aggregated advantages for logging
348
+ advantages = advantages[process_slice]
349
+
350
+ if self.num_remains_in_group is not None and mode == "train":
351
+ local_input_indices_to_keep = group_global_indices[process_slice] - self.accelerator.process_index * len(
352
+ prompts
353
+ ) # step is length of prompts
354
+
355
+ prompt_ids = prompt_ids[local_input_indices_to_keep].contiguous()
356
+ prompt_mask = prompt_mask[local_input_indices_to_keep].contiguous()
357
+ completion_ids = completion_ids[local_input_indices_to_keep].contiguous()
358
+ completion_mask = completion_mask[local_input_indices_to_keep].contiguous()
359
+ attention_mask = attention_mask[local_input_indices_to_keep].contiguous()
360
+ completion_lengths = completion_mask.sum(1)
361
+ agg_completion_lengths = self.accelerator.gather(completion_lengths)
362
+ num_items_in_batch = agg_completion_lengths.sum()
363
+
364
+ if sampling_per_token_logps is not None:
365
+ sampling_per_token_logps = sampling_per_token_logps[local_input_indices_to_keep].contiguous()
366
+ if old_per_token_logps is not None:
367
+ old_per_token_logps = old_per_token_logps[local_input_indices_to_keep].contiguous()
368
+ if ref_per_token_logps is not None:
369
+ ref_per_token_logps = ref_per_token_logps[local_input_indices_to_keep].contiguous()
370
+ if self.use_vllm and self.vllm_importance_sampling_correction:
371
+ importance_sampling_ratio = importance_sampling_ratio[local_input_indices_to_keep].contiguous()
372
+
373
+ # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values)
374
+ for i, reward_func_name in enumerate(self.reward_func_names):
375
+ mean_rewards = torch.nanmean(rewards_per_func[:, i]).item()
376
+ self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards)
377
+ std_func_rewards = nanstd(rewards_per_func[:, i]).item()
378
+ self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards)
379
+ rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1)
380
+ self._metrics[mode]["reward"].append(rewards.mean().item())
381
+ self._metrics[mode]["reward_std"].append(rewards.std().item())
382
+ self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item())
383
+
384
+ # Log prompt and completion texts
385
+ all_prompts_text = gather_object(prompts_text)
386
+ all_completions_text = gather_object(completions_text)
387
+ all_images = gather_object(images) if images is not None else None
388
+ if self.num_remains_in_group is not None and mode == "train":
389
+ group_global_indices_list = group_global_indices.tolist()
390
+ all_prompts_text = [all_prompts_text[i] for i in group_global_indices_list]
391
+ all_completions_text = [all_completions_text[i] for i in group_global_indices_list]
392
+ if images is not None:
393
+ all_images = [all_images[i] for i in group_global_indices_list]
394
+
395
+ self._logs["prompt"].extend(all_prompts_text)
396
+ self._logs["completion"].extend(all_completions_text)
397
+ for i, name in enumerate(self.reward_func_names):
398
+ self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist())
399
+ self._logs["advantages"].extend(all_process_advantages.tolist())
400
+
401
+ if images is not None:
402
+ self._logs["images"].extend(all_images)
403
+
404
+ if self.use_vllm and self.vllm_importance_sampling_correction:
405
+ delta = torch.abs(old_per_token_logps - sampling_per_token_logps)
406
+ delta = delta[completion_mask.bool()]
407
+ mean_delta = torch.mean(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device)
408
+ max_delta = torch.max(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device)
409
+ self._metrics[mode]["sampling/sampling_logp_difference/mean"].append(
410
+ self.accelerator.gather(mean_delta).mean().item()
411
+ )
412
+ self._metrics[mode]["sampling/sampling_logp_difference/max"].append(
413
+ self.accelerator.gather(max_delta).max().item()
414
+ )
415
+
416
+ flat_is_ratio = importance_sampling_ratio[completion_mask.bool()]
417
+ min_importance_sampling_ratio = (
418
+ torch.min(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device)
419
+ )
420
+ mean_importance_sampling_ratio = (
421
+ torch.mean(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device)
422
+ )
423
+ max_importance_sampling_ratio = (
424
+ torch.max(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device)
425
+ )
426
+ self._metrics[mode]["sampling/importance_sampling_ratio/min"].append(
427
+ nanmin(self.accelerator.gather(min_importance_sampling_ratio)).item()
428
+ )
429
+ self._metrics[mode]["sampling/importance_sampling_ratio/mean"].append(
430
+ self.accelerator.gather(mean_importance_sampling_ratio).nanmean().item()
431
+ )
432
+ self._metrics[mode]["sampling/importance_sampling_ratio/max"].append(
433
+ nanmax(self.accelerator.gather(max_importance_sampling_ratio)).item()
434
+ )
435
+
436
+ output = {
437
+ "prompt_ids": prompt_ids,
438
+ "prompt_mask": prompt_mask,
439
+ "completion_ids": completion_ids,
440
+ "completion_mask": completion_mask,
441
+ "advantages": advantages,
442
+ "num_items_in_batch": num_items_in_batch,
443
+ }
444
+ if old_per_token_logps is not None:
445
+ output["old_per_token_logps"] = old_per_token_logps
446
+ if self.use_vllm and self.vllm_importance_sampling_correction:
447
+ output["importance_sampling_ratio"] = importance_sampling_ratio
448
+ if ref_per_token_logps is not None:
449
+ output["ref_per_token_logps"] = ref_per_token_logps
450
+ if "pixel_values" in forward_kwargs:
451
+ output["pixel_values"] = forward_kwargs["pixel_values"]
452
+ if "image_grid_thw" in forward_kwargs:
453
+ output["image_grid_thw"] = forward_kwargs["image_grid_thw"]
454
+ if "pixel_attention_mask" in forward_kwargs:
455
+ output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"]
456
+ if "image_sizes" in forward_kwargs:
457
+ output["image_sizes"] = forward_kwargs["image_sizes"]
458
+ if "token_type_ids" in forward_kwargs:
459
+ output["token_type_ids"] = forward_kwargs["token_type_ids"]
460
+ if images is not None:
461
+ output["num_images"] = num_images
462
+ return output
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gkd/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .gkd_config import GKDConfig
16
+ from .gkd_trainer import GKDTrainer
17
+
18
+
19
+ __all__ = ["GKDConfig", "GKDTrainer"]
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gkd/gkd_config.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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, field
16
+ from typing import Any
17
+
18
+ from ...trainer.sft_config import SFTConfig
19
+
20
+
21
+ @dataclass
22
+ class GKDConfig(SFTConfig):
23
+ """
24
+ Configuration class for [`experimental.gkd.GKDTrainer`].
25
+
26
+ This class includes only the parameters that are specific to GKD training. For a full list of training arguments,
27
+ please refer to the [`~transformers.TrainingArguments`] and [`SFTConfig`] documentation.
28
+
29
+ Args:
30
+ temperature (`float`, *optional*, defaults to `0.9`):
31
+ Temperature for sampling. The higher the temperature, the more random the completions.
32
+ lmbda (`float`, *optional*, defaults to `0.5`):
33
+ Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy
34
+ student-generated outputs).
35
+ beta (`float`, *optional*, defaults to `0.5`):
36
+ Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence loss. When
37
+ beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL Divergence.
38
+ max_new_tokens (`int`, *optional*, defaults to `128`):
39
+ Maximum number of tokens to generate per completion.
40
+ teacher_model_name_or_path (`str`, *optional*):
41
+ Model name or path of the teacher model. If `None`, the teacher model will be the same as the model being
42
+ trained.
43
+ teacher_model_init_kwargs (`dict[str, Any]`, *optional*):
44
+ Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model
45
+ from a string.
46
+ disable_dropout (`bool`, *optional*, defaults to `True`):
47
+ Whether to disable dropout in the model.
48
+ seq_kd (`bool`, *optional*, defaults to `False`):
49
+ Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised FT on
50
+ teacher-generated output).
51
+ """
52
+
53
+ _VALID_DICT_FIELDS = SFTConfig._VALID_DICT_FIELDS + ["teacher_model_init_kwargs"]
54
+
55
+ temperature: float = field(
56
+ default=0.9,
57
+ metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."},
58
+ )
59
+ lmbda: float = field(
60
+ default=0.5,
61
+ metadata={
62
+ "help": "Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy "
63
+ "student-generated outputs)."
64
+ },
65
+ )
66
+ beta: float = field(
67
+ default=0.5,
68
+ metadata={
69
+ "help": "Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence "
70
+ "loss. When beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL "
71
+ "Divergence."
72
+ },
73
+ )
74
+ max_new_tokens: int = field(
75
+ default=128,
76
+ metadata={"help": "Maximum number of tokens to generate per completion."},
77
+ )
78
+ teacher_model_name_or_path: str | None = field(
79
+ default=None,
80
+ metadata={
81
+ "help": "Model name or path of the teacher model. If `None`, the teacher model will be the same as the "
82
+ "model being trained."
83
+ },
84
+ )
85
+ teacher_model_init_kwargs: dict[str, Any] | str | None = field(
86
+ default=None,
87
+ metadata={
88
+ "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the "
89
+ "teacher model from a string."
90
+ },
91
+ )
92
+ disable_dropout: bool = field(
93
+ default=True,
94
+ metadata={"help": "Whether to disable dropouts in `model`."},
95
+ )
96
+ seq_kd: bool = field(
97
+ default=False,
98
+ metadata={
99
+ "help": "Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised "
100
+ "FT on teacher-generated output)."
101
+ },
102
+ )
103
+
104
+ def __post_init__(self):
105
+ super().__post_init__()
106
+ # check lmbda and beta are in the range [0, 1]
107
+ if self.lmbda < 0.0 or self.lmbda > 1.0:
108
+ raise ValueError("lmbda must be in the range [0.0, 1.0].")
109
+ if self.beta < 0.0 or self.beta > 1.0:
110
+ raise ValueError("beta must be in the range [0.0, 1.0].")
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gkd/gkd_trainer.py ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 random
16
+ import textwrap
17
+ from collections.abc import Callable
18
+ from typing import Any
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ from datasets import Dataset
24
+ from transformers import (
25
+ AutoModelForCausalLM,
26
+ BaseImageProcessor,
27
+ DataCollator,
28
+ FeatureExtractionMixin,
29
+ GenerationConfig,
30
+ PreTrainedModel,
31
+ PreTrainedTokenizerBase,
32
+ ProcessorMixin,
33
+ TrainerCallback,
34
+ )
35
+ from transformers.trainer_utils import EvalPrediction
36
+ from transformers.utils import is_liger_kernel_available, is_peft_available
37
+
38
+ from ...models import prepare_deepspeed
39
+ from ...models.utils import unwrap_model_for_generation
40
+ from ...trainer.sft_trainer import SFTTrainer
41
+ from ...trainer.utils import disable_dropout_in_model
42
+ from ..utils import DataCollatorForChatML, empty_cache
43
+ from .gkd_config import GKDConfig
44
+
45
+
46
+ if is_peft_available():
47
+ from peft import PeftConfig
48
+
49
+ if is_liger_kernel_available():
50
+ from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss
51
+
52
+
53
+ class GKDTrainer(SFTTrainer):
54
+ """Trainer for Generalized Knowledge Distillation (GKD) of language models.
55
+
56
+ For details on GKD, see the paper: [On-Policy Distillation of Language Models: Learning from Self-Generated
57
+ Mistakes](https://huggingface.co/papers/2306.13649).
58
+
59
+ Args:
60
+ model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `str`, *optional*):
61
+ Model to be trained, or the string identifier of the model to be instantiated from a pretrained model.
62
+ teacher_model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `str`, *optional*):
63
+ Teacher model for knowledge distillation, or the string identifier of the model to be instantiated from a
64
+ pretrained model.
65
+ args ([`experimental.gkd.GKDConfig`], *optional*):
66
+ Training arguments.
67
+ data_collator ([`~transformers.DataCollator`], *optional*):
68
+ Data collator to batch samples from the dataset. It defaults to a
69
+ [`experimental.utils.DataCollatorForChatML`] using the `processing_class`.
70
+ train_dataset ([`~datasets.Dataset`], *optional*):
71
+ Dataset for training.
72
+ eval_dataset ([`~datasets.Dataset`] or `dict` of [`~datasets.Dataset`], *optional*):
73
+ Dataset for evaluation.
74
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
75
+ Class to process the data.
76
+ compute_metrics (`Callable`, *optional*):
77
+ Function to compute metrics at evaluation. Must take in an [`~transformers.EvalPrediction`] and return a
78
+ dictionary string to float.
79
+ callbacks (`list` of [`~transformers.TrainerCallback`], *optional*):
80
+ Callbacks to use during training.
81
+ optimizers (`tuple` of `torch.optim.Optimizer` and `torch.optim.lr_scheduler.LambdaLR`, *optional*, defaults to `(None, None)`):
82
+ Tuple containing the optimizer and the learning rate scheduler to use for training.
83
+ preprocess_logits_for_metrics (`Callable`, *optional*):
84
+ Function to preprocess the logits before computing the metrics. Must take in the `logits` and `labels` and
85
+ return the logits to be used for metrics computation.
86
+ peft_config ([`~peft.PeftConfig`], *optional*):
87
+ PEFT configuration to use PEFT for training. If `None`, PEFT is not used. If provided, the `model` will be
88
+ wrapped with the specified PEFT adapter.
89
+ formatting_func (`Callable`, *optional*):
90
+ Function to format the dataset. Must take in an example and return an example.
91
+ """
92
+
93
+ _tag_names = ["trl", "gkd"]
94
+ _name = "GKD"
95
+ _paper = {
96
+ "title": "On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes",
97
+ "id": "2306.13649",
98
+ # docstyle-ignore
99
+ "citation": textwrap.dedent("""\
100
+ @inproceedings{agarwal2024on-policy,
101
+ title = {{On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes}},
102
+ author = {Rishabh Agarwal and Nino Vieillard and Yongchao Zhou and Piotr Stanczyk and Sabela Ramos Garea and Matthieu Geist and Olivier Bachem},
103
+ year = 2024,
104
+ booktitle = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024},
105
+ publisher = {OpenReview.net},
106
+ url = {https://openreview.net/forum?id=3zKtaqxLhW},
107
+ }"""),
108
+ }
109
+
110
+ def __init__(
111
+ self,
112
+ model: PreTrainedModel | nn.Module | str | None = None,
113
+ teacher_model: PreTrainedModel | nn.Module | str = None,
114
+ args: GKDConfig | None = None,
115
+ data_collator: DataCollator | None = None, # type: ignore
116
+ train_dataset: Dataset | None = None,
117
+ eval_dataset: Dataset | dict[str, Dataset] | None = None,
118
+ processing_class: PreTrainedTokenizerBase
119
+ | BaseImageProcessor
120
+ | FeatureExtractionMixin
121
+ | ProcessorMixin
122
+ | None = None,
123
+ compute_metrics: Callable[[EvalPrediction], dict] | None = None,
124
+ callbacks: list[TrainerCallback] | None = None,
125
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
126
+ preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
127
+ peft_config: "PeftConfig | None" = None,
128
+ formatting_func: Callable | None = None,
129
+ ):
130
+ # Ensure Trainer does not drop non-signature columns used by the collator (e.g., "prompts")
131
+ args.remove_unused_columns = False
132
+ # Respect a user-provided data_collator; otherwise, provide a ChatML collator that
133
+ if data_collator is None:
134
+ data_collator = DataCollatorForChatML(tokenizer=processing_class, max_length=args.max_length)
135
+
136
+ # Ensure SFTTrainer does not pre-process the dataset when using a ChatML collator,
137
+ # so that raw conversational fields (e.g., "messages") remain available to the collator.
138
+ if args.dataset_kwargs is None:
139
+ args.dataset_kwargs = {"skip_prepare_dataset": True}
140
+ else:
141
+ args.dataset_kwargs["skip_prepare_dataset"] = True
142
+
143
+ # Liger fused GKD loss (JSD)
144
+ self.use_liger_gkd_loss = False
145
+ if args.use_liger_kernel:
146
+ self.liger_jsd_loss = LigerFusedLinearJSDLoss(
147
+ beta=args.beta,
148
+ ignore_index=-100,
149
+ temperature=args.temperature,
150
+ compiled=False,
151
+ )
152
+ self.use_liger_gkd_loss = True
153
+
154
+ super().__init__(
155
+ model,
156
+ args=args,
157
+ data_collator=data_collator,
158
+ train_dataset=train_dataset,
159
+ eval_dataset=eval_dataset,
160
+ processing_class=processing_class,
161
+ compute_metrics=compute_metrics,
162
+ callbacks=callbacks,
163
+ optimizers=optimizers,
164
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
165
+ peft_config=peft_config,
166
+ formatting_func=formatting_func,
167
+ )
168
+
169
+ if args.teacher_model_init_kwargs is None:
170
+ teacher_model_init_kwargs = {}
171
+ elif not isinstance(teacher_model, str):
172
+ raise ValueError(
173
+ "You passed teacher_model_init_kwargs to the GKDConfig, but your teacher_model is already instantiated."
174
+ )
175
+ else:
176
+ teacher_model_init_kwargs = args.teacher_model_init_kwargs
177
+ teacher_model_init_kwargs["dtype"] = (
178
+ teacher_model_init_kwargs["dtype"]
179
+ if teacher_model_init_kwargs["dtype"] in ["auto", None]
180
+ else getattr(torch, teacher_model_init_kwargs["dtype"])
181
+ )
182
+
183
+ if isinstance(teacher_model, str):
184
+ teacher_model = AutoModelForCausalLM.from_pretrained(teacher_model, **teacher_model_init_kwargs)
185
+
186
+ # Disable dropout in the model
187
+ if args.disable_dropout:
188
+ disable_dropout_in_model(self.model)
189
+
190
+ if self.is_deepspeed_enabled:
191
+ self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator)
192
+ else:
193
+ self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True)
194
+
195
+ self.lmbda = args.lmbda
196
+ self.beta = args.beta
197
+ self.temperature = args.temperature
198
+ self.seq_kd = args.seq_kd
199
+
200
+ generation_kwargs = {
201
+ "max_new_tokens": args.max_new_tokens,
202
+ "temperature": args.temperature,
203
+ "do_sample": True,
204
+ "top_k": 0,
205
+ "use_cache": False if args.gradient_checkpointing else True,
206
+ "pad_token_id": self.processing_class.pad_token_id,
207
+ }
208
+ self.generation_config = GenerationConfig(**generation_kwargs)
209
+ # Keep training-specific generation kwargs to overwrite model's original generation config
210
+ self.generation_kwargs = generation_kwargs
211
+ # Set custom EOS tokens if they are specified by the model's generation
212
+ # config. This is important for models with the Llama 3 chat template,
213
+ # which use special tokens <|eot_id|> and <|eom_id|> to mark the end of
214
+ # turns or messages.
215
+ if (
216
+ hasattr(self.model.generation_config, "eos_token_id")
217
+ and self.model.generation_config.eos_token_id is not None
218
+ ):
219
+ self.generation_config.eos_token_id = self.model.generation_config.eos_token_id
220
+
221
+ @staticmethod
222
+ def generalized_jsd_loss(
223
+ student_logits, teacher_logits, labels=None, beta=0.5, temperature=1.0, reduction="batchmean"
224
+ ):
225
+ """
226
+ Compute the generalized Jensen-Shannon Divergence loss for knowledge distillation using F.kl_div. See Eq. (1)
227
+ of https://huggingface.co/papers/2306.13649 for the definition.
228
+
229
+ Args:
230
+ student_logits:
231
+ Tensor of shape (batch_size, sequence_length, vocab_size)
232
+ teacher_logits:
233
+ Tensor of shape (batch_size, sequence_length, vocab_size)
234
+ labels:
235
+ Tensor of shape (batch_size, sequence_length) with -100 for padding tokens to ignore when computing
236
+ loss
237
+ beta:
238
+ Interpolation coefficient between 0 and 1 (default: 0.5)
239
+ temperature:
240
+ Softmax temperature (default: 1.0)
241
+ reduction:
242
+ Specifies the reduction to apply to the output (default: 'batchmean')
243
+
244
+ Returns:
245
+ loss: Scalar tensor with the generalized JSD loss
246
+ """
247
+
248
+ # Apply temperature scaling
249
+ student_logits = student_logits / temperature
250
+ teacher_logits = teacher_logits / temperature
251
+
252
+ # Compute log probabilities for student and probabilities for teacher
253
+ student_log_probs = F.log_softmax(student_logits, dim=-1)
254
+ teacher_log_probs = F.log_softmax(teacher_logits, dim=-1)
255
+
256
+ if beta == 0:
257
+ jsd = F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True)
258
+ elif beta == 1:
259
+ jsd = F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True)
260
+ else:
261
+ # Compute the log of the mixture distribution
262
+ # log(a + b) = log(exp(log(a)) + exp(log(b))) -> for mixture
263
+ beta = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device)
264
+ mixture_log_probs = torch.logsumexp(
265
+ torch.stack([student_log_probs + torch.log1p(-beta), teacher_log_probs + torch.log(beta)]),
266
+ dim=0,
267
+ )
268
+
269
+ # Compute KL divergences using F.kl_div
270
+ # PyTorch differs from the standard mathematical definition, so the order of the probability distributions is swapped compared to that defined in the paper.
271
+ kl_teacher = F.kl_div(mixture_log_probs, teacher_log_probs, reduction="none", log_target=True)
272
+ kl_student = F.kl_div(mixture_log_probs, student_log_probs, reduction="none", log_target=True)
273
+
274
+ # Compute the Generalized Jensen-Shannon Divergence
275
+ jsd = beta * kl_teacher + (1 - beta) * kl_student
276
+
277
+ # Masking
278
+ if labels is not None:
279
+ mask = labels != -100
280
+ jsd = jsd[mask]
281
+
282
+ # Apply reduction
283
+ if reduction == "batchmean":
284
+ return jsd.sum() / mask.sum() if labels is not None else jsd.sum() / jsd.size(0)
285
+ elif reduction == "sum":
286
+ return jsd.sum()
287
+ elif reduction == "mean":
288
+ return jsd.mean()
289
+ else:
290
+ return jsd
291
+
292
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
293
+ if self.use_liger_gkd_loss:
294
+ # Forward only through the base models (avoid lm_head to save memory)
295
+ unwrapped_student = self.accelerator.unwrap_model(model)
296
+ if hasattr(unwrapped_student, "get_decoder") and unwrapped_student.get_decoder() is not None:
297
+ base_student = unwrapped_student.get_decoder()
298
+ else:
299
+ base_student = getattr(
300
+ unwrapped_student, getattr(unwrapped_student, "base_model_prefix", "model"), unwrapped_student
301
+ )
302
+
303
+ student_outputs = base_student(
304
+ input_ids=inputs["input_ids"],
305
+ attention_mask=inputs["attention_mask"],
306
+ use_cache=False,
307
+ )
308
+
309
+ self.teacher_model.eval()
310
+ unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model)
311
+ if hasattr(unwrapped_teacher, "get_decoder") and unwrapped_teacher.get_decoder() is not None:
312
+ base_teacher = unwrapped_teacher.get_decoder()
313
+ else:
314
+ base_teacher = getattr(
315
+ unwrapped_teacher, getattr(unwrapped_teacher, "base_model_prefix", "model"), unwrapped_teacher
316
+ )
317
+ with torch.no_grad():
318
+ teacher_outputs = base_teacher(
319
+ input_ids=inputs["input_ids"],
320
+ attention_mask=inputs["attention_mask"],
321
+ use_cache=False,
322
+ )
323
+
324
+ # hidden states (shifted)
325
+ student_hidden = student_outputs.last_hidden_state[:, :-1]
326
+ teacher_hidden = teacher_outputs.last_hidden_state[:, :-1]
327
+
328
+ # Release full outputs to free memory
329
+ del student_outputs, teacher_outputs
330
+
331
+ # labels mask and labels (shifted)
332
+ labels_mask = inputs["labels"] != -100
333
+ masked_input_ids = torch.where(
334
+ labels_mask, inputs["input_ids"], torch.full_like(inputs["input_ids"], -100)
335
+ )
336
+ true_labels = masked_input_ids[:, 1:].contiguous()
337
+
338
+ # Release intermediate tensors
339
+ del labels_mask, masked_input_ids
340
+
341
+ # heads
342
+ student_head = unwrapped_student.get_output_embeddings()
343
+ teacher_head = unwrapped_teacher.get_output_embeddings()
344
+
345
+ # liger fused jsd loss
346
+ loss = self.liger_jsd_loss(
347
+ student_input=student_hidden,
348
+ student_weight=student_head.weight,
349
+ teacher_input=teacher_hidden,
350
+ teacher_weight=teacher_head.weight,
351
+ true_labels=true_labels,
352
+ student_bias=getattr(student_head, "bias", None),
353
+ teacher_bias=getattr(teacher_head, "bias", None),
354
+ )
355
+
356
+ # Release hidden states after loss computation
357
+ del student_hidden, teacher_hidden, true_labels
358
+ else:
359
+ # compute student output
360
+ student_outputs = model(
361
+ input_ids=inputs["input_ids"],
362
+ attention_mask=inputs["attention_mask"],
363
+ )
364
+
365
+ # compute teacher output in eval mode
366
+ self.teacher_model.eval()
367
+ with torch.no_grad():
368
+ teacher_outputs = self.teacher_model(
369
+ input_ids=inputs["input_ids"],
370
+ attention_mask=inputs["attention_mask"],
371
+ )
372
+
373
+ # slice the logits for the generated tokens using the inputs["prompts"] lengths
374
+ prompt_lengths = inputs["prompts"].shape[1]
375
+ shifted_student_logits = student_outputs.logits[:, prompt_lengths - 1 : -1, :]
376
+ shifted_teacher_logits = teacher_outputs.logits[:, prompt_lengths - 1 : -1, :]
377
+ shifted_labels = inputs["labels"][:, prompt_lengths:]
378
+
379
+ # compute loss
380
+ loss = self.generalized_jsd_loss(
381
+ student_logits=shifted_student_logits,
382
+ teacher_logits=shifted_teacher_logits,
383
+ labels=shifted_labels,
384
+ beta=self.beta,
385
+ )
386
+
387
+ # empty cache
388
+ empty_cache()
389
+
390
+ # Return loss
391
+ return (loss, student_outputs) if return_outputs else loss
392
+
393
+ @staticmethod
394
+ def generate_on_policy_outputs(model, inputs, generation_config, pad_token_id=None):
395
+ # Generate output with respect to the prompt-only
396
+ generated_outputs = model.generate(
397
+ input_ids=inputs["prompts"],
398
+ attention_mask=inputs.get("prompt_attention_mask", None),
399
+ generation_config=generation_config,
400
+ return_dict_in_generate=True,
401
+ )
402
+
403
+ # Get the generated token IDs
404
+ generated_tokens = generated_outputs.sequences
405
+ # Calculate new attention mask
406
+ new_attention_mask = torch.ones_like(generated_tokens)
407
+ new_labels = generated_tokens.clone()
408
+
409
+ # If there's pad_token_id, set attention mask to 0 for padding tokens
410
+ if pad_token_id is not None:
411
+ new_labels[new_labels == pad_token_id] = -100
412
+ new_attention_mask[generated_tokens == pad_token_id] = 0
413
+
414
+ return generated_tokens, new_attention_mask, new_labels
415
+
416
+ def training_step(
417
+ self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None
418
+ ) -> torch.Tensor:
419
+ """
420
+ Perform a training step for the Generalized Knowledge Distillation (GKD) model.
421
+
422
+ This method implements the on-policy learning approach described in the GKD paper. With probability
423
+ `self.lmbda`, it generates new responses using the student model, which are then used for training instead of
424
+ the original inputs.
425
+ """
426
+ if self.seq_kd:
427
+ with (
428
+ unwrap_model_for_generation(
429
+ self.teacher_model,
430
+ self.accelerator,
431
+ generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
432
+ ) as unwrapped_model
433
+ ):
434
+ new_input_ids, new_attention_mask, new_labels = self.generate_on_policy_outputs(
435
+ unwrapped_model, inputs, self.generation_config, self.processing_class.pad_token_id
436
+ )
437
+ inputs["input_ids"] = new_input_ids
438
+ inputs["attention_mask"] = new_attention_mask
439
+ inputs["labels"] = new_labels
440
+ if random.random() <= self.lmbda:
441
+ with (
442
+ unwrap_model_for_generation(
443
+ model,
444
+ self.accelerator,
445
+ generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
446
+ ) as unwrapped_model
447
+ ):
448
+ new_input_ids, new_attention_mask, new_labels = self.generate_on_policy_outputs(
449
+ unwrapped_model, inputs, self.generation_config, self.processing_class.pad_token_id
450
+ )
451
+ inputs["input_ids"] = new_input_ids
452
+ inputs["attention_mask"] = new_attention_mask
453
+ inputs["labels"] = new_labels
454
+
455
+ loss = super().training_step(model, inputs, num_items_in_batch)
456
+ return loss
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gold/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .gold_config import GOLDConfig
16
+ from .gold_trainer import GOLDTrainer
17
+
18
+
19
+ __all__ = ["GOLDConfig", "GOLDTrainer"]
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gold/gold.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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
+ # /// script
16
+ # dependencies = [
17
+ # "trl @ git+https://github.com/huggingface/trl.git",
18
+ # "peft",
19
+ # "trackio",
20
+ # ]
21
+ # ///
22
+
23
+ # docstyle-ignore
24
+ """
25
+ # Full training:
26
+ python trl/experimental/gold/gold.py \
27
+ --model_name_or_path meta-llama/Llama-3.2-1B-Instruct \
28
+ --teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \
29
+ --dataset_name trl-lib/chatbot_arena_completions \
30
+ --learning_rate 2e-5 \
31
+ --per_device_train_batch_size 4 \
32
+ --gradient_accumulation_steps 8 \
33
+ --output_dir gold-model \
34
+ --num_train_epochs 1 \
35
+ --push_to_hub
36
+
37
+ # LoRA:
38
+ python trl/experimental/gold/gold.py \
39
+ --model_name_or_path meta-llama/Llama-3.2-1B-Instruct \
40
+ --teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \
41
+ --dataset_name trl-lib/chatbot_arena_completions \
42
+ --learning_rate 2e-4 \
43
+ --per_device_train_batch_size 4 \
44
+ --gradient_accumulation_steps 8 \
45
+ --output_dir gold-model \
46
+ --num_train_epochs 1 \
47
+ --push_to_hub \
48
+ --use_peft \
49
+ --lora_r 64 \
50
+ --lora_alpha 16
51
+ """
52
+
53
+ import logging
54
+
55
+ from datasets import load_dataset
56
+ from transformers import AutoTokenizer, GenerationConfig
57
+
58
+ from trl import (
59
+ LogCompletionsCallback,
60
+ ModelConfig,
61
+ ScriptArguments,
62
+ TrlParser,
63
+ get_kbit_device_map,
64
+ get_peft_config,
65
+ get_quantization_config,
66
+ )
67
+ from trl.experimental.gold.gold_config import GOLDConfig
68
+ from trl.experimental.gold.gold_trainer import GOLDTrainer
69
+
70
+
71
+ logger = logging.getLogger(__name__)
72
+
73
+
74
+ if __name__ == "__main__":
75
+ parser = TrlParser((ScriptArguments, GOLDConfig, ModelConfig))
76
+ script_args, training_args, model_args = parser.parse_args_and_config()
77
+
78
+ ################
79
+ # Model & Tokenizer
80
+ ################
81
+ quantization_config = get_quantization_config(model_args)
82
+ model_kwargs = dict(
83
+ revision=model_args.model_revision,
84
+ trust_remote_code=model_args.trust_remote_code,
85
+ attn_implementation=model_args.attn_implementation,
86
+ torch_dtype=model_args.dtype,
87
+ use_cache=False if training_args.gradient_checkpointing else True,
88
+ device_map=get_kbit_device_map() if quantization_config is not None else None,
89
+ quantization_config=quantization_config,
90
+ )
91
+ training_args.model_init_kwargs = model_kwargs
92
+
93
+ if training_args.teacher_tokenizer_name_or_path is None and training_args.use_uld_loss:
94
+ training_args.teacher_tokenizer_name_or_path = training_args.teacher_model_name_or_path
95
+ teacher_model_kwargs = dict(
96
+ revision=training_args.teacher_model_revision,
97
+ trust_remote_code=model_args.trust_remote_code,
98
+ attn_implementation=model_args.attn_implementation,
99
+ torch_dtype=model_args.dtype,
100
+ use_cache=True,
101
+ device_map=get_kbit_device_map() if quantization_config is not None else None,
102
+ quantization_config=quantization_config,
103
+ )
104
+ if training_args.teacher_model_init_kwargs is not None:
105
+ teacher_model_kwargs.update(training_args.teacher_model_init_kwargs)
106
+ training_args.teacher_model_init_kwargs = teacher_model_kwargs
107
+
108
+ tokenizer = AutoTokenizer.from_pretrained(
109
+ model_args.model_name_or_path,
110
+ revision=model_args.model_revision,
111
+ trust_remote_code=model_args.trust_remote_code,
112
+ )
113
+ if tokenizer.pad_token is None:
114
+ tokenizer.pad_token = tokenizer.eos_token
115
+
116
+ ################
117
+ # Dataset
118
+ ################
119
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
120
+
121
+ ################
122
+ # Training
123
+ ################
124
+ eval_dataset = None
125
+ if training_args.eval_strategy != "no":
126
+ if script_args.dataset_test_split in dataset:
127
+ eval_dataset = dataset[script_args.dataset_test_split]
128
+ elif "validation" in dataset:
129
+ eval_dataset = dataset["validation"]
130
+ elif "dev" in dataset:
131
+ eval_dataset = dataset["dev"]
132
+
133
+ trainer = GOLDTrainer(
134
+ model=model_args.model_name_or_path,
135
+ teacher_model=training_args.teacher_model_name_or_path,
136
+ args=training_args,
137
+ train_dataset=dataset[script_args.dataset_train_split],
138
+ eval_dataset=eval_dataset,
139
+ processing_class=tokenizer,
140
+ peft_config=get_peft_config(model_args),
141
+ )
142
+
143
+ if training_args.eval_strategy != "no":
144
+ generation_config = GenerationConfig(
145
+ max_new_tokens=training_args.max_completion_length, do_sample=True, temperature=training_args.temperature
146
+ )
147
+ completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8)
148
+ trainer.add_callback(completions_callback)
149
+
150
+ trainer.train()
151
+
152
+ # Save and push to hub
153
+ trainer.save_model(training_args.output_dir)
154
+ if training_args.push_to_hub:
155
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gold/gold_config.py ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 warnings
16
+ from dataclasses import dataclass, field
17
+ from typing import Any
18
+
19
+ from ...trainer.sft_config import SFTConfig
20
+
21
+
22
+ @dataclass
23
+ class GOLDConfig(SFTConfig):
24
+ r"""
25
+ Configuration class for [`GOLDTrainer`].
26
+
27
+ This class includes only the parameters that are specific to GOLD training. For a full list of training arguments,
28
+ please refer to the [`~transformers.TrainingArguments`] and [`SFTConfig`] documentation.
29
+
30
+ Args:
31
+ temperature (`float`, *optional*, defaults to `0.9`):
32
+ Temperature for sampling. The higher the temperature, the more random the completions.
33
+ lmbda (`float`, *optional*, defaults to `0.5`):
34
+ Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy
35
+ student-generated outputs).
36
+ beta (`float`, *optional*, defaults to `0.5`):
37
+ Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence loss. When
38
+ beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL Divergence.
39
+ max_completion_length (`int`, *optional*, defaults to `128`):
40
+ Maximum number of tokens to generate per completion.
41
+ teacher_model_name_or_path (`str`, *optional*):
42
+ Model name or path of the teacher model. If `None`, the teacher model will be the same as the model being
43
+ trained.
44
+ teacher_model_revision (`str` or `None`, *optional*, defaults to `None`):
45
+ Model revision of the teacher model (e.g., branch name, tag, or commit hash). If `None`, the default
46
+ revision is used.
47
+ teacher_model_init_kwargs (`dict[str, Any]`, *optional*):
48
+ Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model
49
+ from a string.
50
+ teacher_tokenizer_name_or_path (`str`, *optional*):
51
+ Tokenizer name or path for the teacher model. If None when using ULD loss, will use the same tokenizer as
52
+ the student model (not recommended for cross-tokenizer distillation).
53
+ disable_dropout (`bool`, *optional*, defaults to `True`):
54
+ Whether to disable dropout in the model.
55
+ seq_kd (`bool`, *optional*, defaults to `False`):
56
+ Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised FT on
57
+ teacher-generated output).
58
+ num_generations (`int`, *optional*, defaults to `1`):
59
+ Number of generations per prompt. Each prompt is repeated this many times in the generation batch.
60
+ generation_batch_size (`int` or `None`, *optional*, defaults to `None`):
61
+ Number of unique prompts per worker per optimizer step. If `None`, it is computed from
62
+ `(per_device_train_batch_size * gradient_accumulation_steps) // num_generations`.
63
+ use_uld_loss (`bool`, *optional*, defaults to `False`):
64
+ Whether to use Universal Logit Distillation (ULD) loss instead of Generalized Jensen-Shannon Divergence
65
+ loss.
66
+ uld_crossentropy_weight (`float`, *optional*, defaults to `0.0`):
67
+ Weight for the cross-entropy loss component in ULD loss. If 0, only ULD distillation loss is used.
68
+ uld_distillation_weight (`float`, *optional*, defaults to `1.0`):
69
+ Weight for the distillation loss component in ULD loss.
70
+ uld_student_temperature (`float`, *optional*, defaults to `1.0`):
71
+ Temperature for student logits in ULD loss computation.
72
+ uld_teacher_temperature (`float`, *optional*, defaults to `1.0`):
73
+ Temperature for teacher logits in ULD loss computation.
74
+ uld_skip_student_eos (`bool`, *optional*, defaults to `True`):
75
+ Whether to skip EOS token for student in ULD loss computation.
76
+ uld_skip_teacher_eos (`bool`, *optional*, defaults to `True`):
77
+ Whether to skip EOS token for teacher in ULD loss computation.
78
+ use_vllm (`bool`, *optional*, defaults to `False`):
79
+ Whether to use vLLM for generating completions from the student model. Requires `vllm` to be installed.
80
+ vllm_mode (`str`, *optional*, defaults to `"colocate"`):
81
+ Mode for student vLLM integration. Either `"server"` (connect to a running TRL vLLM server) or `"colocate"`
82
+ (run vLLM in the same process).
83
+ vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
84
+ Host of the vLLM server for the student model (if `vllm_mode="server"`).
85
+ vllm_server_port (`int`, *optional*, defaults to `8001`):
86
+ Port of the vLLM server for the student model (if `vllm_mode="server"`).
87
+ vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
88
+ Timeout for connecting to the student vLLM server (if `vllm_mode="server"`).
89
+ vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.9`):
90
+ GPU memory utilization for the colocated student vLLM engine (if `vllm_mode="colocate"`). It is recommended
91
+ to set this to a low value if the student and teacher models share the same GPU.
92
+ vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
93
+ Tensor parallel size for the colocated student vLLM engine (if `vllm_mode="colocate"`).
94
+ vllm_structured_outputs_regex (`str`, *optional*):
95
+ Regex for vLLM structured outputs for the student model.
96
+ vllm_server_base_url (`str`, *optional*):
97
+ Base URL for the vLLM server (e.g., `"http://localhost:8001"`). If provided, `vllm_server_host` and
98
+ `vllm_server_port` are ignored.
99
+ vllm_group_port (`int`, *optional*, defaults to `51216`):
100
+ Port for the vLLM weight-update group (NCCL communicator). Unless the port is occupied, there is no need to
101
+ change it.
102
+ vllm_max_model_length (`int`, *optional*):
103
+ Maximum model sequence length for the colocated vLLM engine when `vllm_mode="colocate"`. Defaults to the
104
+ model's maximum context length.
105
+ vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
106
+ Model implementation backend to use in vLLM. Use `"vllm"` (default) or `"transformers"`.
107
+ vllm_sync_frequency (`int`, *optional*, defaults to `1`):
108
+ Frequency (in training steps) to synchronize student model weights to vLLM engine. Set to 1 to sync after
109
+ every step.
110
+ vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`):
111
+ Enable vLLM sleep mode to offload student weights/cache during the optimizer step. Keeps GPU memory usage
112
+ low, but waking the engine adds host–device transfer latency.
113
+ """
114
+
115
+ _VALID_DICT_FIELDS = SFTConfig._VALID_DICT_FIELDS + ["teacher_model_init_kwargs"]
116
+
117
+ # Parameters whose default values are overridden from TrainingArguments
118
+ learning_rate: float = field(
119
+ default=1e-7,
120
+ metadata={"help": "The initial learning rate for AdamW."},
121
+ )
122
+
123
+ # GOLD-specific parameters
124
+ temperature: float = field(
125
+ default=0.9,
126
+ metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."},
127
+ )
128
+ top_p: float = field(
129
+ default=0.95,
130
+ metadata={
131
+ "help": "If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to "
132
+ "`top_p` or higher are kept for generation."
133
+ },
134
+ )
135
+ top_k: int = field(
136
+ default=0,
137
+ metadata={
138
+ "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, "
139
+ "top-k-filtering is disabled and all tokens are considered."
140
+ },
141
+ )
142
+ lmbda: float = field(
143
+ default=0.5,
144
+ metadata={
145
+ "help": "Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy "
146
+ "student-generated outputs)."
147
+ },
148
+ )
149
+ beta: float = field(
150
+ default=0.5,
151
+ metadata={
152
+ "help": "Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence "
153
+ "loss. When beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL "
154
+ "Divergence."
155
+ },
156
+ )
157
+ max_completion_length: int = field(
158
+ default=128,
159
+ metadata={"help": "Maximum number of tokens to generate per completion."},
160
+ )
161
+ teacher_model_name_or_path: str | None = field(
162
+ default=None,
163
+ metadata={
164
+ "help": "Model name or path of the teacher model. If `None`, the teacher model will be the same as the "
165
+ "model being trained."
166
+ },
167
+ )
168
+ teacher_model_revision: str | None = field(
169
+ default=None,
170
+ metadata={
171
+ "help": "Model revision of the teacher model (e.g., branch name, tag, or commit hash). If `None`, the "
172
+ "default revision is used."
173
+ },
174
+ )
175
+ teacher_model_init_kwargs: dict[str, Any] | str | None = field(
176
+ default=None,
177
+ metadata={
178
+ "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the "
179
+ "teacher model from a string."
180
+ },
181
+ )
182
+ teacher_tokenizer_name_or_path: str | None = field(
183
+ default=None,
184
+ metadata={
185
+ "help": "Tokenizer name or path for the teacher model. If None when using ULD loss, will use the same "
186
+ "tokenizer as the student model (not recommended for cross-tokenizer distillation)."
187
+ },
188
+ )
189
+ disable_dropout: bool = field(
190
+ default=True,
191
+ metadata={"help": "Whether to disable dropouts in `model`."},
192
+ )
193
+ seq_kd: bool = field(
194
+ default=False,
195
+ metadata={
196
+ "help": "Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised "
197
+ "FT on teacher-generated output)."
198
+ },
199
+ )
200
+ num_generations: int = field(
201
+ default=1,
202
+ metadata={
203
+ "help": "Number of generations per prompt. Increasing this will decrease the number of unique prompts per optimization step."
204
+ },
205
+ )
206
+ generation_batch_size: int | None = field(
207
+ default=None,
208
+ metadata={
209
+ "help": "Number of unique prompts per worker per optimizer step. "
210
+ "If None, computed from (per_device_train_batch_size * gradient_accumulation_steps) // num_generations."
211
+ },
212
+ )
213
+
214
+ # ULD Loss parameters
215
+ use_uld_loss: bool = field(
216
+ default=False,
217
+ metadata={
218
+ "help": "Whether to use Universal Logit Distillation (ULD) loss instead of Generalized Jensen-Shannon Divergence loss."
219
+ },
220
+ )
221
+ use_extended_uld: bool = field(
222
+ default=True,
223
+ metadata={
224
+ "help": (
225
+ "Whether to enable extended ULD alignment that uses tokenizers to align and merge token "
226
+ "probabilities across student and teacher tokenizations. When True, the trainer will compute "
227
+ "token mappings and merge probabilities for split tokens; when False, ULD will use simple "
228
+ "positional truncation like in the original ULD paper."
229
+ )
230
+ },
231
+ )
232
+ uld_use_hybrid_loss: bool = field(
233
+ default=False,
234
+ metadata={
235
+ "help": (
236
+ "Whether to use a hybrid loss that combines ULD loss and JSD loss. When True, the final loss is a "
237
+ "a combination of JSD for known token mappings and ULD for unknown token mappings."
238
+ )
239
+ },
240
+ )
241
+ uld_hybrid_matched_weight: float | None = field(
242
+ default=None,
243
+ metadata={
244
+ "help": (
245
+ "Weight for the matched token loss component when using hybrid ULD + JSD loss. This weight scales "
246
+ "the JSD loss computed over tokens that have a direct mapping between student and teacher "
247
+ "tokenizations. If None, uses adaptive weighting based on vocabulary overlap. Must be set together "
248
+ "with uld_hybrid_unmatched_weight (both None or both float)."
249
+ )
250
+ },
251
+ )
252
+ uld_hybrid_unmatched_weight: float | None = field(
253
+ default=None,
254
+ metadata={
255
+ "help": (
256
+ "Weight for the unmatched token loss component when using hybrid ULD + JSD loss. This weight scales "
257
+ "the ULD loss computed over tokens that do not have a direct mapping between student and teacher "
258
+ "tokenizations. If None, uses adaptive weighting based on vocabulary overlap. Must be set together "
259
+ "with uld_hybrid_matched_weight (both None or both float)."
260
+ )
261
+ },
262
+ )
263
+ uld_crossentropy_weight: float = field(
264
+ default=0.0,
265
+ metadata={"help": "Weight for the cross-entropy loss component in ULD loss."},
266
+ )
267
+ uld_distillation_weight: float = field(
268
+ default=1.0,
269
+ metadata={"help": "Weight for the distillation loss component in ULD loss."},
270
+ )
271
+ uld_student_temperature: float = field(
272
+ default=1.0,
273
+ metadata={"help": "Temperature for student logits in ULD loss computation."},
274
+ )
275
+ uld_teacher_temperature: float = field(
276
+ default=1.0,
277
+ metadata={"help": "Temperature for teacher logits in ULD loss computation."},
278
+ )
279
+
280
+ uld_skip_student_eos: bool = field(
281
+ default=True,
282
+ metadata={"help": "Whether to skip EOS token for student in ULD loss computation."},
283
+ )
284
+ uld_skip_teacher_eos: bool = field(
285
+ default=True,
286
+ metadata={"help": "Whether to skip EOS token for teacher in ULD loss computation."},
287
+ )
288
+
289
+ # transformers paged attention
290
+ use_transformers_paged: bool = field(
291
+ default=False,
292
+ metadata={
293
+ "help": "Whether to use the `transformers` paged implementation for generation. If set to `True`, the "
294
+ "`transformers` paged implementation will be used for generation instead of the default padded "
295
+ "implementation."
296
+ },
297
+ )
298
+
299
+ # vLLM parameters
300
+ use_vllm: bool = field(
301
+ default=False,
302
+ metadata={"help": "Whether to use vLLM for generating completions. Requires `vllm` to be installed."},
303
+ )
304
+ vllm_mode: str = field(
305
+ default="colocate",
306
+ metadata={
307
+ "help": 'Mode for vLLM integration. Either "server" (connect to a running TRL vLLM server) or "colocate" (run vLLM in the same process).'
308
+ },
309
+ )
310
+ vllm_server_base_url: str | None = field(
311
+ default=None,
312
+ metadata={
313
+ "help": 'Base URL for the vLLM server (e.g., "http://localhost:8001"). If provided, vllm_server_host and vllm_server_port are ignored.'
314
+ },
315
+ )
316
+ vllm_server_host: str = field(
317
+ default="0.0.0.0",
318
+ metadata={"help": 'Host of the vLLM server when `vllm_mode="server"`.'},
319
+ )
320
+ vllm_server_port: int = field(
321
+ default=8001,
322
+ metadata={"help": 'Port of the vLLM server when `vllm_mode="server"`.'},
323
+ )
324
+ vllm_server_timeout: float = field(
325
+ default=240.0,
326
+ metadata={"help": 'Timeout (in seconds) for connecting to the vLLM server when `vllm_mode="server"`.'},
327
+ )
328
+ vllm_group_port: int = field(
329
+ default=51216,
330
+ metadata={"help": "Port for the vLLM weight-update group (NCCL communicator)."},
331
+ )
332
+ vllm_gpu_memory_utilization: float = field(
333
+ default=0.9,
334
+ metadata={
335
+ "help": 'GPU memory utilization for the colocated vLLM engine when `vllm_mode="colocate"`. Lower values reduce contention when sharing a device with the student/teacher models.'
336
+ },
337
+ )
338
+ vllm_tensor_parallel_size: int = field(
339
+ default=1,
340
+ metadata={"help": 'Tensor parallel size for the colocated vLLM engine when `vllm_mode="colocate"`.'},
341
+ )
342
+ vllm_max_model_length: int | None = field(
343
+ default=None,
344
+ metadata={
345
+ "help": 'Maximum model sequence length for the colocated vLLM engine when `vllm_mode="colocate"`. Defaults to the model\'s maximum context length.'
346
+ },
347
+ )
348
+ vllm_model_impl: str = field(
349
+ default="vllm",
350
+ metadata={"help": 'Model implementation backend to use in vLLM. Use "vllm" (default) or "transformers".'},
351
+ )
352
+ vllm_structured_outputs_regex: str | None = field(
353
+ default=None,
354
+ metadata={"help": "Regex pattern used for vLLM structured outputs (optional)."},
355
+ )
356
+ vllm_sync_frequency: int = field(
357
+ default=1,
358
+ metadata={
359
+ "help": "Frequency (in training steps) to synchronize model weights to the vLLM engine. Set to 1 to sync after every step."
360
+ },
361
+ )
362
+ vllm_enable_sleep_mode: bool = field(
363
+ default=False,
364
+ metadata={
365
+ "help": "Enable vLLM sleep mode to offload student weights/cache during the optimizer step. Keeps GPU "
366
+ "memory usage low, but waking the engine adds host–device transfer latency."
367
+ },
368
+ )
369
+ # Parameters that control the logging
370
+ log_completions: bool = field(
371
+ default=False,
372
+ metadata={
373
+ "help": "Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is "
374
+ "installed, it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`."
375
+ },
376
+ )
377
+ log_completions_steps: int = field(
378
+ default=100,
379
+ metadata={
380
+ "help": "Number of steps between logging (prompt, completion) pairs. Only used if `log_completions` is "
381
+ "set to `True`."
382
+ },
383
+ )
384
+ num_completions_to_print: int | None = field(
385
+ default=None,
386
+ metadata={"help": "Number of completions to print with `rich`. If `None`, all completions are logged."},
387
+ )
388
+ wandb_entity: str | None = field(
389
+ default=None,
390
+ metadata={"help": ("The entity to store runs under.")},
391
+ )
392
+ wandb_project: str | None = field(
393
+ default=None,
394
+ metadata={"help": ("The project to store runs under.")},
395
+ )
396
+ wandb_run_group: str | None = field(
397
+ default=None,
398
+ metadata={"help": ("The group to store runs under.")},
399
+ )
400
+ wandb_log_unique_prompts: bool = field(
401
+ default=True,
402
+ metadata={
403
+ "help": ("Whether to log the unique prompts to wandb. This will create a new run for each unique prompt.")
404
+ },
405
+ )
406
+ callbacks: list[str] = field(
407
+ default_factory=lambda: [],
408
+ metadata={"help": "The callbacks to run during training."},
409
+ )
410
+ hub_model_revision: str | None = field(
411
+ default="main", metadata={"help": "The Hub model branch to push the model to."}
412
+ )
413
+ overwrite_hub_revision: bool = field(default=False, metadata={"help": "Whether to overwrite the Hub revision."})
414
+ push_to_hub_revision: bool = field(default=False, metadata={"help": "Whether to push to a Hub revision/branch."})
415
+
416
+ def __post_init__(self):
417
+ super().__post_init__()
418
+ # check lmbda and beta are in the range [0, 1]
419
+ if self.lmbda < 0.0 or self.lmbda > 1.0:
420
+ raise ValueError("lmbda must be in the range [0.0, 1.0].")
421
+ if self.beta < 0.0 or self.beta > 1.0:
422
+ raise ValueError("beta must be in the range [0.0, 1.0].")
423
+
424
+ # Validate that max_length is sufficient for max_completion_length
425
+ if self.max_length is not None and self.max_completion_length >= self.max_length:
426
+ raise ValueError(
427
+ f"max_completion_length ({self.max_completion_length}) must be smaller than max_length ({self.max_length}) "
428
+ f"to leave room for the prompt. Consider increasing max_length or reducing max_completion_length."
429
+ )
430
+
431
+ if self.num_generations < 1:
432
+ raise ValueError(f"num_generations must be at least 1, got {self.num_generations}.")
433
+ local_sequence_batch_size = self.per_device_train_batch_size * self.gradient_accumulation_steps
434
+ if self.generation_batch_size is None:
435
+ self.generation_batch_size = local_sequence_batch_size // self.num_generations
436
+ if self.generation_batch_size < 1:
437
+ raise ValueError(
438
+ f"generation_batch_size must be at least 1. Got generation_batch_size={self.generation_batch_size}."
439
+ )
440
+ if self.generation_batch_size * self.num_generations != local_sequence_batch_size:
441
+ raise ValueError(
442
+ "generation_batch_size and num_generations must exactly partition the local optimizer-step batch. "
443
+ "Expected generation_batch_size * num_generations == per_device_train_batch_size * "
444
+ f"gradient_accumulation_steps, got {self.generation_batch_size} * {self.num_generations} != "
445
+ f"{self.per_device_train_batch_size} * {self.gradient_accumulation_steps}."
446
+ )
447
+ if self.num_generations > 1 and self.lmbda < 1.0:
448
+ warnings.warn(
449
+ f"num_generations={self.num_generations} with lmbda={self.lmbda} means off-policy batches include "
450
+ f"{self.num_generations} copies of each sample; consider lmbda=1.0 when num_generations > 1.",
451
+ UserWarning,
452
+ stacklevel=2,
453
+ )
454
+
455
+ # Validate ULD parameters
456
+ if self.use_uld_loss:
457
+ if self.uld_crossentropy_weight < 0.0:
458
+ raise ValueError("uld_crossentropy_weight must be non-negative.")
459
+ if self.uld_distillation_weight < 0.0:
460
+ raise ValueError("uld_distillation_weight must be non-negative.")
461
+ if self.uld_student_temperature <= 0.0:
462
+ raise ValueError("uld_student_temperature must be positive.")
463
+ if self.uld_teacher_temperature <= 0.0:
464
+ raise ValueError("uld_teacher_temperature must be positive.")
465
+
466
+ # Validate hybrid loss weights - both must be None or both must be set
467
+ if self.uld_use_hybrid_loss:
468
+ if (self.uld_hybrid_matched_weight is None) != (self.uld_hybrid_unmatched_weight is None):
469
+ raise ValueError(
470
+ "uld_hybrid_matched_weight and uld_hybrid_unmatched_weight must both be None (for adaptive "
471
+ "weighting) or both be set to numeric values. Got uld_hybrid_matched_weight="
472
+ f"{self.uld_hybrid_matched_weight} and uld_hybrid_unmatched_weight="
473
+ f"{self.uld_hybrid_unmatched_weight}."
474
+ )
475
+ if self.uld_hybrid_matched_weight is not None:
476
+ if self.uld_hybrid_matched_weight < 0.0:
477
+ raise ValueError("uld_hybrid_matched_weight must be non-negative.")
478
+ if self.uld_hybrid_unmatched_weight < 0.0:
479
+ raise ValueError("uld_hybrid_unmatched_weight must be non-negative.")
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gold/gold_trainer.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/grpo_with_replay_buffer/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .grpo_with_replay_buffer_config import GRPOWithReplayBufferConfig
16
+ from .grpo_with_replay_buffer_trainer import GRPOWithReplayBufferTrainer, ReplayBuffer
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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, field
16
+
17
+ from ...trainer.grpo_config import GRPOConfig
18
+
19
+
20
+ @dataclass
21
+ class GRPOWithReplayBufferConfig(GRPOConfig):
22
+ """
23
+ New Parameters:
24
+ replay_buffer_size (`int`, *optional*, defaults to `0`):
25
+ A cache that stores the rollouts with the highest advantage scores and variance per group. If a new
26
+ group has 0 variance, it is replaced with a group sampled from the replay buffer.
27
+ """
28
+
29
+ replay_buffer_size: int = field(
30
+ default=64,
31
+ metadata={
32
+ "help": "A cache that stores the rollouts with the highest advantage scores and variance per group. If a new group has 0 variance, it is replaced with a group sampled from the replay buffer."
33
+ },
34
+ )
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py ADDED
@@ -0,0 +1,795 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 heapq
16
+ from typing import Any
17
+
18
+ import torch
19
+ from accelerate.utils import gather_object
20
+
21
+ from ...data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages
22
+ from ...models.utils import disable_gradient_checkpointing
23
+ from ...trainer.grpo_trainer import GRPOTrainer
24
+ from ...trainer.utils import nanmax, nanmin, nanstd, pad
25
+ from .grpo_with_replay_buffer_config import GRPOWithReplayBufferConfig
26
+
27
+
28
+ class ReplayBuffer:
29
+ """
30
+ A simple replay buffer to store and sample previously seen rollouts.
31
+ """
32
+
33
+ def __init__(self, max_size: int):
34
+ self.max_size = max_size
35
+ self.heap = [] # Min-heap of (score, data) tuples
36
+
37
+ def add(self, scores: list[float], data: list[dict]):
38
+ for score, datum in zip(scores, data, strict=True):
39
+ if len(self.heap) < self.max_size:
40
+ heapq.heappush(self.heap, (score, datum))
41
+ else:
42
+ # Only add if score is better than worst (minimum) item
43
+ if score > self.heap[0][0]:
44
+ heapq.heapreplace(self.heap, (score, datum))
45
+
46
+ def sample(self, num_samples: int) -> list[dict[str, torch.Tensor]]:
47
+ if not self.heap:
48
+ return None
49
+
50
+ # Sample by normalized scores
51
+ scores = torch.tensor([item[0] for item in self.heap], dtype=torch.float32)
52
+ probabilities = scores / scores.sum()
53
+ replacement = False
54
+ if num_samples > len(self.heap):
55
+ replacement = True
56
+ chosen_indices = torch.multinomial(probabilities, num_samples, replacement=replacement).tolist()
57
+ return [self.heap[i][1] for i in chosen_indices]
58
+
59
+
60
+ class GRPOWithReplayBufferTrainer(GRPOTrainer):
61
+ def __init__(self, args: GRPOWithReplayBufferConfig | None = None, **kwargs):
62
+ super().__init__(args=args, **kwargs)
63
+ self.replay_buffer = ReplayBuffer(args.replay_buffer_size) if args.replay_buffer_size > 0 else None
64
+
65
+ def _generate_and_score_completions(
66
+ self, inputs: list[dict[str, torch.Tensor | Any]]
67
+ ) -> dict[str, torch.Tensor | Any]:
68
+ device = self.accelerator.device
69
+ mode = "train" if self.model.training else "eval"
70
+
71
+ prompts = [x["prompt"] for x in inputs]
72
+
73
+ if "images" in inputs[0]:
74
+ images = [example.get("images") for example in inputs]
75
+ elif "image" in inputs[0]:
76
+ images = [[example.get("image")] if example.get("image") is not None else None for example in inputs]
77
+ else:
78
+ images = None
79
+ # Transformers requires at least one image in the batch, otherwise it throws an error
80
+ if images is not None and all(img_list == [] for img_list in images):
81
+ images = None
82
+
83
+ # If the prompts are conversational and the inputs contain images, we need to convert the prompts from
84
+ # [{"role": "user", "content": "What color is the sky?"}] to
85
+ # [{"role": "user", "content": [{"type": "image", "image": <Image>}, {"type": "text", "text": "What color is the sky?"}]}]
86
+ if images is not None:
87
+ if not is_conversational(inputs[0]):
88
+ raise ValueError(
89
+ "Multimodal training requires conversational prompts. It looks like the dataset contains "
90
+ "non-conversational inputs, likely because a chat template was applied before passing the dataset "
91
+ "to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat "
92
+ "template internally."
93
+ )
94
+ prompts = [
95
+ prepare_multimodal_messages(prompt, images=image_list)
96
+ for prompt, image_list in zip(prompts, images, strict=True)
97
+ ]
98
+
99
+ dataset_images = images # preserve dataset images before _generate may overwrite
100
+ (
101
+ prompt_ids_list,
102
+ completion_ids_list,
103
+ tool_mask_list,
104
+ completions,
105
+ num_items_in_batch,
106
+ sampling_per_token_logps_list,
107
+ extra_fields,
108
+ images,
109
+ tool_images,
110
+ ) = self._generate(prompts)
111
+ if images is None:
112
+ images = dataset_images # restore dataset images (rollout_func path returns None)
113
+
114
+ # Convert lists of token IDs to padded tensors
115
+ prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list]
116
+ prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids]
117
+ prompt_ids = pad(
118
+ prompt_ids,
119
+ padding_value=self.pad_token_id,
120
+ padding_side="left",
121
+ pad_to_multiple_of=self.pad_to_multiple_of,
122
+ ).to(device=device)
123
+ prompt_mask = pad(
124
+ prompt_mask,
125
+ padding_value=0,
126
+ padding_side="left",
127
+ pad_to_multiple_of=self.pad_to_multiple_of,
128
+ ).to(device=device)
129
+ completion_ids = [torch.tensor(ids) for ids in completion_ids_list]
130
+ completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids]
131
+ completion_ids = pad(
132
+ completion_ids,
133
+ padding_value=self.pad_token_id,
134
+ padding_side="right",
135
+ pad_to_multiple_of=self.pad_to_multiple_of,
136
+ ).to(device=device)
137
+ completion_mask = pad(
138
+ completion_mask,
139
+ padding_value=0,
140
+ padding_side="right",
141
+ pad_to_multiple_of=self.pad_to_multiple_of,
142
+ ).to(device=device)
143
+ if sampling_per_token_logps_list is not None:
144
+ sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list]
145
+ sampling_per_token_logps = pad(
146
+ sampling_per_token_logps,
147
+ padding_value=0.0,
148
+ padding_side="right",
149
+ pad_to_multiple_of=self.pad_to_multiple_of,
150
+ ).to(device=device)
151
+ else:
152
+ sampling_per_token_logps = None
153
+ if self.tools:
154
+ tool_mask = [torch.tensor(mask) for mask in tool_mask_list]
155
+ tool_mask = pad(
156
+ tool_mask,
157
+ padding_value=1,
158
+ padding_side="right",
159
+ pad_to_multiple_of=self.pad_to_multiple_of,
160
+ ).to(device=device) # 0 for tool result tokens, 1 elsewhere
161
+
162
+ # If mask_truncated_completions is enabled, zero out truncated completions in completion_mask
163
+ if self.mask_truncated_completions:
164
+ eos_and_pad = [self.eos_token_id, self.pad_token_id]
165
+ is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device)
166
+ completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int()
167
+
168
+ # Concatenate prompt_mask with completion_mask for logit computation
169
+ prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C)
170
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C)
171
+
172
+ logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
173
+ batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size
174
+
175
+ num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None
176
+
177
+ # Get forward_kwargs for models with multimodal inputs
178
+ if images is not None:
179
+ prompts_text = [
180
+ apply_chat_template(
181
+ {"prompt": prompt}, self.processing_class, tools=self.tools, **self.chat_template_kwargs
182
+ )["prompt"]
183
+ for prompt in prompts
184
+ ]
185
+ prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt")
186
+ prompt_inputs = super()._prepare_inputs(prompt_inputs)
187
+ forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]}
188
+ else:
189
+ forward_kwargs = {}
190
+
191
+ # If token_type_ids are used, extend them with zeros for the completion part
192
+ if "token_type_ids" in forward_kwargs:
193
+ token_type_ids = forward_kwargs["token_type_ids"]
194
+ if self.pad_to_multiple_of is not None:
195
+ # Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len
196
+ padding_size = prompt_ids.size(1) - token_type_ids.size(1)
197
+ if padding_size > 0:
198
+ token_type_ids = torch.cat(
199
+ [token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1
200
+ )
201
+ forward_kwargs["token_type_ids"] = torch.cat(
202
+ [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1
203
+ )
204
+ # If mm_token_type_ids are used, extend them with zeros for the completion part
205
+ if "mm_token_type_ids" in forward_kwargs:
206
+ mm_token_type_ids = forward_kwargs["mm_token_type_ids"]
207
+ if self.pad_to_multiple_of is not None:
208
+ # Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len
209
+ padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1)
210
+ if padding_size > 0:
211
+ mm_token_type_ids = torch.cat(
212
+ [mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids],
213
+ dim=1,
214
+ )
215
+ forward_kwargs["mm_token_type_ids"] = torch.cat(
216
+ [mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1
217
+ )
218
+
219
+ # When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a
220
+ # torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True").
221
+ # Temporarily disable checkpointing to avoid this warning during inference.
222
+ with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
223
+ # If the generation and optimization steps are misaligned—i.e., if generation does not occur at the end of
224
+ # a full optimizer step (when gradient_accumulation_steps is not a multiple of generate_every)—then the
225
+ # samples may come from an earlier version of the model. In that case, we need to track old_per_token_logps
226
+ # for importance sampling. If the steps are aligned, importance sampling isn't necessary and we set
227
+ # old_per_token_logps to None.
228
+ # When using vLLM, we always compute old_per_token_logps for importance sampling, it was shown that the
229
+ # distribution mismatch between vLLM and the training model can be large and harm the training.
230
+ generate_every = self.args.steps_per_generation * self.num_iterations # generation frequency
231
+ if self.args.gradient_accumulation_steps % generate_every != 0 or (
232
+ self.use_vllm and self.vllm_importance_sampling_correction
233
+ ):
234
+ old_per_token_logps, _ = self._get_per_token_logps_and_entropies(
235
+ self.model,
236
+ prompt_completion_ids,
237
+ attention_mask,
238
+ logits_to_keep,
239
+ batch_size,
240
+ num_images=num_images,
241
+ **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
242
+ )
243
+ else:
244
+ old_per_token_logps = None
245
+
246
+ # Compute the importance sampling ratio when using vLLM, to correct for potential distribution mismatch
247
+ if self.use_vllm and self.vllm_importance_sampling_correction:
248
+ importance_sampling_ratio = torch.exp(old_per_token_logps - sampling_per_token_logps)
249
+ importance_sampling_ratio = torch.clamp(
250
+ importance_sampling_ratio, max=self.vllm_importance_sampling_cap
251
+ )
252
+
253
+ # Compute the per-token log probabilities for the reference model
254
+ if self.beta != 0.0:
255
+ if self.ref_model is not None:
256
+ ref_per_token_logps, _ = self._get_per_token_logps_and_entropies(
257
+ self.ref_model,
258
+ prompt_completion_ids,
259
+ attention_mask,
260
+ logits_to_keep,
261
+ batch_size=batch_size,
262
+ num_images=num_images,
263
+ **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
264
+ )
265
+ else:
266
+ with self.accelerator.unwrap_model(self.model).disable_adapter():
267
+ ref_per_token_logps, _ = self._get_per_token_logps_and_entropies(
268
+ self.model,
269
+ prompt_completion_ids,
270
+ attention_mask,
271
+ logits_to_keep,
272
+ batch_size=batch_size,
273
+ num_images=num_images,
274
+ **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
275
+ )
276
+ else:
277
+ ref_per_token_logps = None
278
+
279
+ # Decode
280
+ prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True)
281
+ completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
282
+
283
+ # Merge extra_fields from rollout_func into inputs for reward functions
284
+ if extra_fields:
285
+ for i, inp in enumerate(inputs):
286
+ for key, values in extra_fields.items():
287
+ if isinstance(values, list) and i < len(values):
288
+ inp[key] = values[i]
289
+ elif not isinstance(values, list):
290
+ inp[key] = values
291
+
292
+ # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is
293
+ # important because rewards will be normalized per group, and completions are distributed. We will later slice
294
+ # rewards_per_func to extract each process's subset.
295
+ rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
296
+
297
+ # Apply weights to each reward function's output and sum
298
+ rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
299
+
300
+ # Compute grouped-wise rewards
301
+ mean_grouped_rewards = rewards.view(-1, self.num_generations).mean(dim=1)
302
+
303
+ # Normalize the rewards to compute the advantages
304
+ mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
305
+ advantages = rewards - mean_grouped_rewards
306
+
307
+ grouped_std_rewards = rewards.view(-1, self.num_generations).std(dim=1)
308
+ grouped_std_rewards = grouped_std_rewards.repeat_interleave(self.num_generations, dim=0)
309
+
310
+ if self.scale_rewards in ["group", "none"]:
311
+ # If self.scale_rewards = "none", we'll still log group level std
312
+ std_rewards = grouped_std_rewards.clone()
313
+ elif self.scale_rewards == "batch":
314
+ # Compute global std
315
+ std_rewards = rewards.std().expand_as(rewards)
316
+ else:
317
+ raise ValueError(
318
+ f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'."
319
+ )
320
+
321
+ is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards))
322
+ if self.scale_rewards != "none":
323
+ advantages = advantages / (std_rewards + 1e-4)
324
+
325
+ # Slice to keep only the local part of the data
326
+ process_slice = slice(
327
+ self.accelerator.process_index * len(prompts),
328
+ (self.accelerator.process_index + 1) * len(prompts),
329
+ )
330
+ all_process_advantages = advantages.clone() # keep the aggregated advantages for logging
331
+ advantages = advantages[process_slice]
332
+ grouped_std_rewards = grouped_std_rewards[process_slice]
333
+
334
+ # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values)
335
+ for i, reward_func_name in enumerate(self.reward_func_names):
336
+ mean_rewards = torch.nanmean(rewards_per_func[:, i]).item()
337
+ self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards)
338
+ std_func_rewards = nanstd(rewards_per_func[:, i]).item()
339
+ self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards)
340
+ rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1)
341
+ self._metrics[mode]["reward"].append(rewards.mean().item())
342
+ self._metrics[mode]["reward_std"].append(rewards.std().item())
343
+ self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item())
344
+
345
+ # Log prompt and completion texts
346
+ self._logs["prompt"].extend(gather_object(prompts_text))
347
+ self._logs["completion"].extend(gather_object(completions_text))
348
+ for i, name in enumerate(self.reward_func_names):
349
+ self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist())
350
+ self._logs["advantages"].extend(all_process_advantages.tolist())
351
+
352
+ if images is not None:
353
+ self._logs["images"].extend(gather_object(images))
354
+
355
+ if self.use_vllm and self.vllm_importance_sampling_correction:
356
+ delta = torch.abs(old_per_token_logps - sampling_per_token_logps)
357
+ mask = completion_mask.bool() if not self.tools else (completion_mask * tool_mask).bool()
358
+ delta = delta[mask]
359
+ mean_delta = torch.mean(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device)
360
+ max_delta = torch.max(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device)
361
+ self._metrics[mode]["sampling/sampling_logp_difference/mean"].append(
362
+ self.accelerator.gather(mean_delta).mean().item()
363
+ )
364
+ self._metrics[mode]["sampling/sampling_logp_difference/max"].append(
365
+ self.accelerator.gather(max_delta).max().item()
366
+ )
367
+
368
+ flat_is_ratio = importance_sampling_ratio[mask]
369
+ min_importance_sampling_ratio = (
370
+ torch.min(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device)
371
+ )
372
+ mean_importance_sampling_ratio = (
373
+ torch.mean(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device)
374
+ )
375
+ max_importance_sampling_ratio = (
376
+ torch.max(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device)
377
+ )
378
+ self._metrics[mode]["sampling/importance_sampling_ratio/min"].append(
379
+ nanmin(self.accelerator.gather(min_importance_sampling_ratio)).item()
380
+ )
381
+ self._metrics[mode]["sampling/importance_sampling_ratio/mean"].append(
382
+ self.accelerator.gather(mean_importance_sampling_ratio).nanmean().item()
383
+ )
384
+ self._metrics[mode]["sampling/importance_sampling_ratio/max"].append(
385
+ nanmax(self.accelerator.gather(max_importance_sampling_ratio)).item()
386
+ )
387
+ outputs_after_sampling_buffer = self.update_with_replay_buffer(
388
+ advantages,
389
+ grouped_std_rewards,
390
+ prompt_ids,
391
+ prompt_mask,
392
+ completion_ids,
393
+ completion_mask,
394
+ forward_kwargs,
395
+ num_items_in_batch,
396
+ old_per_token_logps,
397
+ ref_per_token_logps,
398
+ importance_sampling_ratio if self.use_vllm and self.vllm_importance_sampling_correction else None,
399
+ )
400
+ if outputs_after_sampling_buffer is not None:
401
+ return outputs_after_sampling_buffer
402
+ else:
403
+ output = {
404
+ "prompt_ids": prompt_ids,
405
+ "prompt_mask": prompt_mask,
406
+ "completion_ids": completion_ids,
407
+ "completion_mask": completion_mask,
408
+ "advantages": advantages,
409
+ "num_items_in_batch": num_items_in_batch,
410
+ }
411
+ if old_per_token_logps is not None:
412
+ output["old_per_token_logps"] = old_per_token_logps
413
+ if self.use_vllm and self.vllm_importance_sampling_correction:
414
+ output["importance_sampling_ratio"] = importance_sampling_ratio
415
+ if ref_per_token_logps is not None:
416
+ output["ref_per_token_logps"] = ref_per_token_logps
417
+ if "pixel_values" in forward_kwargs:
418
+ output["pixel_values"] = forward_kwargs["pixel_values"]
419
+ if "image_grid_thw" in forward_kwargs:
420
+ output["image_grid_thw"] = forward_kwargs["image_grid_thw"]
421
+ if "pixel_attention_mask" in forward_kwargs:
422
+ output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"]
423
+ if "image_sizes" in forward_kwargs:
424
+ output["image_sizes"] = forward_kwargs["image_sizes"]
425
+ if "token_type_ids" in forward_kwargs:
426
+ output["token_type_ids"] = forward_kwargs["token_type_ids"]
427
+ if images is not None:
428
+ output["num_images"] = num_images
429
+ if self.tools:
430
+ output["tool_mask"] = tool_mask
431
+ return output
432
+
433
+ def slice_group_data(
434
+ self, data: torch.Tensor, mask: torch.Tensor, group_idx: int
435
+ ) -> tuple[torch.Tensor, torch.Tensor]:
436
+ """
437
+ Slices the input data and mask tensors for a specific group index. Also trims the sequence length to the
438
+ maximum length in the group based on the mask.
439
+
440
+ Args:
441
+ data: Tensor of shape (num_groups * num_generations, seq_length)
442
+ mask: Tensor of shape (num_groups * num_generations, seq_length)
443
+ group_idx: Index of the group to slice
444
+ Returns:
445
+ Tuple of (sliced_data, sliced_mask) for the specified group, with sequence length trimmed to the maximum
446
+ length in the group.
447
+ """
448
+ start_idx = group_idx * self.num_generations
449
+ end_idx = (group_idx + 1) * self.num_generations
450
+ group_data = data[start_idx:end_idx]
451
+ group_mask = mask[start_idx:end_idx]
452
+ group_max_len = group_mask.sum(dim=1).max().item()
453
+ return group_data[:, :group_max_len], group_mask[:, :group_max_len]
454
+
455
+ def update_replay_buffer(
456
+ self,
457
+ groups_with_variance: torch.Tensor,
458
+ group_advantages: torch.Tensor,
459
+ group_std_rewards: torch.Tensor,
460
+ prompt_ids: torch.Tensor,
461
+ prompt_mask: torch.Tensor,
462
+ completion_ids: torch.Tensor,
463
+ completion_mask: torch.Tensor,
464
+ forward_kwargs: dict,
465
+ optional_vision_fields: list[str] = None,
466
+ old_per_token_logps: torch.Tensor | None = None,
467
+ ref_per_token_logps: torch.Tensor | None = None,
468
+ importance_sampling_ratio: float | None = None,
469
+ ) -> None:
470
+ """
471
+ Update the replay buffer with groups that have reward variance (std > 0).
472
+
473
+ Args:
474
+ groups_with_variance: Boolean tensor indicating which groups have reward variance
475
+ group_advantages: Tensor of shape (num_groups, num_generations) containing advantage values
476
+ std_rewards: Tensor of shape (num_groups, num_generations) containing std of rewards per group
477
+ prompt_ids: Tensor containing prompt token IDs
478
+ prompt_mask: Tensor containing prompt attention masks
479
+ completion_ids: Tensor containing completion token IDs
480
+ completion_mask: Tensor containing completion attention masks
481
+ forward_kwargs: Dictionary containing additional prompt inputs (vision data, etc.)
482
+ optional_vision_fields: List of optional vision-related fields to include if present in forward_kwargs
483
+ old_per_token_logps: Optional tensor of old per-token log probabilities
484
+ ref_per_token_logps: Optional tensor of reference per-token log probabilities
485
+ importance_sampling_ratio: Optional importance sampling correction ratio
486
+ """
487
+ # Prepare buffered outputs for groups with variance
488
+ buffered_outputs = []
489
+ for _, group_idx in enumerate(groups_with_variance.nonzero(as_tuple=True)[0].unique().tolist()):
490
+ group_prompt_ids, group_prompt_mask = self.slice_group_data(prompt_ids, prompt_mask, group_idx)
491
+ group_completion_ids, group_completion_mask = self.slice_group_data(
492
+ completion_ids, completion_mask, group_idx
493
+ )
494
+
495
+ # Store unpadded data in the buffer
496
+ buffered_output = {
497
+ "prompt_ids": group_prompt_ids,
498
+ "completion_ids": group_completion_ids,
499
+ "advantages": group_advantages[group_idx].tolist(),
500
+ "prompt_mask": group_prompt_mask,
501
+ "completion_mask": group_completion_mask,
502
+ }
503
+
504
+ # Add optional fields if they exist
505
+ optional_fields = {
506
+ "old_per_token_logps": old_per_token_logps if old_per_token_logps is not None else None,
507
+ "ref_per_token_logps": ref_per_token_logps if ref_per_token_logps is not None else None,
508
+ }
509
+
510
+ for field_name, field_data in optional_fields.items():
511
+ if field_data is not None:
512
+ buffered_output[field_name] = self.slice_group_data(field_data, completion_mask, group_idx)[0]
513
+
514
+ # Add importance sampling if needed
515
+ if self.use_vllm and self.vllm_importance_sampling_correction:
516
+ buffered_output["importance_sampling_ratio"] = importance_sampling_ratio
517
+
518
+ if optional_vision_fields:
519
+ # Add vision-related fields if they exist
520
+ for field_name in optional_vision_fields:
521
+ if field_name in forward_kwargs:
522
+ buffered_output[field_name] = self.slice_group_data(
523
+ forward_kwargs[field_name], prompt_mask, group_idx
524
+ )[0]
525
+
526
+ buffered_outputs.append(buffered_output)
527
+
528
+ if groups_with_variance.any():
529
+ # Calculate replay buffer scores for groups with variance
530
+ replay_buffer_scores = (group_advantages.abs() * group_std_rewards).sum(dim=-1)[groups_with_variance]
531
+ # Add all groups to replay buffer at once (batch operation)
532
+ self.replay_buffer.add(replay_buffer_scores.tolist(), buffered_outputs)
533
+
534
+ def sample_from_replay_buffer(
535
+ self, num_samples: int, optional_vision_fields: list[str] = None, optional_tensor_fields: list[str] = None
536
+ ) -> list[dict]:
537
+ """
538
+ Sample groups from the replay buffer.
539
+
540
+ Args:
541
+ num_samples: Number of samples to draw from the replay buffer
542
+ optional_vision_fields: List of optional vision-related fields to include if present in sampled data
543
+ optional_tensor_fields: List of optional tensor fields to include if present in sampled data
544
+ Returns:
545
+ List of sampled data dictionaries from the replay buffer
546
+ """
547
+ sampled = self.replay_buffer.sample(num_samples=num_samples)
548
+
549
+ # Extract and concatenate sampled data
550
+ sampled_data = {
551
+ "prompt_ids": [],
552
+ "prompt_mask": [],
553
+ "completion_ids": [],
554
+ "completion_mask": [],
555
+ "advantages": [],
556
+ }
557
+
558
+ all_optional_fields = (optional_tensor_fields or []) + (optional_vision_fields or [])
559
+ # Initialize containers for optional fields if they exist in sampled data
560
+ for field in all_optional_fields:
561
+ if sampled and field in sampled[0]:
562
+ sampled_data[field] = []
563
+
564
+ # Extract data from each sampled item
565
+ for item in sampled:
566
+ # Handle core fields
567
+ for key in ["prompt_ids", "prompt_mask", "completion_ids", "completion_mask"]:
568
+ sampled_data[key].append(item[key])
569
+
570
+ # Handle advantages (list, not tensor)
571
+ sampled_data["advantages"].append(item["advantages"])
572
+
573
+ # Handle optional fields
574
+ for field in all_optional_fields:
575
+ if field in item:
576
+ sampled_data[field].append(item[field])
577
+
578
+ return sampled_data
579
+
580
+ def update_with_replay_buffer(
581
+ self,
582
+ group_advantages: torch.Tensor,
583
+ group_std_rewards: torch.Tensor,
584
+ prompt_ids: torch.Tensor,
585
+ prompt_mask: torch.Tensor,
586
+ completion_ids: torch.Tensor,
587
+ completion_mask: torch.Tensor,
588
+ forward_kwargs: dict,
589
+ num_items_in_batch: int,
590
+ old_per_token_logps: torch.Tensor | None = None,
591
+ ref_per_token_logps: torch.Tensor | None = None,
592
+ importance_sampling_ratio: float | None = None,
593
+ ) -> None:
594
+ """
595
+ Update current batch data with samples from replay buffer.
596
+
597
+ Groups with reward variance (std > 0) are added to the replay buffer and then replaced with samples from the
598
+ buffer to improve training stability.
599
+
600
+ Args:
601
+ group_advantages: Tensor of shape (num_groups, num_generations) containing advantage values
602
+ std_rewards: Tensor of shape (num_groups, num_generations) containing std of rewards per group
603
+ prompt_ids: Tensor containing prompt token IDs
604
+ prompt_mask: Tensor containing prompt attention masks
605
+ completion_ids: Tensor containing completion token IDs
606
+ completion_mask: Tensor containing completion attention masks
607
+ forward_kwargs: Dictionary containing additional prompt inputs (vision data, etc.)
608
+ num_items_in_batch: Number of items in the current batch
609
+ old_per_token_logps: Optional tensor of old per-token log probabilities
610
+ ref_per_token_logps: Optional tensor of reference per-token log probabilities
611
+ importance_sampling_ratio: Optional importance sampling correction ratio
612
+ """
613
+ if self.replay_buffer.max_size <= 0:
614
+ return
615
+
616
+ # Groups to consider for adding to the replay buffer
617
+ groups_with_variance = group_std_rewards.max(dim=0).values > 0
618
+ # Groups to replace from the replay buffer
619
+ groups_without_variance = ~groups_with_variance
620
+
621
+ # Track which optional fields are present in sampled data
622
+ optional_tensor_fields = ["old_per_token_logps", "ref_per_token_logps"]
623
+ vision_fields = ["pixel_values", "image_grid_thw", "pixel_attention_mask", "image_sizes"]
624
+
625
+ self.update_replay_buffer(
626
+ groups_with_variance,
627
+ group_advantages,
628
+ group_std_rewards,
629
+ prompt_ids,
630
+ prompt_mask,
631
+ completion_ids,
632
+ completion_mask,
633
+ forward_kwargs,
634
+ vision_fields,
635
+ old_per_token_logps,
636
+ ref_per_token_logps,
637
+ importance_sampling_ratio,
638
+ )
639
+
640
+ # Sample from replay buffer to replace groups with variance
641
+ num_groups_to_replace = groups_without_variance.sum().item()
642
+ if not num_groups_to_replace:
643
+ return
644
+
645
+ sampled_data = self.sample_from_replay_buffer(
646
+ num_samples=num_groups_to_replace,
647
+ optional_vision_fields=vision_fields,
648
+ optional_tensor_fields=optional_tensor_fields,
649
+ )
650
+
651
+ # Pad sampled data if they are shorter than the current batch sequences
652
+ # Or pad the current batch if sampled are longer
653
+ current_batch_prompt_seq_len = prompt_ids.size(1)
654
+ current_batch_completion_seq_len = completion_ids.size(1)
655
+
656
+ groups_to_replace_idxs = groups_with_variance.logical_not().nonzero(as_tuple=True)[0].unique().tolist()
657
+
658
+ # Determine target (max) sequence lengths once
659
+ sampled_prompt_lengths = [t.size(1) for t in sampled_data["prompt_ids"]]
660
+ sampled_completion_lengths = [t.size(1) for t in sampled_data["completion_ids"]]
661
+ target_prompt_len = max([current_batch_prompt_seq_len] + sampled_prompt_lengths)
662
+ target_completion_len = max([current_batch_completion_seq_len] + sampled_completion_lengths)
663
+
664
+ # If any sampled prompt is longer, pad the whole batch prompt tensors once (left padding)
665
+ if target_prompt_len > current_batch_prompt_seq_len:
666
+ prompt_ids = pad(
667
+ list(prompt_ids.unbind(0)),
668
+ padding_value=self.pad_token_id,
669
+ pad_to_multiple_of=target_prompt_len,
670
+ padding_side="left",
671
+ )
672
+ prompt_mask = pad(
673
+ list(prompt_mask.unbind(0)), padding_value=0, pad_to_multiple_of=target_prompt_len, padding_side="left"
674
+ )
675
+ # If any sampled completion is longer, pad the whole batch completion tensors once (right padding)
676
+ if target_completion_len > current_batch_completion_seq_len:
677
+ completion_ids = pad(
678
+ list(completion_ids.unbind(0)),
679
+ padding_value=self.pad_token_id,
680
+ pad_to_multiple_of=target_completion_len,
681
+ padding_side="right",
682
+ )
683
+ completion_mask = pad(
684
+ list(completion_mask.unbind(0)),
685
+ padding_value=0,
686
+ pad_to_multiple_of=target_completion_len,
687
+ padding_side="right",
688
+ )
689
+ if old_per_token_logps is not None:
690
+ old_per_token_logps = pad(
691
+ list(old_per_token_logps.unbind(0)),
692
+ padding_value=0.0,
693
+ pad_to_multiple_of=target_completion_len,
694
+ padding_side="right",
695
+ )
696
+ if ref_per_token_logps is not None:
697
+ ref_per_token_logps = pad(
698
+ list(ref_per_token_logps.unbind(0)),
699
+ padding_value=0.0,
700
+ pad_to_multiple_of=target_completion_len,
701
+ padding_side="right",
702
+ )
703
+
704
+ # Replace per-group data, padding only sampled groups that are shorter than the target
705
+ for i, group_idx in enumerate(groups_to_replace_idxs):
706
+ start_idx = group_idx * self.num_generations
707
+ end_idx = (group_idx + 1) * self.num_generations
708
+ idx_range = slice(start_idx, end_idx)
709
+
710
+ # Pad sampled prompt to target length if needed
711
+ if sampled_data["prompt_ids"][i].size(1) < target_prompt_len:
712
+ sampled_data["prompt_ids"][i] = pad(
713
+ sampled_data["prompt_ids"][i],
714
+ padding_value=self.pad_token_id,
715
+ pad_to_multiple_of=target_prompt_len,
716
+ padding_side="left",
717
+ )
718
+ sampled_data["prompt_mask"][i] = pad(
719
+ sampled_data["prompt_mask"][i],
720
+ padding_value=0,
721
+ pad_to_multiple_of=target_prompt_len,
722
+ padding_side="left",
723
+ )
724
+
725
+ # Pad sampled completion to target length if needed
726
+ if sampled_data["completion_ids"][i].size(1) < target_completion_len:
727
+ sampled_data["completion_ids"][i] = pad(
728
+ sampled_data["completion_ids"][i],
729
+ padding_value=self.pad_token_id,
730
+ pad_to_multiple_of=target_completion_len,
731
+ padding_side="right",
732
+ )
733
+ sampled_data["completion_mask"][i] = pad(
734
+ sampled_data["completion_mask"][i],
735
+ padding_value=0,
736
+ pad_to_multiple_of=target_completion_len,
737
+ padding_side="right",
738
+ )
739
+ if "old_per_token_logps" in sampled_data:
740
+ sampled_data["old_per_token_logps"][i] = pad(
741
+ sampled_data["old_per_token_logps"][i],
742
+ padding_value=0.0,
743
+ pad_to_multiple_of=target_completion_len,
744
+ padding_side="right",
745
+ )
746
+ if "ref_per_token_logps" in sampled_data:
747
+ sampled_data["ref_per_token_logps"][i] = pad(
748
+ sampled_data["ref_per_token_logps"][i],
749
+ padding_value=0.0,
750
+ pad_to_multiple_of=target_completion_len,
751
+ padding_side="right",
752
+ )
753
+
754
+ # Assign (replace) group slice
755
+ prompt_ids[idx_range] = sampled_data["prompt_ids"][i]
756
+ prompt_mask[idx_range] = sampled_data["prompt_mask"][i]
757
+ completion_ids[idx_range] = sampled_data["completion_ids"][i]
758
+ completion_mask[idx_range] = sampled_data["completion_mask"][i]
759
+ group_advantages[group_idx] = sampled_data["advantages"][i]
760
+
761
+ if "old_per_token_logps" in sampled_data:
762
+ old_per_token_logps[idx_range] = sampled_data["old_per_token_logps"][i]
763
+ if "ref_per_token_logps" in sampled_data:
764
+ ref_per_token_logps[idx_range] = sampled_data["ref_per_token_logps"][i]
765
+
766
+ for field in vision_fields:
767
+ if field in sampled_data and field in forward_kwargs:
768
+ forward_kwargs[field][idx_range] = sampled_data[field][i]
769
+
770
+ # Prepare final outputs after sampling and replacement
771
+ outputs_after_sampling_buffer = {
772
+ "prompt_ids": prompt_ids,
773
+ "prompt_mask": prompt_mask,
774
+ "completion_ids": completion_ids,
775
+ "completion_mask": completion_mask,
776
+ "advantages": group_advantages,
777
+ }
778
+
779
+ # Replace optional tensor fields if they exist
780
+ for field in optional_tensor_fields:
781
+ if field in sampled_data:
782
+ outputs_after_sampling_buffer[field] = (
783
+ old_per_token_logps if field == "old_per_token_logps" else ref_per_token_logps
784
+ )
785
+
786
+ # Replace vision fields if they exist
787
+ for field in vision_fields:
788
+ if field in sampled_data and field in forward_kwargs:
789
+ outputs_after_sampling_buffer[field] = forward_kwargs[field]
790
+
791
+ outputs_after_sampling_buffer["num_items_in_batch"] = num_items_in_batch
792
+ if self.use_vllm and self.vllm_importance_sampling_correction:
793
+ outputs_after_sampling_buffer["importance_sampling_ratio"] = importance_sampling_ratio
794
+
795
+ return outputs_after_sampling_buffer
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gspo_token/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .grpo_trainer import GRPOTrainer
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/gspo_token/grpo_trainer.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 torch
16
+
17
+ from ...trainer.grpo_trainer import GRPOTrainer as _GRPOTrainer
18
+ from ...trainer.utils import nanmax, nanmin
19
+
20
+
21
+ class GRPOTrainer(_GRPOTrainer):
22
+ def _compute_loss(self, model, inputs):
23
+ # Compute the per-token log probabilities for the model
24
+ prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
25
+ completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
26
+ input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
27
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
28
+ logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
29
+
30
+ # Compute the per_token_logps and the entropy at each position in the completion
31
+ per_token_logps, entropies = self._get_per_token_logps_and_entropies(
32
+ model,
33
+ input_ids,
34
+ attention_mask,
35
+ logits_to_keep,
36
+ compute_entropy=True,
37
+ pixel_values=inputs.get("pixel_values"),
38
+ image_grid_thw=inputs.get("image_grid_thw"),
39
+ num_images=inputs.get("num_images"),
40
+ pixel_attention_mask=inputs.get("pixel_attention_mask"),
41
+ image_sizes=inputs.get("image_sizes"),
42
+ token_type_ids=inputs.get("token_type_ids"),
43
+ )
44
+
45
+ if self.top_entropy_quantile < 1.0:
46
+ entropy_mask = self.get_high_entropy_mask(entropies, completion_mask, 1 - self.top_entropy_quantile)
47
+ else:
48
+ entropy_mask = None
49
+
50
+ # Compute the KL divergence between the model and the reference model
51
+ if self.beta != 0.0:
52
+ ref_per_token_logps = inputs["ref_per_token_logps"]
53
+ per_token_kl = (
54
+ torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
55
+ )
56
+
57
+ # Compute the loss
58
+ advantages = inputs["advantages"]
59
+ # When num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps,
60
+ # old_per_token_logps == per_token_logps. In this case we can skip its computation
61
+ # (see _generate_and_score_completions) and instead use per_token_logps.detach().
62
+ # The exception is when using vLLM, where we always compute old_per_token_logps
63
+ # for importance sampling
64
+ old_per_token_logps = inputs.get("old_per_token_logps")
65
+ old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps
66
+
67
+ log_ratio = per_token_logps - old_per_token_logps
68
+ if self.importance_sampling_level == "token":
69
+ log_importance_weights = log_ratio
70
+ elif self.importance_sampling_level == "sequence":
71
+ log_importance_weights = (log_ratio * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)
72
+ log_importance_weights = log_importance_weights.unsqueeze(-1)
73
+ elif self.importance_sampling_level == "sequence_token":
74
+ # GSPO-token: sg[si(θ)] * πθ(yi,t)/sg[πθ(yi,t)]
75
+ seq_level_log_weight = (log_ratio * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)
76
+ seq_level_log_weight = seq_level_log_weight.detach().unsqueeze(-1) # Stop gradient
77
+ log_importance_weights = per_token_logps - per_token_logps.detach() + seq_level_log_weight
78
+ else:
79
+ raise ValueError(
80
+ f"Unknown importance sampling level: {self.importance_sampling_level}. Possible values are 'token' "
81
+ "and 'sequence'."
82
+ )
83
+ # From here, log_importance_weights (and all subsequent tensors, coef_1, coef_2, etc.) shape depends on
84
+ # importance_sampling_level: "token" level: (B, T); "sequence" level: (B, 1)
85
+
86
+ coef_1 = torch.exp(log_importance_weights)
87
+ coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
88
+
89
+ # Two-sided clipping
90
+ if self.args.delta is not None:
91
+ coef_1 = torch.clamp(coef_1, max=self.args.delta)
92
+
93
+ per_token_loss1 = coef_1 * advantages.unsqueeze(1)
94
+ per_token_loss2 = coef_2 * advantages.unsqueeze(1)
95
+ per_token_loss = -torch.min(per_token_loss1, per_token_loss2)
96
+ if entropy_mask is not None:
97
+ per_token_loss = per_token_loss * entropy_mask
98
+
99
+ if self.use_vllm and self.vllm_importance_sampling_correction:
100
+ per_token_loss = per_token_loss * inputs["importance_sampling_ratio"]
101
+
102
+ if self.beta != 0.0:
103
+ per_token_loss = per_token_loss + self.beta * per_token_kl
104
+
105
+ mode = "train" if self.model.training else "eval"
106
+ if self.loss_type == "grpo":
107
+ loss = ((per_token_loss * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)).mean()
108
+ normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval
109
+ loss = loss / normalizer
110
+ elif self.loss_type == "bnpo":
111
+ loss = (per_token_loss * completion_mask).sum() / completion_mask.sum().clamp(min=1.0)
112
+ normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval
113
+ loss = loss / normalizer
114
+ elif self.loss_type == "dr_grpo":
115
+ loss = (per_token_loss * completion_mask).sum() / (per_token_loss.size(0) * self.max_completion_length)
116
+ normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval
117
+ loss = loss / normalizer
118
+ elif self.loss_type == "dapo":
119
+ normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes
120
+ loss = (per_token_loss * completion_mask).sum() / normalizer
121
+ else:
122
+ raise ValueError(f"Unknown loss type: {self.loss_type}")
123
+
124
+ # Log the metrics
125
+ completion_token_count = completion_mask.sum().clamp(min=1.0)
126
+
127
+ def masked_batch_mean(x):
128
+ if x.shape[1] == 1: # when importance_sampling_level == "sequence"
129
+ return x.mean()
130
+ else:
131
+ return (x * completion_mask).sum() / completion_token_count
132
+
133
+ if self.beta != 0.0:
134
+ mean_kl = masked_batch_mean(per_token_kl)
135
+ self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
136
+
137
+ mean_entropy = masked_batch_mean(entropies)
138
+ self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item())
139
+
140
+ # Compute the clipped probability ratios
141
+ is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages.unsqueeze(1) < 0)
142
+ is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages.unsqueeze(1) > 0)
143
+ is_region_clipped = is_low_clipped | is_high_clipped
144
+
145
+ low_clip = masked_batch_mean(is_low_clipped.float())
146
+ high_clip = masked_batch_mean(is_high_clipped.float())
147
+ clip_ratio = masked_batch_mean(is_region_clipped.float())
148
+
149
+ gathered_low_clip = self.accelerator.gather(low_clip)
150
+ self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item())
151
+ self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item())
152
+ gathered_high_clip = self.accelerator.gather(high_clip)
153
+ self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item())
154
+ self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item())
155
+ gathered_clip_ratio = self.accelerator.gather(clip_ratio)
156
+ self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item())
157
+ return loss
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/judges/__init__.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .judges import (
16
+ AllTrueJudge,
17
+ BaseBinaryJudge,
18
+ BaseJudge,
19
+ BasePairwiseJudge,
20
+ BaseRankJudge,
21
+ HfPairwiseJudge,
22
+ OpenAIPairwiseJudge,
23
+ PairRMJudge,
24
+ )
25
+
26
+
27
+ __all__ = [
28
+ "AllTrueJudge",
29
+ "BaseBinaryJudge",
30
+ "BaseJudge",
31
+ "BasePairwiseJudge",
32
+ "BaseRankJudge",
33
+ "HfPairwiseJudge",
34
+ "OpenAIPairwiseJudge",
35
+ "PairRMJudge",
36
+ ]
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/judges/judges.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 concurrent.futures
16
+ import logging
17
+ from abc import ABC, abstractmethod
18
+
19
+ import numpy as np
20
+ from accelerate import Accelerator
21
+ from huggingface_hub import InferenceClient
22
+ from packaging.version import Version
23
+ from transformers.utils import is_openai_available
24
+
25
+ from ...import_utils import is_llm_blender_available
26
+
27
+
28
+ DEFAULT_PAIRWISE_SYSTEM_PROMPT = '''I require a leaderboard for various large language models. I'll provide you with prompts given to these models and their corresponding outputs. Your task is to assess these responses, and select the model that produces the best output from a human perspective.
29
+
30
+ ## Instruction
31
+
32
+ {{
33
+ "instruction": """{prompt}""",
34
+ }}
35
+
36
+ ## Model Outputs
37
+
38
+ Here are the unordered outputs from the models. Each output is associated with a specific model, identified by a unique model identifier.
39
+
40
+ {{
41
+ {{
42
+ "model_identifier": "0",
43
+ "output": """{response0}"""
44
+ }},
45
+ {{
46
+ "model_identifier": "1",
47
+ "output": """{response1}"""
48
+ }}
49
+ }}
50
+
51
+ ## Task
52
+
53
+ Evaluate the models on the basis of the quality and relevance of their results, and select the model that generated the best result. Reply with the identifier of the best model. Our evaluation will only take into account the first character of your answer, so make sure it contains only one of the identifiers and nothing else (no quotation marks, no spaces, no new lines, ...).
54
+ '''
55
+
56
+
57
+ def _ensure_llm_blender_importable() -> None:
58
+ """
59
+ Pre-import shim to work around a known `llm-blender` issue.
60
+
61
+ As of `llm-blender` v0.0.2 (see upstream issue: https://github.com/yuchenlin/LLM-Blender/issues/33), importing
62
+ `llm_blender` may fail on `transformers` >= 5.0.0 because it unconditionally accesses
63
+ `transformers.utils.hub.TRANSFORMERS_CACHE`.
64
+
65
+ We set this attribute to a dummy value before importing `llm_blender` so that the import succeeds. This helper is
66
+ intentionally a no-op on older `transformers` versions.
67
+
68
+ This shim can be removed once the upstream issue is fixed and the minimum required `llm-blender` version includes
69
+ that fix.
70
+ """
71
+ import transformers.utils.hub
72
+
73
+ if Version(transformers.__version__) >= Version("5.0.0"):
74
+ transformers.utils.hub.TRANSFORMERS_CACHE = None # unused; just needs to exist
75
+
76
+
77
+ class BaseJudge(ABC):
78
+ """
79
+ Base class for judges. The subclasses of this class should implement the `judge` method.
80
+ """
81
+
82
+ @abstractmethod
83
+ def judge(self, prompts: list[str], completions: list[str], shuffle_order: bool = True) -> list:
84
+ raise NotImplementedError("Judge subclasses must implement the `judge` method.")
85
+
86
+
87
+ class BaseRankJudge(ABC):
88
+ """
89
+ Base class for LLM ranking judges.
90
+
91
+ **Example**:
92
+ ```python
93
+ class MyRankJudge(BaseRankJudge):
94
+ def judge(self, prompts, completions, shuffle_order=True):
95
+ return ... # Your ranking logic here
96
+
97
+
98
+ judge = MyRankJudge()
99
+ judge.judge(
100
+ prompts=["The capital of France is", "The capital of Germany is"],
101
+ completions=[[" Paris", " Marseille", "Lyon"], [" Munich", " Berlin"]],
102
+ ) # [[0, 1, 2], [1, 0]]
103
+ ```
104
+ """
105
+
106
+ @abstractmethod
107
+ def judge(self, prompts: list[str], completions: list[list[str]], shuffle_order: bool = True) -> list[list[int]]:
108
+ """
109
+ Judge the completion for the given prompts and return the ranks of each completion.
110
+
111
+ Args:
112
+ prompts (`list[str]`):
113
+ List of prompts.
114
+ completions (`list[list[str]]`):
115
+ List of completions list, where each element is a list of completions for the corresponding prompt.
116
+ shuffle_order (`bool`, *optional*, defaults to `True`):
117
+ Whether to shuffle the order of the completions to avoid positional bias.
118
+
119
+ Returns:
120
+ `list[list[int]]`:
121
+ List of lists of idxs, where each list contains the ranks of the completions for the corresponding
122
+ prompt. E.g., `[1, 2, 0]` means that the second completion (`idx=1`) is the best, followed by the
123
+ third, and then the first.
124
+ """
125
+ raise NotImplementedError("Judge subclasses must implement the `judge` method.")
126
+
127
+
128
+ class BasePairwiseJudge(BaseJudge):
129
+ """
130
+ Base class for pairwise judges.
131
+ """
132
+
133
+ @abstractmethod
134
+ def judge(self, prompts: list[str], completions: list[list[str]], shuffle_order: bool = True) -> list[int]:
135
+ """
136
+ Judge the completion pairs for the given prompts.
137
+
138
+ Args:
139
+ prompts (`list[str]`):
140
+ List of prompts.
141
+ completions (`list[list[str]]`):
142
+ List of completions pairs, where each element is a pair of completions for the corresponding prompt.
143
+ shuffle_order (`bool`, *optional*, defaults to `True`):
144
+ Whether to shuffle the order of the completions to avoid positional bias.
145
+
146
+ Returns:
147
+ `list[int]`:
148
+ List of idxs, where each idx is the rank of the best completion for the corresponding prompt. E.g., `1`
149
+ means that the second completion (`idx=1`) is the best.
150
+
151
+ Note:
152
+ If the judge returns `-1` for any prompt, it indicates that the inner process used to compute the
153
+ preference has failed. For instance, this could occur if the underlying language model returned an invalid
154
+ answer. In such cases, the caller should handle these invalid indices appropriately, possibly by
155
+ implementing fallback logic or error handling.
156
+ """
157
+ raise NotImplementedError("Judge subclasses must implement the `judge` method.")
158
+
159
+
160
+ class BaseBinaryJudge(BaseJudge):
161
+ """
162
+ Base class for binary judges.
163
+ """
164
+
165
+ @abstractmethod
166
+ def judge(
167
+ self,
168
+ prompts: list[str],
169
+ completions: list[str],
170
+ gold_completions: list[str] | None = None,
171
+ shuffle_order: bool = True,
172
+ ) -> list[int]:
173
+ """
174
+ Judge the completion for a given prompt. Used to assess if a completion satisfies a constraint.
175
+
176
+ This base class should be used to implement binary evaluations as done in section 4.1.4 of the [CGPO
177
+ paper](https://huggingface.co/papers/2409.20370). It is relevant for assessing whether a prompt-completion pair
178
+ satisfies a specific constraint.
179
+
180
+ Args:
181
+ prompts (`list[str]`): List of prompts.
182
+ completions (`list[str]`): List of completions.
183
+ gold_completions (`list[str]`, `optional`): List of gold completions if it exists.
184
+ shuffle_order (`bool`): Whether to shuffle the order of the completions to avoid positional bias.
185
+
186
+ Returns:
187
+ list[int]: A list of binary labels:
188
+ - 1 indicates that the completion satisfies the evaluated constraint.
189
+ - 0 indicates that the completion does not satisfy the evaluated constraint.
190
+
191
+ Note:
192
+ If the judge returns -1 for any prompt, it indicates that the inner process used to compute the preference
193
+ has failed. For instance, this could occur if the underlying language model or rule based constraint
194
+ returned an invalid answer. In such cases, the caller should handle these invalid indices appropriately,
195
+ possibly by implementing fallback logic or error handling.
196
+ """
197
+ raise NotImplementedError("Judge subclasses must implement the `judge` method.")
198
+
199
+
200
+ class PairRMJudge(BasePairwiseJudge):
201
+ # docstyle-ignore
202
+ """
203
+ LLM judge based on the PairRM model from AllenAI.
204
+
205
+ This judge uses the PairRM model to rank pairs of completions for given prompts. It's designed for pairwise
206
+ comparison of language model outputs. The PairRM model is loaded using the llm-blender library and runs on the
207
+ default Accelerator device.
208
+
209
+ **Attributes**:
210
+
211
+ blender (`llm_blender.Blender`):
212
+ An instance of the Blender class from llm-blender.
213
+
214
+ **Example**:
215
+ ```python
216
+ >>> pairrm_judge = PairRMJudge()
217
+ >>> prompts = ["Translate 'hello' to French", "What's the capital of Japan?"]
218
+ >>> completions = [["Bonjour", "Salut"], ["Kyoto", "Tokyo"]]
219
+ >>> results = pairrm_judge.judge(prompts, completions)
220
+ >>> print(results) # [0, 1] (indicating the first completion is preferred for the first prompt and the second)
221
+ ```
222
+
223
+ > [!TIP]
224
+ > This class requires the llm-blender library to be installed. Install it with: `pip install llm-blender`.
225
+ """
226
+
227
+ def __init__(self):
228
+ if not is_llm_blender_available():
229
+ raise ValueError("llm-blender is not installed. Please install it with `pip install llm-blender`.")
230
+ import transformers
231
+
232
+ if Version(transformers.__version__) >= Version("5.0.0"):
233
+ raise RuntimeError(
234
+ "llm-blender currently supports transformers < 5.0.0. Please install a compatible version: `pip install 'transformers<5.0.0'`. Check the issue tracker for updates: https://github.com/huggingface/trl/issues/4918"
235
+ )
236
+ _ensure_llm_blender_importable()
237
+ import llm_blender
238
+
239
+ self.blender = llm_blender.Blender()
240
+ self.blender.loadranker("llm-blender/PairRM", device=Accelerator().device)
241
+
242
+ def judge(
243
+ self,
244
+ prompts: list[str],
245
+ completions: list[list[str]],
246
+ shuffle_order: bool = True,
247
+ return_scores: bool = False,
248
+ temperature: float = 1.0,
249
+ ) -> list[int | float]:
250
+ """
251
+ Judge the completion pairs for the given prompts using the PairRM model.
252
+
253
+ Args:
254
+ prompts (`list[str]`):
255
+ List of prompts to judge.
256
+ completions (`list[list[str]]`):
257
+ List of completion pairs for each prompt.
258
+ shuffle_order (`bool`, *optional*, defaults to `True`):
259
+ Whether to shuffle the order of the completions to avoid positional bias.
260
+ return_scores (`bool`, *optional*, defaults to `False`):
261
+ If `True`, return probability scores of the first completion instead of ranks (i.e. a *soft-judge*).
262
+ temperature (`float`, *optional*, defaults to `1.0`):
263
+ Temperature for scaling logits if `return_scores` is True.
264
+
265
+ Returns:
266
+ `list[int | float]`:
267
+ If `return_scores` is `False`, returns a list of ranks (`0` or `1`) for each prompt, indicating which
268
+ completion is preferred. If `return_scores` is `True`, returns softmax probabilities for the first
269
+ completion.
270
+
271
+ Raises:
272
+ `ValueError`:
273
+ If the number of completions per prompt is not exactly 2.
274
+
275
+ Note:
276
+ Unlike llm-blender, ranks are 0-indexed (`0` means the first completion is preferred).
277
+ """
278
+
279
+ if len(completions[0]) != 2:
280
+ raise ValueError("PairRM judge requires exactly 2 completions per prompt.")
281
+
282
+ # Shuffle the order of the completions to avoid positional bias
283
+ if shuffle_order:
284
+ flip_mask = np.random.choice([True, False], size=len(prompts))
285
+ completions = [pair[::-1] if flip else pair for flip, pair in zip(flip_mask, completions, strict=True)]
286
+
287
+ # Rank the completions
288
+ ranks = self.blender.rank(prompts, completions, return_scores=return_scores, disable_tqdm=True)
289
+ if not return_scores:
290
+ ranks -= 1 # PairRM rank is 1-indexed, so we subtract 1 to make it 0-indexed
291
+ else:
292
+ # scale the logits by temperature
293
+ ranks /= temperature
294
+
295
+ # Flip back the ranks or scores to the original order if needed
296
+ if shuffle_order:
297
+ ranks[flip_mask] = ranks[flip_mask][:, ::-1]
298
+
299
+ # Return the ranks or score probability
300
+ if return_scores:
301
+ logit_max = np.amax(ranks, axis=-1, keepdims=True)
302
+ exp_logit_shifted = np.exp(ranks - logit_max)
303
+ probs = exp_logit_shifted / np.sum(exp_logit_shifted, axis=-1, keepdims=True)
304
+ return probs[:, 0].tolist()
305
+ else:
306
+ return ranks[:, 0].tolist()
307
+
308
+
309
+ class HfPairwiseJudge(BasePairwiseJudge):
310
+ """
311
+ Pairwise judge based on the Hugging Face API with chat completion.
312
+
313
+ This judge is relevant for assessing the quality chat models, where the completion is a response to a given prompt.
314
+
315
+ Args:
316
+ model (`str`, *optional*, defaults to `"meta-llama/Meta-Llama-3-70B-Instruct"`):
317
+ Model to use for the judge.
318
+ token (`str`, *optional*):
319
+ Hugging Face API token to use for the [`huggingface_hub.InferenceClient`].
320
+ system_prompt (`str`, *optional*):
321
+ The system prompt to be used for the judge. If not provided, a default prompt is used. Note that the system
322
+ prompt should contain the following placeholders: `{prompt}`, `{response0}`, and `{response1}`. Also, the
323
+ inference is called with `max_tokens=1`, consequently the system prompt should ask for a single token
324
+ response.
325
+ """
326
+
327
+ def __init__(
328
+ self,
329
+ model="meta-llama/Meta-Llama-3-70B-Instruct",
330
+ token: str | None = None,
331
+ system_prompt: str | None = None,
332
+ ):
333
+ self.client = InferenceClient(model=model, token=token)
334
+ self.system_prompt = system_prompt or DEFAULT_PAIRWISE_SYSTEM_PROMPT
335
+
336
+ def judge(self, prompts: list[str], completions: list[list[str]], shuffle_order: bool = True) -> list[int]:
337
+ # Shuffle the order of the completions to avoid positional bias
338
+ if shuffle_order:
339
+ flip_mask = np.random.choice([True, False], size=len(prompts))
340
+ completions = [pair[::-1] if flip else pair for flip, pair in zip(flip_mask, completions, strict=True)]
341
+
342
+ # Define a function to get the rank for a single prompt, will be called concurrently
343
+ def get_rank(prompt, candidates):
344
+ content = self.system_prompt.format(prompt=prompt, response0=candidates[0], response1=candidates[1])
345
+ completion = self.client.chat_completion(messages=[{"role": "user", "content": content}], max_tokens=1)
346
+ response = completion.choices[0].message.content
347
+ if response in ["0", "1"]:
348
+ return int(response)
349
+ else:
350
+ logging.debug(f"Invalid response from the judge model: '{response}'. Returning -1.")
351
+ return -1
352
+
353
+ # Call the completions concurrently
354
+ with concurrent.futures.ThreadPoolExecutor() as executor:
355
+ ranks = list(executor.map(get_rank, prompts, completions))
356
+
357
+ # Flip back the ranks to the original order if needed
358
+ if shuffle_order:
359
+ ranks = [ranks[i] if not flip else 1 - ranks[i] for i, flip in enumerate(flip_mask)]
360
+
361
+ # Return the ranks
362
+ return ranks
363
+
364
+
365
+ class OpenAIPairwiseJudge(BasePairwiseJudge):
366
+ """
367
+ Judge based on the OpenAI API.
368
+
369
+ This judge is relevant for assessing the quality chat models, where the completion is a response to a given prompt.
370
+
371
+ Args:
372
+ model (`str`, *optional*, defaults to `"gpt-4-turbo-preview"`):
373
+ Model to use for the judge.
374
+ system_prompt (`str`, *optional*):
375
+ System prompt to be used for the judge. If not provided, a default prompt is used. Note that the system
376
+ prompt should contain the following placeholders: `{prompt}`, `{response0}`, and `{response1}`. Also, the
377
+ inference is called with `max_tokens=1`, consequently the system prompt should ask for a single token
378
+ response.
379
+ max_requests (`int` or `None`, *optional*, defaults to `1000`):
380
+ Maximum number of requests to make to the OpenAI API. If set to `None`, there is no limit.
381
+ """
382
+
383
+ def __init__(
384
+ self, model="gpt-4-turbo-preview", system_prompt: str | None = None, max_requests: int | None = 1_000
385
+ ):
386
+ if not is_openai_available():
387
+ raise ValueError("OpenAI client is not installed. Please install it with 'pip install openai'.")
388
+ from openai import OpenAI
389
+
390
+ self.client = OpenAI()
391
+ self.model = model
392
+ self.system_prompt = system_prompt or DEFAULT_PAIRWISE_SYSTEM_PROMPT
393
+ self.max_requests = max_requests
394
+ self.num_requests = 0
395
+ self._warned = False
396
+
397
+ def judge(self, prompts: list[str], completions: list[list[str]], shuffle_order: bool = True) -> list[int]:
398
+ # Check if the limit of requests is reached, if so, use random choice instead
399
+ if self.max_requests is not None and self.num_requests >= self.max_requests:
400
+ if not self._warned: # Print the warning only once
401
+ logging.warning(
402
+ f"Reached the maximum number of requests ({self.max_requests}). From now on, returning -1 instead. "
403
+ " To increase the limit, set `max_requests` to a higher value, or to `None` for no limit."
404
+ )
405
+ self._warned = True
406
+ return [-1] * len(prompts)
407
+
408
+ # Shuffle the order of the completions to avoid positional bias
409
+ if shuffle_order:
410
+ flip_mask = np.random.choice([True, False], size=len(prompts))
411
+ completions = [pair[::-1] if flip else pair for flip, pair in zip(flip_mask, completions, strict=True)]
412
+
413
+ # Define a function to get the rank for a single prompt, will be called concurrently
414
+ def get_rank(prompt, candidates):
415
+ content = self.system_prompt.format(prompt=prompt, response0=candidates[0], response1=candidates[1])
416
+ messages = [{"role": "user", "content": content}]
417
+ completion = self.client.chat.completions.create(model=self.model, messages=messages, max_tokens=1)
418
+ response = completion.choices[0].message.content
419
+ if response in ["0", "1"]:
420
+ return int(response)
421
+ else:
422
+ logging.debug(f"Invalid response from the judge model: '{response}'. Returning -1.")
423
+ return -1
424
+
425
+ # Call the completions concurrently
426
+ with concurrent.futures.ThreadPoolExecutor() as executor:
427
+ ranks = list(executor.map(get_rank, prompts, completions))
428
+
429
+ # Flip back the ranks to the original order if needed
430
+ if shuffle_order:
431
+ ranks = [ranks[i] if not flip else 1 - ranks[i] for i, flip in enumerate(flip_mask)]
432
+
433
+ # Update the number of requests
434
+ self.num_requests += len(prompts)
435
+
436
+ # Return the ranks
437
+ return ranks
438
+
439
+
440
+ class AllTrueJudge(BaseBinaryJudge):
441
+ """
442
+ Unify the decision of multiple [`experimental.judges.BaseBinaryJudge`] instances.
443
+
444
+ Returns `1` only if all inner binary judges return `1`. If any judge returns `0`, it returns `0`. If any judge
445
+ returns `-1`, indicating a failure in its process, this judge will also return `-1`.
446
+
447
+ Implements the Mixture of Judges as described in the [CGPO paper](https://huggingface.co/papers/2409.20370).
448
+
449
+ Args:
450
+ judges (`list` of [`experimental.judges.BaseBinaryJudge`]):
451
+ A list of [`experimental.judges.BaseBinaryJudge`] instances whose decisions will be unified.
452
+ """
453
+
454
+ def __init__(self, judges: list[BaseBinaryJudge]):
455
+ self.judges = judges
456
+
457
+ def judge(
458
+ self,
459
+ prompts: list[str],
460
+ completions: list[str],
461
+ gold_completions: list[str] | None = None,
462
+ shuffle_order: bool = True,
463
+ ) -> list[int]:
464
+ all_binary_judgments = [
465
+ judge.judge(prompts, completions, gold_completions, shuffle_order) for judge in self.judges
466
+ ]
467
+ output = []
468
+ for binary_judgments in zip(*all_binary_judgments, strict=True):
469
+ # Check that all values are in {0, 1, -1}
470
+ if any(binary_judgment not in {0, 1, -1} for binary_judgment in binary_judgments):
471
+ raise ValueError(
472
+ f"Invalid binary judgment: {binary_judgments}, expected list of values in {{0, 1, -1}}."
473
+ )
474
+
475
+ # Unify the decision
476
+ if -1 in binary_judgments:
477
+ output.append(-1)
478
+ elif all(binary_judgment == 1 for binary_judgment in binary_judgments):
479
+ output.append(1)
480
+ else:
481
+ output.append(0)
482
+ return output
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/kto/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .kto_config import KTOConfig
16
+ from .kto_trainer import KTOTrainer
17
+
18
+
19
+ __all__ = ["KTOConfig", "KTOTrainer"]
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/kto/kto_config.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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, field
16
+ from typing import Any
17
+
18
+ from ...trainer.base_config import _BaseConfig
19
+
20
+
21
+ @dataclass
22
+ class KTOConfig(_BaseConfig):
23
+ # docstyle-ignore
24
+ r"""
25
+ Configuration class for the [`experimental.kto.KTOTrainer`].
26
+
27
+ This class includes only the parameters that are specific to KTO training. For a full list of training arguments,
28
+ please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
29
+ differ from those in [`~transformers.TrainingArguments`].
30
+
31
+ Using [`~transformers.HfArgumentParser`] we can turn this class into
32
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
33
+ command line.
34
+
35
+ Parameters:
36
+ > Parameters that control the model
37
+
38
+ model_init_kwargs (`dict[str, Any]`, *optional*):
39
+ Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model`
40
+ argument of the [`KTOTrainer`] is provided as a string.
41
+ disable_dropout (`bool`, *optional*, defaults to `True`):
42
+ Whether to disable dropout in the model and reference model.
43
+
44
+ > Parameters that control the data preprocessing
45
+
46
+ dataset_num_proc (`int`, *optional*):
47
+ Number of processes to use for processing the dataset.
48
+ max_length (`int` or `None`, *optional*, defaults to `1024`):
49
+ Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the left.
50
+ If `None`, no truncation is applied.
51
+ precompute_ref_log_probs (`bool`, *optional*, defaults to `False`):
52
+ Whether to precompute the reference model log probabilities for the entire training dataset before
53
+ training. This allows to save memory during training, as the reference model does not need to be kept in
54
+ memory.
55
+
56
+ > Parameters that control the training
57
+
58
+ loss_type (`str`, *optional*, defaults to `"kto"`):
59
+ Type of loss to use. Possible values are:
60
+
61
+ - `"kto"`: KTO loss from the [KTO](https://huggingface.co/papers/2402.01306) paper.
62
+ - `"apo_zero_unpaired"`: Unpaired variant of APO-zero loss from the
63
+ [APO](https://huggingface.co/papers/2408.06266) paper.
64
+
65
+ beta (`float`, *optional*, defaults to `0.1`):
66
+ Parameter controlling the deviation from the reference model. Higher β means less deviation from the
67
+ reference model.
68
+ desirable_weight (`float`, *optional*, defaults to `1.0`):
69
+ Desirable losses are weighed by this factor to counter unequal number of desirable and undesirable pairs.
70
+ undesirable_weight (`float`, *optional*, defaults to `1.0`):
71
+ Undesirable losses are weighed by this factor to counter unequal number of desirable and undesirable pairs.
72
+ generate_during_eval (`bool`, *optional*, defaults to `False`):
73
+ If `True`, generates and logs completions from both the model and the reference model to W&B or Comet
74
+ during evaluation.
75
+
76
+ > [!NOTE]
77
+ > These parameters have default values different from [`~transformers.TrainingArguments`]:
78
+ > - `logging_steps`: Defaults to `10` instead of `500`.
79
+ > - `gradient_checkpointing`: Defaults to `True` instead of `False`.
80
+ > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
81
+ > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.
82
+ """
83
+
84
+ _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
85
+
86
+ # Parameters whose default values are overridden from TrainingArguments
87
+ learning_rate: float = field(
88
+ default=1e-6,
89
+ metadata={"help": "The initial learning rate for AdamW."},
90
+ )
91
+
92
+ # Parameters that control the model
93
+ model_init_kwargs: dict[str, Any] | str | None = field(
94
+ default=None,
95
+ metadata={
96
+ "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of "
97
+ "the `KTOTrainer` is provided as a string."
98
+ },
99
+ )
100
+ disable_dropout: bool = field(
101
+ default=True,
102
+ metadata={"help": "Whether to disable dropout in the model and reference model."},
103
+ )
104
+
105
+ # Parameters that control the data preprocessing
106
+ dataset_num_proc: int | None = field(
107
+ default=None,
108
+ metadata={"help": "Number of processes to use for processing the dataset."},
109
+ )
110
+ max_length: int | None = field(
111
+ default=1024,
112
+ metadata={
113
+ "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from "
114
+ "the left. If `None`, no truncation is applied."
115
+ },
116
+ )
117
+ precompute_ref_log_probs: bool = field(
118
+ default=False,
119
+ metadata={
120
+ "help": "Whether to precompute the reference model log probabilities for the entire training dataset "
121
+ "before training. This allows to save memory during training, as the reference model does not need to be "
122
+ "kept in memory."
123
+ },
124
+ )
125
+
126
+ # Parameters that control the training
127
+ loss_type: str = field(
128
+ default="kto",
129
+ metadata={
130
+ "help": "Type of loss to use.",
131
+ "choices": ["kto", "apo_zero_unpaired"],
132
+ },
133
+ )
134
+ beta: float = field(
135
+ default=0.1,
136
+ metadata={
137
+ "help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from "
138
+ "the reference model."
139
+ },
140
+ )
141
+ desirable_weight: float = field(
142
+ default=1.0,
143
+ metadata={
144
+ "help": "Desirable losses are weighed by this factor to counter unequal number of desirable and "
145
+ "undesirable pairs.",
146
+ },
147
+ )
148
+ undesirable_weight: float = field(
149
+ default=1.0,
150
+ metadata={
151
+ "help": "Undesirable losses are weighed by this factor to counter unequal number of desirable and "
152
+ "undesirable pairs.",
153
+ },
154
+ )
155
+ generate_during_eval: bool = field(
156
+ default=False,
157
+ metadata={
158
+ "help": "If `True`, generates and logs completions from both the model and the reference model to W&B "
159
+ "during evaluation."
160
+ },
161
+ )
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/kto/kto_trainer.py ADDED
@@ -0,0 +1,1451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 inspect
16
+ import random
17
+ import textwrap
18
+ from collections import defaultdict
19
+ from collections.abc import Callable
20
+ from contextlib import contextmanager, nullcontext
21
+ from operator import itemgetter
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING, Any, Literal
24
+
25
+ import numpy as np
26
+ import pandas as pd
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+ import transformers
31
+ from accelerate import PartialState, logging
32
+ from accelerate.utils import tqdm
33
+ from datasets import Dataset, concatenate_datasets
34
+ from packaging.version import Version
35
+ from torch import autocast
36
+ from torch.utils.data import DataLoader, SequentialSampler
37
+ from transformers import (
38
+ BaseImageProcessor,
39
+ DataCollator,
40
+ FeatureExtractionMixin,
41
+ PreTrainedModel,
42
+ PreTrainedTokenizerBase,
43
+ ProcessorMixin,
44
+ TrainerCallback,
45
+ TrainingArguments,
46
+ is_comet_available,
47
+ is_wandb_available,
48
+ )
49
+ from transformers.trainer_utils import EvalLoopOutput, has_length
50
+ from transformers.utils import is_peft_available
51
+
52
+ from ...data_utils import maybe_apply_chat_template, maybe_extract_prompt, maybe_unpair_preference_dataset
53
+ from ...import_utils import is_liger_kernel_available
54
+ from ...models.utils import prepare_deepspeed
55
+ from ...trainer.base_trainer import _BaseTrainer
56
+ from ...trainer.utils import (
57
+ create_model_from_path,
58
+ disable_dropout_in_model,
59
+ log_table_to_comet_experiment,
60
+ selective_log_softmax,
61
+ )
62
+ from ..utils import DPODataCollatorWithPadding, create_reference_model, pad_to_length, peft_module_casting_to_bf16
63
+ from .kto_config import KTOConfig
64
+
65
+
66
+ if is_liger_kernel_available():
67
+ from liger_kernel.chunked_loss import LigerFusedLinearKTOLoss
68
+
69
+ if is_peft_available():
70
+ from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training
71
+
72
+ if is_wandb_available():
73
+ import wandb
74
+
75
+
76
+ if TYPE_CHECKING:
77
+ from transformers import PreTrainedModel, PreTrainedTokenizer
78
+
79
+
80
+ logger = logging.get_logger(__name__)
81
+
82
+ RUNNING_NAME = "running.pt"
83
+
84
+
85
+ def _get_kl_dataset(batch: dict[str, list[Any]]) -> dict[str, list[Any]]:
86
+ """
87
+ Creates mismatched pairs of prompts and completions for the KL dataset by adding a +1 offset to the order of
88
+ completions. For best results, the mismatched outputs y' used to estimate the KL term for a batch should be the
89
+ same set as the matched outputs y used to estimate the rewards in that batch, just paired with different x.
90
+ """
91
+ batch["answer_input_ids"] = [batch["answer_input_ids"][-1]] + batch["answer_input_ids"][:-1]
92
+ batch["answer_attention_mask"] = [batch["answer_attention_mask"][-1]] + batch["answer_attention_mask"][:-1]
93
+ return batch
94
+
95
+
96
+ def _tokenize(
97
+ batch: dict[str, list[Any]],
98
+ tokenizer: "PreTrainedTokenizer",
99
+ ) -> dict[str, list[Any]]:
100
+ """Tokenize a batch from a KTO specific dataset."""
101
+ prompt_tokenized = tokenizer(batch["prompt"], add_special_tokens=False)
102
+ prompt_input_ids = prompt_tokenized["input_ids"]
103
+ prompt_attention_mask = prompt_tokenized["attention_mask"]
104
+ prompt_and_completion = [
105
+ prompt + completion for prompt, completion in zip(batch["prompt"], batch["completion"], strict=True)
106
+ ]
107
+ full_tokenized = tokenizer(prompt_and_completion, add_special_tokens=False)
108
+ full_input_ids = full_tokenized["input_ids"]
109
+ full_attention_mask = full_tokenized["attention_mask"]
110
+
111
+ answer_input_ids = [f[len(p) :] for f, p in zip(full_input_ids, prompt_input_ids, strict=True)]
112
+ answer_attention_mask = [f[len(p) :] for f, p in zip(full_attention_mask, prompt_attention_mask, strict=True)]
113
+
114
+ # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]`
115
+ full_concat_input_ids = [np.concatenate([p, a]) for p, a in zip(prompt_input_ids, answer_input_ids, strict=True)]
116
+ # Prepare input tokens for token by token comparison
117
+ full_input_ids = [np.array(f) for f in full_input_ids]
118
+ for full, concat in zip(full_input_ids, full_concat_input_ids, strict=True):
119
+ if len(full) != len(concat):
120
+ raise ValueError(
121
+ "The elements in 'full_input_ids' and 'full_concat_input_ids' must have the same pairwise length."
122
+ )
123
+
124
+ # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens
125
+ # can be merged together when tokenizing prompt+answer. This could result
126
+ # on the last token from the prompt being different when tokenized on its own
127
+ # vs when done as prompt+answer.
128
+ response_token_ids_start_idx = [len(p) for p in prompt_input_ids]
129
+
130
+ # If tokenized prompt is different than both prompt+answer, then it means the
131
+ # last token has changed due to merging.
132
+ for idx, (p, f, r) in enumerate(zip(prompt_input_ids, full_input_ids, response_token_ids_start_idx, strict=True)):
133
+ if not np.array_equal(p, f[:r]):
134
+ response_token_ids_start_idx[idx] -= 1
135
+
136
+ prompt_input_ids = [f[:r] for f, r in zip(full_input_ids, response_token_ids_start_idx, strict=True)]
137
+ prompt_attention_mask = [f[:r] for f, r in zip(full_attention_mask, response_token_ids_start_idx, strict=True)]
138
+
139
+ for p, m in zip(prompt_input_ids, prompt_attention_mask, strict=True):
140
+ if len(p) != len(m):
141
+ raise ValueError("Prompt input ids and attention mask should have the same length.")
142
+
143
+ answer_input_ids = [f[r:] for f, r in zip(full_input_ids, response_token_ids_start_idx, strict=True)]
144
+ answer_attention_mask = [f[r:] for f, r in zip(full_attention_mask, response_token_ids_start_idx, strict=True)]
145
+
146
+ output = dict(
147
+ prompt_input_ids=prompt_input_ids,
148
+ prompt_attention_mask=prompt_attention_mask,
149
+ answer_input_ids=answer_input_ids,
150
+ answer_attention_mask=answer_attention_mask,
151
+ )
152
+
153
+ return output
154
+
155
+
156
+ def _process_tokens(example: dict[str, Any], model: "PreTrainedModel" = None, **kwargs) -> dict:
157
+ """Process tokens of a KTO specific dataset.
158
+
159
+ At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt +
160
+ completion responses is/are too long. We truncate from the end (completion) to fit within max_length.
161
+
162
+ We also create the labels for the completion responses, which are of length equal to the sum of the length of the
163
+ prompt and the completion response, with `-100` for the prompt tokens.
164
+ """
165
+ prompt = example["prompt"]
166
+ completion = example["completion"]
167
+
168
+ batch = {
169
+ f"{kwargs['prefix']}prompt": prompt,
170
+ f"{kwargs['prefix']}completion": completion,
171
+ f"{kwargs['prefix']}label": example["label"],
172
+ }
173
+
174
+ # Check issues below for more details
175
+ # 1. https://github.com/huggingface/trl/issues/907
176
+ # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
177
+ # 3. https://github.com/LianjiaTech/BELLE/issues/337
178
+
179
+ if not isinstance(prompt, str):
180
+ raise ValueError(f"prompt should be an str but got {type(prompt)}")
181
+
182
+ if not isinstance(completion, str):
183
+ raise ValueError(f"completion should be an str but got {type(completion)}")
184
+
185
+ # keys of format prompt_* refers to just the prompt and answer_* refers to just the answer
186
+ all_tokens = {
187
+ "prompt_input_ids": example["prompt_input_ids"],
188
+ "prompt_attention_mask": example["prompt_attention_mask"],
189
+ "answer_input_ids": example["answer_input_ids"],
190
+ "answer_attention_mask": example["answer_attention_mask"],
191
+ }
192
+
193
+ # calculate max length by checking if BOS/EOS is already there
194
+ max_length = kwargs["max_length"]
195
+ bos_token_id = kwargs["tokenizer"].bos_token_id
196
+ eos_token_id = kwargs["tokenizer"].eos_token_id
197
+ if len(all_tokens["prompt_input_ids"]) > 0 and bos_token_id != all_tokens["prompt_input_ids"][0]:
198
+ max_length -= 1
199
+ if len(all_tokens["answer_input_ids"]) > 0 and eos_token_id != all_tokens["answer_input_ids"][-1]:
200
+ max_length -= 1
201
+
202
+ # if combined sequence is too long, truncate the completion (answer) from the end
203
+ prompt_length = len(all_tokens["prompt_input_ids"])
204
+ completion_length = len(all_tokens["answer_input_ids"])
205
+ if prompt_length + completion_length > max_length:
206
+ max_completion_length = max_length - prompt_length
207
+ for k in ["answer_input_ids", "answer_attention_mask"]:
208
+ all_tokens[k] = all_tokens[k][:max_completion_length]
209
+
210
+ # all input_ids and attention mask as is. We then check if we need to add BOS/EOS tokens
211
+ batch[f"{kwargs['prefix']}prompt_input_ids"] = all_tokens["prompt_input_ids"]
212
+ batch[f"{kwargs['prefix']}prompt_attention_mask"] = all_tokens["prompt_attention_mask"]
213
+ batch[f"{kwargs['prefix']}completion_input_ids"] = all_tokens["prompt_input_ids"] + all_tokens["answer_input_ids"]
214
+ batch[f"{kwargs['prefix']}completion_attention_mask"] = (
215
+ all_tokens["prompt_attention_mask"] + all_tokens["answer_attention_mask"]
216
+ )
217
+
218
+ # add BOS, which affects both prompt and the full completion
219
+ if bos_token_id is not None:
220
+ if len(all_tokens["prompt_input_ids"]) == 0 or bos_token_id != all_tokens["prompt_input_ids"][0]:
221
+ batch[f"{kwargs['prefix']}prompt_input_ids"] = [bos_token_id] + batch[
222
+ f"{kwargs['prefix']}prompt_input_ids"
223
+ ]
224
+ batch[f"{kwargs['prefix']}prompt_attention_mask"] = [1] + batch[f"{kwargs['prefix']}prompt_attention_mask"]
225
+ batch[f"{kwargs['prefix']}completion_input_ids"] = [bos_token_id] + batch[
226
+ f"{kwargs['prefix']}completion_input_ids"
227
+ ]
228
+ batch[f"{kwargs['prefix']}completion_attention_mask"] = [1] + batch[
229
+ f"{kwargs['prefix']}completion_attention_mask"
230
+ ]
231
+ # add EOS, which affects only the full completion
232
+ if len(all_tokens["answer_input_ids"]) == 0 or eos_token_id != all_tokens["answer_input_ids"][-1]:
233
+ batch[f"{kwargs['prefix']}completion_input_ids"] = batch[f"{kwargs['prefix']}completion_input_ids"] + [
234
+ eos_token_id
235
+ ]
236
+ batch[f"{kwargs['prefix']}completion_attention_mask"] = batch[
237
+ f"{kwargs['prefix']}completion_attention_mask"
238
+ ] + [1]
239
+
240
+ batch[f"{kwargs['prefix']}completion_labels"] = batch[f"{kwargs['prefix']}completion_input_ids"][:]
241
+ batch[f"{kwargs['prefix']}completion_labels"][: len(batch[f"{kwargs['prefix']}prompt_input_ids"])] = [-100] * len(
242
+ batch[f"{kwargs['prefix']}prompt_input_ids"]
243
+ )
244
+
245
+ return batch
246
+
247
+
248
+ class KTOTrainer(_BaseTrainer):
249
+ r"""
250
+ Initialize KTOTrainer.
251
+
252
+ Args:
253
+ model ([`~transformers.PreTrainedModel`]):
254
+ The model to train, preferably an [`~transformers.AutoModelForSequenceClassification`].
255
+ ref_model ([`~transformers.PreTrainedModel`]):
256
+ Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation
257
+ and loss. If no reference model is provided, the trainer will create a reference model with the same
258
+ architecture as the model to be optimized.
259
+ args ([`experimental.kto.KTOConfig`]):
260
+ The arguments to use for training.
261
+ train_dataset ([`~datasets.Dataset`]):
262
+ The dataset to use for training.
263
+ eval_dataset ([`~datasets.Dataset`]):
264
+ The dataset to use for evaluation.
265
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
266
+ Processing class used to process the data. If provided, will be used to automatically process the inputs
267
+ for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
268
+ reuse the fine-tuned model.
269
+ data_collator ([`~transformers.DataCollator`], *optional*):
270
+ The data collator to use for training. If None is specified, the default data collator
271
+ ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the
272
+ maximum length of the sequences in the batch, given a dataset of paired sequences.
273
+ model_init (`Callable[[], transformers.PreTrainedModel]`):
274
+ The model initializer to use for training. If None is specified, the default model initializer will be
275
+ used.
276
+ callbacks (`list[transformers.TrainerCallback]`):
277
+ The callbacks to use for training.
278
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
279
+ The optimizer and scheduler to use for training.
280
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
281
+ The function to use to preprocess the logits before computing the metrics.
282
+ peft_config (`dict`, defaults to `None`):
283
+ The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in
284
+ a PEFT model.
285
+ compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
286
+ The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
287
+ metric values.
288
+ model_adapter_name (`str`, defaults to `None`):
289
+ Name of the train target PEFT adapter, when using LoRA with multiple adapters.
290
+ ref_adapter_name (`str`, defaults to `None`):
291
+ Name of the reference PEFT adapter, when using LoRA with multiple adapters.
292
+ """
293
+
294
+ _tag_names = ["trl", "kto"]
295
+ _name = "KTO"
296
+ _paper = {
297
+ "title": "KTO: Model Alignment as Prospect Theoretic Optimization",
298
+ "id": "2402.01306",
299
+ # docstyle-ignore
300
+ "citation": textwrap.dedent("""\
301
+ @article{ethayarajh2024kto,
302
+ title = {{KTO: Model Alignment as Prospect Theoretic Optimization}},
303
+ author = {Kawin Ethayarajh and Winnie Xu and Niklas Muennighoff and Dan Jurafsky and Douwe Kiela},
304
+ year = 2024,
305
+ eprint = {arXiv:2402.01306},
306
+ }"""),
307
+ }
308
+
309
+ def __init__(
310
+ self,
311
+ model: PreTrainedModel | nn.Module | str = None,
312
+ ref_model: PreTrainedModel | nn.Module | str | None = None,
313
+ args: KTOConfig = None,
314
+ train_dataset: Dataset | None = None,
315
+ eval_dataset: Dataset | dict[str, Dataset] | None = None,
316
+ processing_class: PreTrainedTokenizerBase
317
+ | BaseImageProcessor
318
+ | FeatureExtractionMixin
319
+ | ProcessorMixin
320
+ | None = None,
321
+ data_collator: DataCollator | None = None,
322
+ model_init: Callable[[], PreTrainedModel] | None = None,
323
+ callbacks: list[TrainerCallback] | None = None,
324
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
325
+ preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
326
+ peft_config: dict | None = None,
327
+ compute_metrics: Callable[[EvalLoopOutput], dict] | None = None,
328
+ model_adapter_name: str | None = None,
329
+ ref_adapter_name: str | None = None,
330
+ ):
331
+ if type(args) is TrainingArguments:
332
+ raise ValueError("Please use `KTOConfig` instead TrainingArguments.")
333
+
334
+ if train_dataset is None:
335
+ raise ValueError("`train_dataset` is required")
336
+
337
+ if not isinstance(model, str) and ref_model is model:
338
+ raise ValueError(
339
+ "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the "
340
+ "same as `model`, you must mass a copy of it, or `None` if you use peft."
341
+ )
342
+
343
+ # Model initialization
344
+ if isinstance(model, str):
345
+ model_init_kwargs = args.model_init_kwargs or {}
346
+ # Distributed training requires device_map=None ("auto" fails)
347
+ if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
348
+ model_init_kwargs["device_map"] = None
349
+ model = create_model_from_path(model, **model_init_kwargs)
350
+ else:
351
+ if args.model_init_kwargs is not None:
352
+ logger.warning(
353
+ "You passed `model_init_kwargs` to the KTOConfig, but your model is already instantiated. "
354
+ "The `model_init_kwargs` will be ignored."
355
+ )
356
+
357
+ # Reference model initialization
358
+ if isinstance(ref_model, str):
359
+ ref_model_init_kwargs = args.model_init_kwargs or {}
360
+ # Distributed training requires device_map=None ("auto" fails)
361
+ if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
362
+ ref_model_init_kwargs["device_map"] = None
363
+ ref_model = create_model_from_path(ref_model, **ref_model_init_kwargs)
364
+
365
+ # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16`
366
+ # has been called in order to properly call autocast if needed.
367
+ self._peft_has_been_casted_to_bf16 = False
368
+
369
+ if not is_peft_available() and peft_config is not None:
370
+ raise ValueError(
371
+ "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it with `pip install peft` to use the PEFT models"
372
+ )
373
+ elif is_peft_available() and peft_config is not None:
374
+ if isinstance(model, PeftModel):
375
+ raise ValueError(
376
+ "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first "
377
+ "merge and unload the existing adapter, save the resulting base model, and then pass that base "
378
+ "model along with the new `peft_config` to the trainer."
379
+ )
380
+
381
+ if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False):
382
+ _support_gc_kwargs = hasattr(
383
+ args, "gradient_checkpointing_kwargs"
384
+ ) and "gradient_checkpointing_kwargs" in list(
385
+ inspect.signature(prepare_model_for_kbit_training).parameters
386
+ )
387
+
388
+ prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing}
389
+
390
+ if _support_gc_kwargs:
391
+ prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs
392
+
393
+ model = prepare_model_for_kbit_training(model, **prepare_model_kwargs)
394
+ elif args.gradient_checkpointing:
395
+ # For backward compatibility with older versions of transformers
396
+ if hasattr(model, "enable_input_require_grads"):
397
+ model.enable_input_require_grads()
398
+ else:
399
+
400
+ def make_inputs_require_grad(module, input, output):
401
+ output.requires_grad_(True)
402
+
403
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
404
+
405
+ # get peft model with the given config
406
+ model = get_peft_model(model, peft_config)
407
+ if args.bf16 and getattr(model, "is_loaded_in_4bit", False):
408
+ peft_module_casting_to_bf16(model)
409
+ # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager
410
+ self._peft_has_been_casted_to_bf16 = True
411
+
412
+ # For models that use gradient_checkpointing, we need to attach a hook that enables input
413
+ # to explicitly have `requires_grad=True`, otherwise training will either silently
414
+ # fail or completely fail.
415
+ elif args.gradient_checkpointing:
416
+ # For backward compatibility with older versions of transformers
417
+ if hasattr(model, "enable_input_require_grads"):
418
+ model.enable_input_require_grads()
419
+ else:
420
+
421
+ def make_inputs_require_grad(module, input, output):
422
+ output.requires_grad_(True)
423
+
424
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
425
+
426
+ if args.generate_during_eval and not (is_wandb_available() or is_comet_available()):
427
+ raise ValueError(
428
+ "`generate_during_eval=True` requires Weights and Biases or Comet to be installed."
429
+ " Please install `wandb` or `comet-ml` to resolve."
430
+ )
431
+
432
+ # KTO only supports causal language models, not encoder-decoder models
433
+ if model is not None and hasattr(model.config, "is_encoder_decoder") and model.config.is_encoder_decoder:
434
+ raise ValueError(
435
+ "KTO only supports causal language models. Encoder-decoder models are not supported. "
436
+ "Please use a causal LM (e.g., GPT, Llama, Mistral) instead of an encoder-decoder model (e.g., T5, BART)."
437
+ )
438
+
439
+ self.is_peft_model = is_peft_available() and isinstance(model, PeftModel)
440
+ self.model_adapter_name = model_adapter_name
441
+ self.ref_adapter_name = ref_adapter_name
442
+
443
+ if ref_model:
444
+ self.ref_model = ref_model
445
+ elif self.is_peft_model or args.precompute_ref_log_probs:
446
+ # The `model` with adapters turned off will be used as the reference model
447
+ self.ref_model = None
448
+ else:
449
+ self.ref_model = create_reference_model(model)
450
+
451
+ if processing_class is None:
452
+ raise ValueError(
453
+ "max_length or a processing_class must be specified when using the default DPODataCollatorWithPadding"
454
+ )
455
+ if args.max_length is None:
456
+ logger.warning(
457
+ "When using DPODataCollatorWithPadding, you should set `max_length` in the KTOTrainer's init"
458
+ " it will be set to `512` by default, but you should do it yourself in the future.",
459
+ )
460
+ max_length = 512
461
+ if args.max_length is not None:
462
+ max_length = args.max_length
463
+
464
+ if data_collator is None:
465
+ data_collator = DPODataCollatorWithPadding(
466
+ pad_token_id=processing_class.pad_token_id,
467
+ )
468
+
469
+ if args.remove_unused_columns:
470
+ args.remove_unused_columns = False
471
+ # warn users
472
+ logger.warning(
473
+ "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your KTOConfig"
474
+ " we have set it for you, but you should do it yourself in the future.",
475
+ )
476
+
477
+ self.use_dpo_data_collator = True
478
+ else:
479
+ self.use_dpo_data_collator = False
480
+
481
+ # Disable dropout in the model and reference model
482
+ if args.disable_dropout:
483
+ disable_dropout_in_model(model)
484
+ if self.ref_model is not None:
485
+ disable_dropout_in_model(self.ref_model)
486
+
487
+ self.loss_type = args.loss_type
488
+ self.max_length = max_length
489
+ self.generate_during_eval = args.generate_during_eval
490
+ self.processing_class = processing_class
491
+ self.precompute_ref_log_probs = args.precompute_ref_log_probs
492
+
493
+ # Not all losses require a KL calculation
494
+ self.calculate_KL = True
495
+ if self.loss_type in ["apo_zero_unpaired"]:
496
+ self.calculate_KL = False
497
+
498
+ # metric
499
+ self._stored_metrics = defaultdict(lambda: defaultdict(list))
500
+
501
+ # KTO parameter
502
+ self.beta = args.beta
503
+ self.desirable_weight = args.desirable_weight
504
+ self.undesirable_weight = args.undesirable_weight
505
+ self.aux_loss_enabled = getattr(model.config, "output_router_logits", False)
506
+ self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0)
507
+ if self.aux_loss_enabled and self.aux_loss_coef == 0.0:
508
+ logger.warning(
509
+ "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to "
510
+ "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value "
511
+ "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary "
512
+ "loss.",
513
+ )
514
+
515
+ # Compute that only on the main process for faster data processing.
516
+ # see: https://github.com/huggingface/trl/pull/1255
517
+ with PartialState().main_process_first():
518
+ # Extract the prompt if needed
519
+ train_dataset = train_dataset.map(
520
+ maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from train dataset"
521
+ )
522
+ # Unpair the dataset if needed
523
+ train_dataset = maybe_unpair_preference_dataset(
524
+ train_dataset, args.dataset_num_proc, desc="Unpairing train dataset"
525
+ )
526
+ # Apply the chat template if needed
527
+ train_dataset = train_dataset.map(
528
+ maybe_apply_chat_template,
529
+ fn_kwargs={"tokenizer": processing_class},
530
+ num_proc=args.dataset_num_proc,
531
+ desc="Applying chat template to train dataset",
532
+ )
533
+ if eval_dataset is not None:
534
+ eval_dataset = eval_dataset.map(
535
+ maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from eval dataset"
536
+ )
537
+ eval_dataset = maybe_unpair_preference_dataset(
538
+ eval_dataset, args.dataset_num_proc, desc="Unpairing eval dataset"
539
+ )
540
+ eval_dataset = eval_dataset.map(
541
+ maybe_apply_chat_template,
542
+ fn_kwargs={"tokenizer": processing_class},
543
+ num_proc=args.dataset_num_proc,
544
+ desc="Applying chat template to eval dataset",
545
+ )
546
+
547
+ # Tokenize and prepare the training datasets
548
+ train_dataset = train_dataset.map(
549
+ _tokenize,
550
+ batched=True,
551
+ fn_kwargs={"tokenizer": self.processing_class},
552
+ num_proc=args.dataset_num_proc,
553
+ desc="Tokenizing train dataset",
554
+ )
555
+
556
+ fn_kwargs = {
557
+ "prefix": "",
558
+ "tokenizer": self.processing_class,
559
+ "max_length": self.max_length,
560
+ }
561
+
562
+ train_dataset = train_dataset.map(
563
+ _process_tokens,
564
+ fn_kwargs=fn_kwargs,
565
+ num_proc=args.dataset_num_proc,
566
+ desc="Processing tokenized train dataset",
567
+ )
568
+
569
+ # Tokenize and prepare the eval datasets
570
+ if eval_dataset is not None:
571
+ eval_dataset = eval_dataset.map(
572
+ _tokenize,
573
+ fn_kwargs={"tokenizer": self.processing_class},
574
+ batched=True,
575
+ num_proc=args.dataset_num_proc,
576
+ desc="Tokenizing eval dataset",
577
+ )
578
+
579
+ eval_dataset = eval_dataset.map(
580
+ _process_tokens,
581
+ fn_kwargs=fn_kwargs,
582
+ num_proc=args.dataset_num_proc,
583
+ desc="Processing tokenized eval dataset",
584
+ )
585
+
586
+ # Get KL datasets if needed
587
+ if self.calculate_KL:
588
+ if args.per_device_train_batch_size <= 1:
589
+ raise ValueError(
590
+ "Actual (not effective) batch size must be > 1. KTO will not work properly because the KL term will be equivalent to the implied reward."
591
+ )
592
+
593
+ # create pairs for estimating the KL term by flipping the matched pairs in each batch of size total_batch_size
594
+ # i.e., (x_1, y_1), ..., (x_n, y_n) --> (x_1, y_n), ..., (x_n, y_1) = (x'_1, y'_1), ..., (x'_n, y'_n)
595
+ train_kl_dataset = train_dataset.map(
596
+ _get_kl_dataset,
597
+ batched=True,
598
+ batch_size=args.per_device_train_batch_size,
599
+ num_proc=args.dataset_num_proc,
600
+ desc="Extracting KL train dataset",
601
+ )
602
+
603
+ fn_kwargs["prefix"] = "KL_"
604
+ train_kl_dataset = train_kl_dataset.map(
605
+ _process_tokens,
606
+ fn_kwargs=fn_kwargs,
607
+ num_proc=args.dataset_num_proc,
608
+ remove_columns=[c for c in train_kl_dataset.column_names if c in train_dataset.column_names],
609
+ desc="Processing tokenized train KL dataset",
610
+ )
611
+
612
+ # merge the datasets
613
+ train_dataset = concatenate_datasets([train_dataset, train_kl_dataset], axis=1)
614
+
615
+ if eval_dataset is not None:
616
+ # Get KL dataset
617
+ eval_kl_dataset = eval_dataset.map(
618
+ _get_kl_dataset,
619
+ batched=True,
620
+ batch_size=args.per_device_train_batch_size,
621
+ num_proc=args.dataset_num_proc,
622
+ desc="Extracting eval KL dataset",
623
+ )
624
+
625
+ eval_kl_dataset = eval_kl_dataset.map(
626
+ _process_tokens,
627
+ fn_kwargs=fn_kwargs,
628
+ num_proc=args.dataset_num_proc,
629
+ remove_columns=[c for c in eval_kl_dataset.column_names if c in eval_dataset.column_names],
630
+ desc="Processing tokenized eval KL dataset",
631
+ )
632
+
633
+ # merge the datasets
634
+ eval_dataset = concatenate_datasets([eval_dataset, eval_kl_dataset], axis=1)
635
+
636
+ # calculate dataset desirability balance
637
+ num_desirable = max(sum(train_dataset["label"]), 1)
638
+ num_undesirable = max(len(train_dataset["label"]) - num_desirable, 1) # "label" is binary
639
+
640
+ if num_desirable != num_undesirable:
641
+ # The lower and upper bounds come from Eq. (8) of https://huggingface.co/papers/2402.01306
642
+ des_weight_lower_bound = round((num_undesirable * self.undesirable_weight / num_desirable) * 1, 2)
643
+ des_weight_upper_bound = round((num_undesirable * self.undesirable_weight / num_desirable) * 1.33, 2)
644
+ und_weight_lower_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1.33, 2)
645
+ und_weight_upper_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1, 2)
646
+
647
+ des_weight_in_range = des_weight_lower_bound <= self.desirable_weight <= des_weight_upper_bound
648
+ und_weight_in_range = und_weight_lower_bound <= self.undesirable_weight <= und_weight_upper_bound
649
+
650
+ if not (des_weight_in_range or und_weight_in_range):
651
+ logger.warning(
652
+ "You have different amounts of desirable/positive and undesirable/negative examples but the "
653
+ "weights on the desirable and undesirable losses don't seem to be in an ideal range. Based "
654
+ f"on your data, we recommend EITHER "
655
+ f"desirable_weight in [{des_weight_lower_bound}, {des_weight_upper_bound}] or "
656
+ f"undesirable_weight in [{und_weight_lower_bound}, {und_weight_upper_bound}] (but NOT BOTH). "
657
+ "See the documentation on how to optimally set these weights.",
658
+ )
659
+
660
+ # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
661
+ # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
662
+ # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
663
+ # default to the recommended non-reentrant behavior here, while preserving any user-provided value.
664
+ if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
665
+ args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
666
+ args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
667
+
668
+ super().__init__(
669
+ model=model,
670
+ args=args,
671
+ data_collator=data_collator,
672
+ train_dataset=train_dataset,
673
+ eval_dataset=eval_dataset,
674
+ processing_class=processing_class,
675
+ model_init=model_init,
676
+ compute_metrics=compute_metrics,
677
+ callbacks=callbacks,
678
+ optimizers=optimizers,
679
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
680
+ )
681
+
682
+ # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
683
+ # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
684
+ # self.model_accepts_loss_kwargs to False to enable scaling.
685
+ self.model_accepts_loss_kwargs = False
686
+
687
+ # Add tags for models that have been loaded with the correct transformers version
688
+ if hasattr(self.model, "add_model_tags"):
689
+ self.model.add_model_tags(self._tag_names)
690
+
691
+ if not hasattr(self, "accelerator"):
692
+ raise AttributeError(
693
+ "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`."
694
+ )
695
+
696
+ # Deepspeed Zero-3 does not support precompute_ref_log_probs
697
+ if self.is_deepspeed_enabled:
698
+ if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs:
699
+ raise ValueError(
700
+ "You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`."
701
+ )
702
+
703
+ if self.ref_model is None:
704
+ if not (self.is_peft_model or self.precompute_ref_log_probs):
705
+ raise ValueError(
706
+ "No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`"
707
+ )
708
+ else:
709
+ if self.is_deepspeed_enabled:
710
+ self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator)
711
+ else:
712
+ self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
713
+
714
+ # Import Liger kernel if enabled
715
+ if self.args.use_liger_kernel:
716
+ if not is_liger_kernel_available():
717
+ raise ImportError(
718
+ "You set `use_liger_kernel=True` but the liger kernel is not available. "
719
+ "Please install liger-kernel first: `pip install liger-kernel`"
720
+ )
721
+ if self.loss_type in ["apo_zero_unpaired"]:
722
+ raise ValueError(
723
+ "You cannot set `loss_type='apo_zero_unpaired'` with liger-kernel."
724
+ "Only KTO loss is supported with liger-kernel."
725
+ )
726
+ if self.precompute_ref_log_probs:
727
+ raise ValueError(
728
+ "You cannot use `precompute_ref_log_probs=True` with liger kernel. Please set "
729
+ "`precompute_ref_log_probs=False`."
730
+ )
731
+ if self.is_peft_model or self.ref_adapter_name is not None:
732
+ raise ValueError(
733
+ "You cannot use `use_liger_kernel=True` with Peft models. Please set `use_liger_kernel=False`."
734
+ )
735
+ self.kto_loss_fn = LigerFusedLinearKTOLoss(beta=self.beta, use_ref_model=(self.ref_model is not None))
736
+
737
+ if self.precompute_ref_log_probs:
738
+ self.train_dataset = self._precompute_reference_log_probs(
739
+ self.train_dataset, "train", self.args.per_device_train_batch_size
740
+ )
741
+ if self.eval_dataset is not None:
742
+ if isinstance(self.eval_dataset, dict):
743
+ self.eval_dataset = {
744
+ name: self._precompute_reference_log_probs(dataset, name, self.args.per_device_eval_batch_size)
745
+ for name, dataset in self.eval_dataset.items()
746
+ }
747
+ else:
748
+ self.eval_dataset = self._precompute_reference_log_probs(
749
+ self.eval_dataset, "eval", self.args.per_device_eval_batch_size
750
+ )
751
+
752
+ @contextmanager
753
+ def null_ref_context(self):
754
+ """Context manager for handling null reference model (that is, peft adapter manipulation)."""
755
+ with (
756
+ self.accelerator.unwrap_model(self.model).disable_adapter()
757
+ if self.is_peft_model and not self.ref_adapter_name
758
+ else nullcontext()
759
+ ):
760
+ if self.ref_adapter_name:
761
+ self.model.set_adapter(self.ref_adapter_name)
762
+ yield
763
+ if self.ref_adapter_name:
764
+ self.model.set_adapter(self.model_adapter_name or "default")
765
+
766
+ def _precompute_reference_log_probs(self, dataset: Dataset, name: str, batch_size: int) -> Dataset:
767
+ dataloader_params = {
768
+ "batch_size": batch_size,
769
+ "collate_fn": self.data_collator,
770
+ "num_workers": self.args.dataloader_num_workers,
771
+ "pin_memory": self.args.dataloader_pin_memory,
772
+ "shuffle": False,
773
+ }
774
+ data_loader = self.accelerator.prepare(DataLoader(dataset, **dataloader_params))
775
+ reference_completion_logps = []
776
+ reference_KL_logps = []
777
+ for padded_batch in tqdm(iterable=data_loader, desc=f"Computing reference log probs for {name} dataset"):
778
+ reference_completion_logp, reference_KL_logp = self.compute_reference_log_probs(padded_batch)
779
+ reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp)
780
+ reference_completion_logps.append(reference_completion_logp.cpu())
781
+ if self.calculate_KL:
782
+ reference_KL_logp = self.accelerator.gather_for_metrics(reference_KL_logp)
783
+ reference_KL_logps.append(reference_KL_logp.cpu())
784
+ dataset = dataset.add_column(
785
+ name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy()
786
+ )
787
+ if self.calculate_KL:
788
+ dataset = dataset.add_column(
789
+ name="reference_KL_logps", column=torch.cat(reference_KL_logps).float().numpy()
790
+ )
791
+ return dataset
792
+
793
+ def compute_reference_log_probs(self, padded_batch: dict) -> dict:
794
+ """Computes log probabilities of the reference model for a single padded batch of a KTO specific dataset."""
795
+ with torch.no_grad():
796
+ if self.ref_model is None:
797
+ with self.null_ref_context():
798
+ completion_logits = self.model(
799
+ padded_batch["completion_input_ids"],
800
+ attention_mask=padded_batch["completion_attention_mask"],
801
+ ).logits
802
+
803
+ if self.calculate_KL:
804
+ KL_logits = self.model(
805
+ padded_batch["KL_completion_input_ids"],
806
+ attention_mask=padded_batch["KL_completion_attention_mask"],
807
+ ).logits
808
+ else:
809
+ completion_logits = self.ref_model(
810
+ padded_batch["completion_input_ids"], attention_mask=padded_batch["completion_attention_mask"]
811
+ ).logits
812
+
813
+ if self.calculate_KL:
814
+ KL_logits = self.ref_model(
815
+ padded_batch["KL_completion_input_ids"],
816
+ attention_mask=padded_batch["KL_completion_attention_mask"],
817
+ ).logits
818
+
819
+ completion_logps = self.get_batch_logps(
820
+ completion_logits,
821
+ padded_batch["completion_labels"],
822
+ average_log_prob=False,
823
+ )
824
+
825
+ if self.calculate_KL:
826
+ KL_logps = self.get_batch_logps(
827
+ KL_logits,
828
+ padded_batch["KL_completion_labels"],
829
+ average_log_prob=False,
830
+ )
831
+ else:
832
+ KL_logps = None
833
+
834
+ return completion_logps, KL_logps
835
+
836
+ @staticmethod
837
+ def get_batch_logps(
838
+ logits: torch.FloatTensor,
839
+ labels: torch.LongTensor,
840
+ average_log_prob: bool = False,
841
+ ) -> torch.FloatTensor:
842
+ """Compute the log probabilities of the given labels under the given logits.
843
+
844
+ Args:
845
+ logits:
846
+ Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size)
847
+ labels:
848
+ Labels for which to compute the log probabilities. Label tokens with a value of `-100` are ignored.
849
+ Shape: (batch_size, sequence_length)
850
+ average_log_prob:
851
+ If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the
852
+ log probabilities of the (non-masked) tokens.
853
+
854
+ Returns:
855
+ A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the
856
+ given logits.
857
+ """
858
+ if logits.shape[:-1] != labels.shape:
859
+ raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.")
860
+
861
+ # For causal LM, shift labels and logits by one position
862
+ labels = labels[:, 1:].clone()
863
+ logits = logits[:, :-1, :]
864
+
865
+ loss_mask = labels != -100
866
+
867
+ # dummy token; we'll ignore the losses on these tokens later
868
+ labels[labels == -100] = 0
869
+
870
+ per_token_logps = selective_log_softmax(logits, labels)
871
+
872
+ if average_log_prob:
873
+ return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1)
874
+ else:
875
+ return (per_token_logps * loss_mask).sum(-1)
876
+
877
+ def forward(
878
+ self, model: nn.Module, batch: dict[str, list | torch.LongTensor]
879
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
880
+ KL_logps = self._compute_kl_logps(model, batch)
881
+
882
+ model_kwargs = {}
883
+ if self.aux_loss_enabled:
884
+ model_kwargs["output_router_logits"] = True
885
+
886
+ outputs = model(
887
+ batch["completion_input_ids"],
888
+ attention_mask=batch["completion_attention_mask"],
889
+ **model_kwargs,
890
+ )
891
+ completion_logits = outputs.logits
892
+
893
+ completion_logps = self.get_batch_logps(
894
+ completion_logits,
895
+ batch["completion_labels"],
896
+ average_log_prob=False,
897
+ )
898
+
899
+ if completion_logps.shape[0] != len(batch["label"]):
900
+ raise ValueError(
901
+ "There is a mismatch between the number of examples in this batch and the number of "
902
+ "examples for which an output sequence was predicted."
903
+ )
904
+
905
+ # Use torch.nonzero for efficient tensor index selection
906
+ device = completion_logits.device
907
+ labels = torch.as_tensor(batch["label"], dtype=torch.bool, device=device)
908
+ chosen_idx = torch.nonzero(labels, as_tuple=False).view(-1)
909
+ rejected_idx = torch.nonzero(~labels, as_tuple=False).view(-1)
910
+
911
+ # Use index_select for efficient CUDA operations
912
+ chosen_logps = completion_logps.index_select(0, chosen_idx)
913
+ rejected_logps = completion_logps.index_select(0, rejected_idx)
914
+
915
+ chosen_logits = completion_logits.index_select(0, chosen_idx)
916
+ rejected_logits = completion_logits.index_select(0, rejected_idx)
917
+
918
+ if self.aux_loss_enabled:
919
+ return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, KL_logps, outputs.aux_loss)
920
+ else:
921
+ return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, KL_logps)
922
+
923
+ def kto_loss(
924
+ self,
925
+ policy_chosen_logps: torch.FloatTensor,
926
+ policy_rejected_logps: torch.FloatTensor,
927
+ policy_KL_logps: torch.FloatTensor,
928
+ reference_chosen_logps: torch.FloatTensor,
929
+ reference_rejected_logps: torch.FloatTensor,
930
+ reference_KL_logps: torch.FloatTensor,
931
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
932
+ """Compute the KTO loss for a batch of policy and reference model log probabilities.
933
+
934
+ Args:
935
+ policy_chosen_logps:
936
+ Log probabilities of the policy model for the chosen responses. Shape: (num(chosen) in batch_size,)
937
+ policy_rejected_logps:
938
+ Log probabilities of the policy model for the rejected responses. Shape: (num(rejected) in batch_size,)
939
+ policy_KL_logps: Log probabilities of the policy model for the KL responses. Shape: (batch_size,)
940
+ reference_chosen_logps:
941
+ Log probabilities of the reference model for the chosen responses. Shape: (num(chosen) in batch_size,)
942
+ reference_rejected_logps:
943
+ Log probabilities of the reference model for the rejected responses. Shape: (num(rejected) in
944
+ batch_size,)
945
+ reference_KL_logps: Log probabilities of the reference model for the KL responses. Shape: (batch_size,)
946
+
947
+ Returns:
948
+ A tuple of four tensors: (losses, chosen_rewards, rejected_rewards, KL). The losses tensor contains the KTO
949
+ loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for
950
+ the chosen and rejected responses, respectively. The KL tensor contains the detached KL divergence estimate
951
+ between the policy and reference models.
952
+ """
953
+ if self.calculate_KL:
954
+ kl = (policy_KL_logps - reference_KL_logps).mean().detach()
955
+ kl = self.accelerator.gather_for_metrics(kl).mean().clamp(min=0)
956
+ else:
957
+ kl = torch.zeros(1).to(policy_chosen_logps.device)
958
+
959
+ # Chosen losses
960
+ if policy_chosen_logps.shape[0] != 0 or reference_chosen_logps.shape[0] != 0:
961
+ chosen_logratios = policy_chosen_logps - reference_chosen_logps
962
+
963
+ if self.loss_type == "kto":
964
+ # Eqn (7) of the KTO paper (https://huggingface.co/papers/2402.01306)
965
+ chosen_losses = 1 - F.sigmoid(self.beta * (chosen_logratios - kl))
966
+ elif self.loss_type == "apo_zero_unpaired":
967
+ # Unpaired variant of Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266)
968
+ # Use this loss when you believe the chosen outputs are better than your model's default output
969
+ chosen_losses = 1 - F.sigmoid(self.beta * chosen_logratios)
970
+
971
+ chosen_rewards = self.beta * chosen_logratios.detach()
972
+
973
+ else:
974
+ # lists can't be empty -- if they are, then accelerate.gather will hang
975
+ chosen_losses = torch.Tensor([]).to(self.accelerator.device)
976
+ chosen_rewards = torch.Tensor([]).to(self.accelerator.device)
977
+
978
+ # Rejected losses
979
+ if policy_rejected_logps.shape[0] != 0 or reference_rejected_logps.shape[0] != 0:
980
+ rejected_logratios = policy_rejected_logps - reference_rejected_logps
981
+
982
+ if self.loss_type == "kto":
983
+ rejected_losses = 1 - F.sigmoid(self.beta * (kl - rejected_logratios))
984
+ elif self.loss_type == "apo_zero_unpaired":
985
+ rejected_losses = F.sigmoid(self.beta * rejected_logratios)
986
+
987
+ rejected_rewards = self.beta * rejected_logratios.detach()
988
+ else:
989
+ # lists can't be empty -- if they are, then accelerate.gather will hang
990
+ rejected_losses = torch.Tensor([]).to(self.accelerator.device)
991
+ rejected_rewards = torch.Tensor([]).to(self.accelerator.device)
992
+
993
+ losses = torch.cat(
994
+ (self.desirable_weight * chosen_losses, self.undesirable_weight * rejected_losses),
995
+ 0,
996
+ )
997
+
998
+ return losses, chosen_rewards, rejected_rewards, kl
999
+
1000
+ def _compute_kl_logps(self, model, batch):
1001
+ """Compute KL log probabilities for a given batch."""
1002
+ KL_logps = None
1003
+ if self.calculate_KL:
1004
+ KL_model_kwargs = {
1005
+ "input_ids": batch["KL_completion_input_ids"],
1006
+ "attention_mask": batch["KL_completion_attention_mask"],
1007
+ }
1008
+
1009
+ with torch.no_grad():
1010
+ KL_logits = model(**KL_model_kwargs).logits
1011
+
1012
+ KL_logps = self.get_batch_logps(
1013
+ KL_logits,
1014
+ batch["KL_completion_labels"],
1015
+ average_log_prob=False,
1016
+ )
1017
+ return KL_logps
1018
+
1019
+ def _compute_loss_liger(self, model, batch):
1020
+ """
1021
+ Compute the KTO loss using the Liger-Kernel's LigerFusedLinearKTOLoss.
1022
+
1023
+ Args:
1024
+ model:
1025
+ The policy model used for generating log probabilities and outputs. It could be an encoder-decoder
1026
+ model or a regular language model.
1027
+ batch: A dictionary containing the input data and labels for the batch.
1028
+
1029
+ Returns:
1030
+ A dictionary containing the following keys:
1031
+ - "loss": The computed KTO loss for the batch.
1032
+ - "chosen_logits_sum": Sum of the logits for the chosen responses from the policy model.
1033
+ - "rejected_logits_sum": Sum of the logits for the rejected responses from the policy model.
1034
+ - "chosen_logps": Log probabilities of the chosen responses from the policy model.
1035
+ - "rejected_logps": Log probabilities of the rejected responses from the policy model.
1036
+ - "chosen_rewards": Rewards for the chosen responses.
1037
+ - "rejected_rewards": Rewards for the rejected responses.
1038
+ - "kl": The KL divergence between the policy and reference models (detached).
1039
+
1040
+ If auxiliary loss is enabled, the dictionary will also include:
1041
+ - "aux_loss": The auxiliary loss from the model outputs.
1042
+ """
1043
+ policy_KL_logps = self._compute_kl_logps(model, batch)
1044
+ reference_KL_logps = self._compute_kl_logps(self.ref_model, batch)
1045
+ if self.calculate_KL:
1046
+ kl = (policy_KL_logps - reference_KL_logps).mean().detach()
1047
+ kl = self.accelerator.gather_for_metrics(kl).mean().clamp(min=0)
1048
+ else:
1049
+ kl = torch.zeros(1).to(self.accelerator.device)
1050
+
1051
+ model_kwargs = {}
1052
+ if self.aux_loss_enabled:
1053
+ model_kwargs["output_router_logits"] = True
1054
+
1055
+ # skip the lm head and get the last hidden state
1056
+ base_model = model.get_decoder()
1057
+ outputs = base_model(
1058
+ batch["completion_input_ids"],
1059
+ attention_mask=batch["completion_attention_mask"],
1060
+ use_cache=False,
1061
+ **model_kwargs,
1062
+ )
1063
+
1064
+ # reference model
1065
+ ref_base_model = self.ref_model.get_decoder()
1066
+ ref_outputs = ref_base_model(
1067
+ batch["completion_input_ids"],
1068
+ attention_mask=batch["completion_attention_mask"],
1069
+ use_cache=False,
1070
+ **model_kwargs,
1071
+ )
1072
+ lm_head = model.get_output_embeddings()
1073
+ ref_lm_head = self.ref_model.get_output_embeddings()
1074
+
1075
+ (
1076
+ loss,
1077
+ (
1078
+ chosen_logps_sum,
1079
+ rejected_logps_sum,
1080
+ chosen_logits_sum,
1081
+ rejected_logits_sum,
1082
+ chosen_rewards_sum,
1083
+ rejected_rewards_sum,
1084
+ ),
1085
+ ) = self.kto_loss_fn(
1086
+ _input=outputs.last_hidden_state[:, :-1],
1087
+ lin_weight=lm_head.weight,
1088
+ target=batch["completion_labels"][:, 1:],
1089
+ bias=lm_head.bias if hasattr(lm_head, "bias") else None,
1090
+ preference_labels=torch.tensor(batch["label"], dtype=torch.bool).to(self.accelerator.device),
1091
+ ref_input=ref_outputs.last_hidden_state[:, :-1],
1092
+ ref_weight=ref_lm_head.weight,
1093
+ ref_bias=ref_lm_head.bias if hasattr(lm_head, "bias") else None,
1094
+ kl=kl,
1095
+ )
1096
+
1097
+ output = {
1098
+ "loss": loss,
1099
+ "chosen_logits_sum": chosen_logits_sum,
1100
+ "rejected_logits_sum": rejected_logits_sum,
1101
+ "chosen_logps_sum": chosen_logps_sum,
1102
+ "rejected_logps_sum": rejected_logps_sum,
1103
+ "chosen_rewards_sum": chosen_rewards_sum,
1104
+ "rejected_rewards_sum": rejected_rewards_sum,
1105
+ "kl": kl,
1106
+ }
1107
+ if self.aux_loss_enabled:
1108
+ output["aux_loss"] = outputs.aux_loss
1109
+
1110
+ return output
1111
+
1112
+ def get_batch_loss_metrics(
1113
+ self,
1114
+ model,
1115
+ batch: dict[str, list | torch.LongTensor],
1116
+ ):
1117
+ """Compute the KTO loss and other metrics for the given batch of inputs for train or test."""
1118
+ metrics = {}
1119
+ batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in batch.items()}
1120
+
1121
+ labels = torch.tensor(batch["label"])
1122
+ num_chosen = labels.sum().to(self.accelerator.device)
1123
+ num_rejected = (len(labels) - num_chosen).to(self.accelerator.device)
1124
+
1125
+ if self.args.use_liger_kernel:
1126
+ model_output = self._compute_loss_liger(model, batch)
1127
+ losses = model_output["loss"]
1128
+ policy_chosen_logits = model_output["chosen_logits_sum"]
1129
+ policy_rejected_logits = model_output["rejected_logits_sum"]
1130
+ policy_chosen_logps = model_output["chosen_logps_sum"]
1131
+ policy_rejected_logps = model_output["rejected_logps_sum"]
1132
+ chosen_rewards = model_output["chosen_rewards_sum"]
1133
+ rejected_rewards = model_output["rejected_rewards_sum"]
1134
+ kl = model_output["kl"]
1135
+ if self.aux_loss_enabled:
1136
+ aux_loss = model_output["aux_loss"]
1137
+ else:
1138
+ forward_output = self.forward(model, batch)
1139
+ (
1140
+ policy_chosen_logps,
1141
+ policy_rejected_logps,
1142
+ policy_chosen_logits,
1143
+ policy_rejected_logits,
1144
+ policy_KL_logps,
1145
+ ) = forward_output[:5]
1146
+ if self.aux_loss_enabled:
1147
+ aux_loss = forward_output[5]
1148
+
1149
+ # if reference_logps in batch use them, otherwise use the reference model
1150
+ if "reference_logps" in batch:
1151
+ # Convert Python lists to tensor indices for efficient CUDA operations
1152
+ device = batch["reference_logps"].device
1153
+ labels = torch.as_tensor(batch["label"], dtype=torch.bool, device=device)
1154
+ chosen_idx = torch.nonzero(labels, as_tuple=False).view(-1)
1155
+ rejected_idx = torch.nonzero(~labels, as_tuple=False).view(-1)
1156
+
1157
+ # Use index_select for efficient CUDA operations
1158
+ reference_chosen_logps = batch["reference_logps"].index_select(0, chosen_idx)
1159
+ reference_rejected_logps = batch["reference_logps"].index_select(0, rejected_idx)
1160
+ if self.calculate_KL:
1161
+ reference_KL_logps = batch["reference_KL_logps"]
1162
+ else:
1163
+ reference_KL_logps = None
1164
+ else:
1165
+ with torch.no_grad():
1166
+ if self.ref_model is None:
1167
+ with self.null_ref_context():
1168
+ (
1169
+ reference_chosen_logps,
1170
+ reference_rejected_logps,
1171
+ _,
1172
+ _,
1173
+ reference_KL_logps,
1174
+ ) = self.forward(self.model, batch)[:5]
1175
+ else:
1176
+ (
1177
+ reference_chosen_logps,
1178
+ reference_rejected_logps,
1179
+ _,
1180
+ _,
1181
+ reference_KL_logps,
1182
+ ) = self.forward(self.ref_model, batch)[:5]
1183
+
1184
+ losses, chosen_rewards, rejected_rewards, kl = self.kto_loss(
1185
+ policy_chosen_logps,
1186
+ policy_rejected_logps,
1187
+ policy_KL_logps,
1188
+ reference_chosen_logps,
1189
+ reference_rejected_logps,
1190
+ reference_KL_logps,
1191
+ )
1192
+
1193
+ metrics["kl"] = kl.item()
1194
+
1195
+ all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item()
1196
+ all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item()
1197
+
1198
+ if all_num_chosen > 0:
1199
+ metrics["rewards/chosen_sum"] = (
1200
+ self.accelerator.gather_for_metrics(chosen_rewards.nansum()).nansum().item()
1201
+ )
1202
+ metrics["logps/chosen_sum"] = (
1203
+ self.accelerator.gather_for_metrics(policy_chosen_logps.nansum()).nansum().item()
1204
+ )
1205
+ metrics["logits/chosen_sum"] = (
1206
+ self.accelerator.gather_for_metrics(policy_chosen_logits.nansum()).nansum().item()
1207
+ )
1208
+ metrics["count/chosen"] = all_num_chosen
1209
+
1210
+ if all_num_rejected > 0:
1211
+ metrics["rewards/rejected_sum"] = (
1212
+ self.accelerator.gather_for_metrics(rejected_rewards.nansum()).nansum().item()
1213
+ )
1214
+ metrics["logps/rejected_sum"] = (
1215
+ self.accelerator.gather_for_metrics(policy_rejected_logps.nansum()).nansum().item()
1216
+ )
1217
+ metrics["logits/rejected_sum"] = (
1218
+ self.accelerator.gather_for_metrics(policy_rejected_logits.nansum()).nansum().item()
1219
+ )
1220
+ metrics["count/rejected"] = all_num_rejected
1221
+
1222
+ loss = losses.nanmean()
1223
+ if self.aux_loss_enabled:
1224
+ loss += self.aux_loss_coef * aux_loss
1225
+
1226
+ return loss, metrics
1227
+
1228
+ def compute_loss(
1229
+ self,
1230
+ model: PreTrainedModel | nn.Module,
1231
+ inputs: dict[str, torch.Tensor | Any],
1232
+ return_outputs=False,
1233
+ num_items_in_batch=None,
1234
+ ) -> torch.Tensor | tuple[torch.Tensor, dict[str, torch.Tensor]]:
1235
+ compute_loss_context_manager = (
1236
+ autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
1237
+ )
1238
+
1239
+ with compute_loss_context_manager:
1240
+ loss, metrics = self.get_batch_loss_metrics(model, inputs)
1241
+
1242
+ # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class:
1243
+ loss = loss.to(self.args.device)
1244
+ # force log the metrics
1245
+ if self.accelerator.is_main_process:
1246
+ self.store_metrics(metrics, train_eval="train")
1247
+
1248
+ if return_outputs:
1249
+ return (loss, metrics)
1250
+ return loss
1251
+
1252
+ def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None:
1253
+ for key, value in metrics.items():
1254
+ self._stored_metrics[train_eval][key].append(value)
1255
+
1256
+ def _get_train_sampler(self, dataset: Dataset | None = None) -> torch.utils.data.Sampler | None:
1257
+ if dataset is None:
1258
+ dataset = self.train_dataset
1259
+ if dataset is None or not has_length(dataset):
1260
+ return None
1261
+ return SequentialSampler(dataset)
1262
+
1263
+ def generate_from_model_and_ref(self, model, batch: dict[str, torch.LongTensor]) -> tuple[str, str]:
1264
+ """Generate samples from the model and reference model for the given batch of inputs."""
1265
+
1266
+ # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with
1267
+ # the torch amp context manager as some hidden states are silently casted to full precision.
1268
+ generate_context_manager = (
1269
+ autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
1270
+ )
1271
+
1272
+ with generate_context_manager:
1273
+ policy_output = model.generate(
1274
+ input_ids=batch["prompt_input_ids"],
1275
+ attention_mask=batch["prompt_attention_mask"],
1276
+ max_length=self.max_length,
1277
+ do_sample=True,
1278
+ pad_token_id=self.processing_class.pad_token_id,
1279
+ )
1280
+
1281
+ # if reference_output in batch use that otherwise use the reference model
1282
+ if "reference_output" in batch:
1283
+ reference_output = batch["reference_output"]
1284
+ else:
1285
+ if self.ref_model is None:
1286
+ with self.null_ref_context():
1287
+ reference_output = self.model.generate(
1288
+ input_ids=batch["prompt_input_ids"],
1289
+ attention_mask=batch["prompt_attention_mask"],
1290
+ max_length=self.max_length,
1291
+ do_sample=True,
1292
+ pad_token_id=self.processing_class.pad_token_id,
1293
+ )
1294
+ else:
1295
+ reference_output = self.ref_model.generate(
1296
+ input_ids=batch["prompt_input_ids"],
1297
+ attention_mask=batch["prompt_attention_mask"],
1298
+ max_length=self.max_length,
1299
+ do_sample=True,
1300
+ pad_token_id=self.processing_class.pad_token_id,
1301
+ )
1302
+
1303
+ policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id)
1304
+ policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True)
1305
+
1306
+ reference_output = pad_to_length(reference_output, self.max_length, self.processing_class.pad_token_id)
1307
+ reference_output_decoded = self.processing_class.batch_decode(reference_output, skip_special_tokens=True)
1308
+
1309
+ return policy_output_decoded, reference_output_decoded
1310
+
1311
+ def prediction_step(
1312
+ self,
1313
+ model: PreTrainedModel | nn.Module,
1314
+ inputs: dict[str, torch.Tensor | Any],
1315
+ prediction_loss_only: bool,
1316
+ ignore_keys: list[str] | None = None,
1317
+ ):
1318
+ if ignore_keys is None:
1319
+ if hasattr(model, "config"):
1320
+ ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", [])
1321
+ else:
1322
+ ignore_keys = []
1323
+
1324
+ prediction_context_manager = (
1325
+ autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
1326
+ )
1327
+ with torch.no_grad(), prediction_context_manager:
1328
+ loss, metrics = self.get_batch_loss_metrics(model, inputs)
1329
+
1330
+ # force log the metrics
1331
+ if self.accelerator.is_main_process:
1332
+ self.store_metrics(metrics, train_eval="eval")
1333
+
1334
+ if prediction_loss_only:
1335
+ return (loss.detach(), None, None)
1336
+
1337
+ # logits for the chosen and rejected samples from model
1338
+ logits_dict = {}
1339
+ if "logits/chosen_sum" in metrics:
1340
+ logits_dict["eval_logits/chosen"] = metrics["logits/chosen_sum"]
1341
+ if "logits/rejected_sum" in metrics:
1342
+ logits_dict["eval_logits/rejected"] = metrics["logits/rejected_sum"]
1343
+ logits = [v for k, v in logits_dict.items() if k not in ignore_keys]
1344
+ logits = torch.tensor(logits, device=self.accelerator.device)
1345
+ labels = torch.zeros(logits.shape[0], device=self.accelerator.device)
1346
+
1347
+ return (loss.detach(), logits, labels)
1348
+
1349
+ def evaluation_loop(
1350
+ self,
1351
+ dataloader: DataLoader,
1352
+ description: str,
1353
+ prediction_loss_only: bool | None = None,
1354
+ ignore_keys: list[str] | None = None,
1355
+ metric_key_prefix: str = "eval",
1356
+ ) -> EvalLoopOutput:
1357
+ """
1358
+ Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by
1359
+ `Trainer.evaluate()` and `Trainer.predict()`.
1360
+
1361
+ Works both with or without labels.
1362
+ """
1363
+
1364
+ # Sample and save to game log if requested (for one batch to save time)
1365
+ if self.generate_during_eval:
1366
+ # Generate random indices within the range of the total number of samples
1367
+ num_samples = len(dataloader.dataset)
1368
+ random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size)
1369
+
1370
+ # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader
1371
+ random_batch_dataset = dataloader.dataset.select(random_indices)
1372
+ random_batch = self.data_collator(random_batch_dataset)
1373
+ random_batch = self._prepare_inputs(random_batch)
1374
+
1375
+ target_labels = torch.tensor(random_batch["label"], dtype=torch.bool, device=self.accelerator.device)
1376
+ target_indices = torch.where(~target_labels)[0]
1377
+ target_batch = {
1378
+ "prompt_input_ids": random_batch["prompt_input_ids"][target_indices],
1379
+ "prompt_attention_mask": random_batch["prompt_attention_mask"][target_indices],
1380
+ "prompt": itemgetter(*target_indices)(random_batch["prompt"]),
1381
+ }
1382
+ policy_output_decoded, ref_output_decoded = self.generate_from_model_and_ref(self.model, target_batch)
1383
+
1384
+ table = pd.DataFrame(
1385
+ columns=["Prompt", "Policy", "Ref Model"],
1386
+ data=[
1387
+ [prompt, pol[len(prompt) :], ref[len(prompt) :]]
1388
+ for prompt, pol, ref in zip(
1389
+ target_batch["prompt"], policy_output_decoded, ref_output_decoded, strict=True
1390
+ )
1391
+ ],
1392
+ )
1393
+ if "wandb" in self.args.report_to:
1394
+ wandb.log({"game_log": wandb.Table(data=table)})
1395
+
1396
+ if "comet_ml" in self.args.report_to:
1397
+ log_table_to_comet_experiment(
1398
+ name="game_log.csv",
1399
+ table=table,
1400
+ )
1401
+
1402
+ # Base evaluation
1403
+ initial_output = super().evaluation_loop(
1404
+ dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix
1405
+ )
1406
+
1407
+ return initial_output
1408
+
1409
+ def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
1410
+ """
1411
+ Log `logs` on the various objects watching training, including stored metrics.
1412
+
1413
+ Args:
1414
+ logs (`dict[str, float]`):
1415
+ The values to log.
1416
+ start_time (`float`, *optional*):
1417
+ Start time of the training.
1418
+ """
1419
+ # logs either has 'loss' or 'eval_loss'
1420
+ train_eval = "train" if "loss" in logs else "eval"
1421
+ # train metrics should have no prefix, eval should have 'eval_'
1422
+ prefix = "eval_" if train_eval == "eval" else ""
1423
+ # accumulate average metrics from sums and lengths
1424
+ for split in ["chosen", "rejected"]:
1425
+ if f"count/{split}" in self._stored_metrics[train_eval]:
1426
+ count_sum = torch.Tensor(self._stored_metrics[train_eval][f"count/{split}"]).sum().item()
1427
+ for metric in ["rewards", "logps", "logits"]:
1428
+ logs[f"{prefix}{metric}/{split}"] = (
1429
+ torch.Tensor(self._stored_metrics[train_eval][f"{metric}/{split}_sum"]).sum().item()
1430
+ / count_sum
1431
+ )
1432
+ # delete obsolete metric
1433
+ del self._stored_metrics[train_eval][f"{metric}/{split}_sum"]
1434
+ del self._stored_metrics[train_eval][f"count/{split}"]
1435
+ # calculate reward margin
1436
+ if f"{prefix}rewards/chosen" in logs and f"{prefix}rewards/rejected" in logs:
1437
+ logs[f"{prefix}rewards/margins"] = logs[f"{prefix}rewards/chosen"] - logs[f"{prefix}rewards/rejected"]
1438
+ # Add averaged stored metrics to logs
1439
+ for key, metrics in self._stored_metrics[train_eval].items():
1440
+ logs[f"{prefix}{key}"] = torch.Tensor(metrics).mean().item()
1441
+ del self._stored_metrics[train_eval]
1442
+ return super().log(logs, start_time)
1443
+
1444
+ # Ensure the model card is saved along with the checkpoint
1445
+ def _save_checkpoint(self, model, trial):
1446
+ if self.args.hub_model_id is None:
1447
+ model_name = Path(self.args.output_dir).name
1448
+ else:
1449
+ model_name = self.args.hub_model_id.split("/")[-1]
1450
+ self.create_model_card(model_name=model_name)
1451
+ super()._save_checkpoint(model, trial)
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/merge_model_callback.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 logging
16
+ import os
17
+
18
+ import torch
19
+ from huggingface_hub import HfApi
20
+ from transformers import TrainerCallback
21
+
22
+ from ..import_utils import is_mergekit_available
23
+ from ..trainer.utils import get_config_model_id
24
+
25
+
26
+ if is_mergekit_available():
27
+ from mergekit.config import MergeConfiguration
28
+ from mergekit.merge import MergeOptions, run_merge
29
+
30
+
31
+ # Logger for module-level logging
32
+ logger = logging.getLogger(__name__)
33
+
34
+
35
+ def upload_model_to_hf(folder_path: str, repo_id: str):
36
+ api = HfApi()
37
+ # Create the repository if it doesn't exist
38
+ repo = api.create_repo(repo_id, repo_type="model")
39
+
40
+ # Upload the folder to the specified repository
41
+ api.upload_folder(
42
+ folder_path=folder_path,
43
+ repo_id=repo.repo_id,
44
+ repo_type=repo.repo_type,
45
+ )
46
+
47
+
48
+ class MergeConfig:
49
+ r"""
50
+ Configuration class for merging two models using `mergekit`.
51
+
52
+ This class provides a structured way to configure and generate merge configurations for various merge methods, such
53
+ as `linear`, `ties`, `dare_ties`, and `slerp`.
54
+
55
+ Args:
56
+ method (`str`, *optional*, defaults to `"linear"`):
57
+ Merge method to use. Supported methods include:
58
+
59
+ - `"linear"`: Linearly combines two models with specified weights.
60
+ - `"ties"`: Combines two models using the TIES method with density parameters.
61
+ - `"dare_ties"`: A variant of TIES for domain adaptation.
62
+ - `"slerp"`: Combines models using spherical linear interpolation.
63
+
64
+ Note:
65
+
66
+ For more details about the merge methods and how they are implemented, see the [MergeKit GitHub
67
+ repository](https://github.com/arcee-ai/mergekit?tab=readme-ov-file#merge-methods).
68
+
69
+ Attributes:
70
+ method (`str`): The merge method to use.
71
+ policy_model_path (`str` or `None`): Path to the policy model.
72
+ target_model_path (`str` or `None`): Path to the target model.
73
+ policy_model_weight (`float`): Weight for the policy model (for `linear` and `ties` methods).
74
+ target_model_weight (`float`): Weight for the target model (for `linear` and `ties` methods).
75
+ policy_model_density (`list[float]`): Density parameters for the policy model (for `ties` and `dare_ties`).
76
+ target_model_density (`list[float]`): Density parameters for the target model (for `ties` and `dare_ties`).
77
+ normalize (`float` or `None`): Normalization factor for the TIES method.
78
+ t_values (`float` or `None`): Interpolation factor for the SLERP method.
79
+ dtype (`str`): Data type to use for merging, e.g., `"float16"`.
80
+ """
81
+
82
+ def __init__(self, method: str = "linear"):
83
+ if not is_mergekit_available():
84
+ raise ImportError("MergeConfig requires the `mergekit` extra. To install, run `pip install mergekit`.")
85
+ self.method = method
86
+ self.policy_model_path = None
87
+ self.target_model_path = None
88
+
89
+ # Initialize relevant parameters based on the method
90
+ if method == "linear":
91
+ self.policy_model_weight = 0.5
92
+ self.target_model_weight = 0.5
93
+ self.dtype = "float16"
94
+ elif method == "ties":
95
+ self.policy_model_weight = 1.0
96
+ self.policy_model_density = [1.0, 0.7, 0.1]
97
+ self.target_model_weight = 1.0
98
+ self.target_model_density = [1.0]
99
+ self.normalize = 1.0
100
+ self.dtype = "float16"
101
+ elif method == "dare_ties":
102
+ self.policy_model_weight = 1.0
103
+ self.policy_model_density = [1.0, 0.7, 0.1]
104
+ self.target_model_weight = 1.0
105
+ self.target_model_density = [1.0]
106
+ self.normalize = 1.0
107
+ self.dtype = "float16"
108
+ elif method == "slerp":
109
+ self.t_values = 0.5
110
+ self.dtype = "float16"
111
+ else:
112
+ raise ValueError(f"Unsupported merge method: {method}")
113
+
114
+ def create_merge_config_linear(self) -> "MergeConfiguration":
115
+ """
116
+ Creates a merge configuration for a linear merge of two models with specified weights.
117
+ """
118
+ # Create the merge configuration dictionary
119
+ merge_config_dict = {
120
+ "dtype": self.dtype,
121
+ "merge_method": "linear",
122
+ "models": [
123
+ {"model": self.policy_model_path, "parameters": {"weight": self.policy_model_weight}},
124
+ {"model": self.target_model_path, "parameters": {"weight": self.target_model_weight}},
125
+ ],
126
+ }
127
+
128
+ # Create the MergeConfiguration from the dictionary
129
+ merge_config = MergeConfiguration.model_validate(merge_config_dict)
130
+
131
+ return merge_config
132
+
133
+ def create_merge_config_ties(self) -> "MergeConfiguration":
134
+ """
135
+ Creates a merge configuration for a TIES merge of two models, with specified weights and densities.
136
+ """
137
+ # Create the TIES merge configuration dictionary
138
+ merge_config_dict = {
139
+ "merge_method": "ties",
140
+ "slices": None, # Optional slices if needed
141
+ "models": [
142
+ {
143
+ "model": {
144
+ "model": {"path": self.target_model_path, "revision": None},
145
+ "lora": None,
146
+ "override_architecture": None,
147
+ },
148
+ "parameters": {"density": self.target_model_density, "weight": self.target_model_weight},
149
+ },
150
+ {
151
+ "model": {
152
+ "model": {"path": self.policy_model_path, "revision": None},
153
+ "lora": None,
154
+ "override_architecture": None,
155
+ },
156
+ "parameters": {"density": self.policy_model_density, "weight": self.policy_model_weight},
157
+ },
158
+ ],
159
+ "parameters": {"normalize": self.normalize},
160
+ "base_model": {
161
+ "model": {"path": self.policy_model_path, "revision": None},
162
+ "lora": None,
163
+ "override_architecture": None,
164
+ },
165
+ "dtype": self.dtype,
166
+ "tokenizer_source": None,
167
+ "tokenizer": None,
168
+ "chat_template": None,
169
+ "out_dtype": None,
170
+ }
171
+
172
+ # Create the MergeConfiguration from the dictionary
173
+ merge_config = MergeConfiguration.model_validate(merge_config_dict)
174
+
175
+ return merge_config
176
+
177
+ def create_merge_config_dare_ties(self) -> "MergeConfiguration":
178
+ """
179
+ Creates a merge configuration for a DARE TIES merge of two models, with specified weights and densities.
180
+ """
181
+ # Create the DARE TIES merge configuration dictionary
182
+ merge_config_dict = {
183
+ "merge_method": "dare_ties",
184
+ "slices": None, # Optional slices if needed
185
+ "models": [
186
+ {
187
+ "model": {
188
+ "model": {"path": self.target_model_path, "revision": None},
189
+ "lora": None,
190
+ "override_architecture": None,
191
+ },
192
+ "parameters": {"density": self.target_model_density, "weight": self.target_model_weight},
193
+ },
194
+ {
195
+ "model": {
196
+ "model": {"path": self.policy_model_path, "revision": None},
197
+ "lora": None,
198
+ "override_architecture": None,
199
+ },
200
+ "parameters": {"density": self.policy_model_density, "weight": self.policy_model_weight},
201
+ },
202
+ ],
203
+ "parameters": {"normalize": self.normalize},
204
+ "base_model": {
205
+ "model": {"path": self.policy_model_path, "revision": None},
206
+ "lora": None,
207
+ "override_architecture": None,
208
+ },
209
+ "dtype": self.dtype,
210
+ "tokenizer_source": None,
211
+ "tokenizer": None,
212
+ "chat_template": None,
213
+ "out_dtype": None,
214
+ }
215
+
216
+ # Create the MergeConfiguration from the dictionary
217
+ merge_config = MergeConfiguration.model_validate(merge_config_dict)
218
+
219
+ return merge_config
220
+
221
+ def create_merge_config_slerp(self) -> "MergeConfiguration":
222
+ """
223
+ Creates a merge configuration for a SLERP merge of a model with a base model.
224
+ """
225
+
226
+ # Create the SLERP merge configuration dictionary
227
+ merge_config_dict = {
228
+ "merge_method": "slerp",
229
+ "slices": None, # Optional slices if needed
230
+ "models": [
231
+ {
232
+ "model": {
233
+ "model": {"path": self.target_model_path, "revision": None},
234
+ "lora": None,
235
+ "override_architecture": None,
236
+ },
237
+ "parameters": None, # No specific parameters for SLERP model
238
+ }
239
+ ],
240
+ "parameters": {
241
+ "t": self.t_values # Set the t values for SLERP
242
+ },
243
+ "base_model": {
244
+ "model": {"path": self.policy_model_path, "revision": None},
245
+ "lora": None,
246
+ "override_architecture": None,
247
+ },
248
+ "dtype": self.dtype,
249
+ "tokenizer_source": None,
250
+ "tokenizer": None,
251
+ "chat_template": None,
252
+ "out_dtype": None,
253
+ }
254
+
255
+ # Create the MergeConfiguration from the dictionary
256
+ merge_config = MergeConfiguration.model_validate(merge_config_dict)
257
+
258
+ return merge_config
259
+
260
+ def create(self) -> "MergeConfiguration":
261
+ if self.method == "linear":
262
+ return self.create_merge_config_linear()
263
+ elif self.method == "ties":
264
+ return self.create_merge_config_ties()
265
+ elif self.method == "dare_ties":
266
+ return self.create_merge_config_dare_ties()
267
+ elif self.method == "slerp":
268
+ return self.create_merge_config_slerp()
269
+
270
+
271
+ def merge_models(config: "MergeConfiguration", out_path: str):
272
+ """
273
+ Merge two models using mergekit
274
+
275
+ Args:
276
+ config (`MergeConfiguration`): The merge configuration.
277
+ out_path (`str`): The output path for the merged model.
278
+ """
279
+ if not is_mergekit_available():
280
+ raise ImportError("merge_models requires the `mergekit` extra. To install, run `pip install mergekit`.")
281
+ run_merge(
282
+ config,
283
+ out_path=out_path,
284
+ options=MergeOptions(
285
+ device="auto",
286
+ cuda=torch.cuda.is_available(),
287
+ copy_tokenizer=True,
288
+ lazy_unpickle=False,
289
+ low_cpu_memory=False,
290
+ ),
291
+ )
292
+
293
+
294
+ class MergeModelCallback(TrainerCallback):
295
+ r"""
296
+ A [`~transformers.TrainerCallback`] that merges the policy model (the model being trained) with another model based
297
+ on a merge configuration.
298
+
299
+ Args:
300
+ merge_config ([`experimental.merge_model_callback.MergeConfig`], *optional*):
301
+ Configuration used for the merging process. If not provided, the default
302
+ [`~experimental.merge_model_callback.MergeConfig`] is used.
303
+ merge_at_every_checkpoint (`bool`, *optional*, defaults to `False`):
304
+ Whether to merge the model at every checkpoint.
305
+ push_to_hub (`bool`, *optional*, defaults to `False`):
306
+ Whether to push the merged model to the Hub after merging.
307
+
308
+ Example:
309
+
310
+ ```python
311
+ from trl.experimental.merge_model_callback import MergeConfig, MergeModelCallback
312
+
313
+ config = MergeConfig()
314
+ merge_callback = MergeModelCallback(config)
315
+ trainer = DPOTrainer(..., callbacks=[merge_callback])
316
+ ```
317
+ """
318
+
319
+ def __init__(
320
+ self,
321
+ merge_config: "MergeConfig | None" = None,
322
+ merge_at_every_checkpoint: bool = False,
323
+ push_to_hub: bool = False,
324
+ ):
325
+ if not is_mergekit_available():
326
+ raise ImportError(
327
+ "MergeModelCallback requires the `mergekit` extra. To install, run `pip install mergekit`."
328
+ )
329
+ self.merge_config = merge_config or MergeConfig()
330
+ self.merge_at_every_checkpoint = merge_at_every_checkpoint
331
+ self.push_to_hub = push_to_hub
332
+
333
+ def _merge_and_maybe_push(self, output_dir, global_step, model):
334
+ checkpoint_path = os.path.join(output_dir, f"checkpoint-{global_step}")
335
+ self.merge_config.policy_model_path = checkpoint_path
336
+ if self.merge_config.target_model_path is None:
337
+ self.merge_config.target_model_path = get_config_model_id(model.config)
338
+ merge_path = os.path.join(checkpoint_path, "merged")
339
+
340
+ merge_models(self.merge_config.create(), merge_path)
341
+
342
+ if self.push_to_hub:
343
+ repo_name = f"{output_dir}_checkpoint-{global_step}_merged"
344
+ upload_model_to_hf(merge_path, repo_name)
345
+
346
+ def on_save(self, args, state, control, model=None, **kwargs):
347
+ if self.merge_at_every_checkpoint:
348
+ self._merge_and_maybe_push(args.output_dir, state.global_step, model)
349
+
350
+ def on_train_end(self, args, state, control, model=None, **kwargs):
351
+ if not self.merge_at_every_checkpoint:
352
+ self._merge_and_maybe_push(args.output_dir, state.global_step, model)
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/minillm/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .minillm_config import MiniLLMConfig
16
+ from .minillm_trainer import MiniLLMTrainer
17
+
18
+
19
+ __all__ = ["MiniLLMConfig", "MiniLLMTrainer"]
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/minillm/minillm_config.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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, field
16
+ from typing import Any
17
+
18
+ from ...trainer.base_config import _BaseConfig
19
+ from ...trainer.grpo_config import GRPOConfig
20
+
21
+
22
+ @dataclass
23
+ class MiniLLMConfig(GRPOConfig):
24
+ """
25
+ Configuration class for [`MiniLLMTrainer`].
26
+
27
+ This class includes only the parameters that are specific to MiniLLM training. For a full list of training
28
+ arguments, please refer to the [`~transformers.TrainingArguments`] and [`GRPOConfig`] documentation.
29
+
30
+ Args:
31
+ teacher_model_init_kwargs (`dict[str, Any]`, *optional*):
32
+ Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model
33
+ from a string.
34
+ disable_dropout (`bool`, *optional*, defaults to `True`):
35
+ Whether to disable dropout in the model.
36
+ rkl_advantage (`bool`, *optional*, defaults to `True`):
37
+ Whether to add the reverse KL advantage to the reward advantage.
38
+ single_step_decomposition (`bool`, *optional*, defaults to `True`):
39
+ Whether to use single-step decomposition for the KL divergence computation.
40
+ kd_temperature (`float`, *optional*, defaults to `1.0`):
41
+ Temperature for knowledge distillation. Higher temperatures produce softer probability distributions over
42
+ classes.
43
+ gamma (`float`, *optional*, defaults to `0.0`):
44
+ Discount factor for future rewards in reinforcement learning.
45
+ length_normalization (`bool`, *optional*, defaults to `True`):
46
+ Whether to apply length normalization to the rewards.
47
+ """
48
+
49
+ _VALID_DICT_FIELDS = GRPOConfig._VALID_DICT_FIELDS + ["teacher_model_init_kwargs"]
50
+
51
+ teacher_model_init_kwargs: dict[str, Any] | str | None = field(
52
+ default=None,
53
+ metadata={
54
+ "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the "
55
+ "teacher model from a string."
56
+ },
57
+ )
58
+ disable_dropout: bool = field(
59
+ default=True,
60
+ metadata={"help": "Whether to disable dropouts in `model`."},
61
+ )
62
+ rkl_advantage: bool = field(
63
+ default=True,
64
+ metadata={"help": "Whether to add the reverse KL advantage to the reward advantage."},
65
+ )
66
+ single_step_decomposition: bool = field(
67
+ default=True,
68
+ metadata={"help": "Whether to use single-step decomposition for the KL divergence computation."},
69
+ )
70
+ kd_temperature: float = field(
71
+ default=1.0,
72
+ metadata={
73
+ "help": "Temperature for knowledge distillation. Higher temperatures produce softer probability "
74
+ "distributions over classes."
75
+ },
76
+ )
77
+ gamma: float = field(
78
+ default=0.0,
79
+ metadata={"help": "Discount factor for future rewards in reinforcement learning."},
80
+ )
81
+ length_normalization: bool = field(
82
+ default=True,
83
+ metadata={"help": "Whether to apply length normalization to the rewards."},
84
+ )
85
+
86
+ def __post_init__(self):
87
+ # We do not use the post_init of GRPOConfig because:
88
+ # 1. num_generations can be < 2 in MiniLLMConfig. Scale_rewards must be set to "none" to avoid nan.
89
+ _BaseConfig.__post_init__(self)
90
+
91
+ self.scale_rewards = {True: "group", False: "none"}.get(self.scale_rewards, self.scale_rewards)
92
+ if self.num_generations == 1:
93
+ self.scale_rewards = "none"
94
+
95
+ num_processes = self.world_size
96
+ # The current default effective batch size
97
+ if self.generation_batch_size is None and self.steps_per_generation is None:
98
+ self.steps_per_generation = self.gradient_accumulation_steps
99
+ self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
100
+ elif self.generation_batch_size is not None and self.steps_per_generation is None:
101
+ # Just ensure the value is divisible by the global batch size
102
+ if self.generation_batch_size % (self.per_device_train_batch_size * num_processes) != 0:
103
+ raise ValueError(
104
+ f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size "
105
+ f"({self.per_device_train_batch_size * num_processes})."
106
+ )
107
+ self.steps_per_generation = self.generation_batch_size // (
108
+ self.per_device_train_batch_size * num_processes
109
+ )
110
+ elif self.generation_batch_size is None and self.steps_per_generation is not None:
111
+ self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
112
+ else:
113
+ raise ValueError(
114
+ "'generation_batch_size' and 'steps_per_generation' can not be both configured at the same time"
115
+ )
116
+
117
+ if self.do_eval and self.eval_strategy != "no":
118
+ # Determine the number of generations to use for evaluation
119
+ num_generations = self.num_generations_eval or self.num_generations
120
+
121
+ # Just ensure the value is divisible by the global batch size
122
+ if (self.per_device_eval_batch_size * num_processes) % num_generations != 0:
123
+ raise ValueError(
124
+ f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be "
125
+ f"divisible by the number of generations used for evaluation ({num_generations})."
126
+ )
127
+
128
+ # The generation batch must contain full prompt groups (no partials), so it must be divisible by
129
+ # num_generations.
130
+ if self.generation_batch_size % self.num_generations != 0:
131
+ raise ValueError(
132
+ f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations "
133
+ f"({self.num_generations})."
134
+ )
135
+
136
+ if self.delta is not None and self.use_liger_kernel:
137
+ raise ValueError("Liger kernel does not support two-sided GRPO loss yet.")
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/minillm/minillm_trainer.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 textwrap
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+ import transformers
21
+ from datasets import Dataset, IterableDataset
22
+ from packaging.version import Version
23
+ from transformers import (
24
+ AutoModelForCausalLM,
25
+ PreTrainedModel,
26
+ PreTrainedTokenizerBase,
27
+ ProcessorMixin,
28
+ TrainerCallback,
29
+ )
30
+ from transformers.utils import is_peft_available
31
+
32
+ from ...models import prepare_deepspeed
33
+ from ...trainer.grpo_trainer import GRPOTrainer, RewardFunc, RolloutFunc
34
+ from ...trainer.utils import disable_dropout_in_model, get_config_model_id
35
+ from ..utils import empty_cache
36
+ from .minillm_config import MiniLLMConfig
37
+
38
+
39
+ if is_peft_available():
40
+ from peft import PeftConfig
41
+
42
+
43
+ def dummy_reward_func(completions: list, **kwargs):
44
+ # placeholder reward function when no reward function is provided
45
+ return [1.0 for _ in completions]
46
+
47
+
48
+ class MiniLLMTrainer(GRPOTrainer):
49
+ """
50
+ Trainer for the Knowledge Distillation of Language Models (MiniLLM) method. This algorithm was initially proposed
51
+ in the paper [Knowledge Distillation of Large Language Models](https://huggingface.co/papers/2306.08543).
52
+
53
+ Example:
54
+
55
+ ```python
56
+ from datasets import load_dataset
57
+ from trl.experimental.minillm import MiniLLMTrainer
58
+
59
+ dataset = load_dataset("trl-lib/tldr", split="train")
60
+
61
+ trainer = MiniLLMTrainer(
62
+ model="Qwen/Qwen3-0.6B",
63
+ teacher_model="Qwen/Qwen3-1.7B",
64
+ train_dataset=dataset,
65
+ )
66
+ trainer.train()
67
+ ```
68
+
69
+ Args:
70
+ model (`str | PreTrainedModel`):
71
+ Model to be trained. Can be either:
72
+
73
+ - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
74
+ path to a *directory* containing model weights saved using
75
+ [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
76
+ using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in
77
+ `args.model_init_kwargs`.
78
+ - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
79
+ teacher_model (`PreTrainedModel | nn.Module | str`):
80
+ Teacher model used for knowledge distillation. Instantiated similarly to `model`.
81
+ reward_funcs (`RewardFunc | list[RewardFunc]`, *optional*):
82
+ Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
83
+ functions with the prompts and completions and sum the rewards. Can be either:
84
+
85
+ - A single reward function, such as:
86
+ - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a
87
+ path to a *directory* containing model weights saved using
88
+ [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
89
+ using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the
90
+ keyword arguments in `args.model_init_kwargs`.
91
+ - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported.
92
+ - A custom reward function: The function is provided with the prompts and the generated completions,
93
+ plus any additional columns in the dataset. It should return a list of rewards. Custom reward
94
+ functions can also return `None` when the reward is not applicable to those samples. This is useful
95
+ for multi-task training where different reward functions apply to different types of samples. When a
96
+ reward function returns `None` for a sample, that reward function is excluded from the reward
97
+ calculation for that sample. For more details, see [Using a custom reward
98
+ function](#using-a-custom-reward-function).
99
+
100
+ The trainer's state is also passed to the reward function. The trainer's state is an instance of
101
+ [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the
102
+ reward function's signature.
103
+ - A list of reward functions, where each item can independently be any of the above types. Mixing different
104
+ types within the list (e.g., a string model ID and a custom reward function) is allowed.
105
+ args ([`experimental.minillm.MiniLLMConfig`], *optional*):
106
+ Configuration for this trainer. If `None`, a default configuration is used.
107
+ train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
108
+ Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is
109
+ ignored. The format of the samples can be either:
110
+
111
+ - [Standard](dataset_formats#standard): Each sample contains plain text.
112
+ - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
113
+ and content).
114
+ eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
115
+ Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
116
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*):
117
+ Processing class used to process the data. The padding side must be set to "left". If `None`, the
118
+ processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A
119
+ padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token,
120
+ `tokenizer.eos_token` will be used as the default.
121
+ reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*):
122
+ Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:
123
+
124
+ - A single processing class: Used when `reward_funcs` contains only one reward function.
125
+ - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
126
+ If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is
127
+ `None`, the tokenizer for the model is automatically loaded using
128
+ [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward
129
+ functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes`
130
+ are ignored.
131
+ callbacks (list of [`~transformers.TrainerCallback`], *optional*):
132
+ List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
133
+ in [here](https://huggingface.co/docs/transformers/main_classes/callback).
134
+
135
+ If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
136
+ method.
137
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`):
138
+ A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your
139
+ model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`.
140
+ peft_config ([`~peft.PeftConfig`], *optional*):
141
+ PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
142
+ rollout_func (`RolloutFunc`, *optional*):
143
+ Function to use for generating completions. It must take prompts, args, and processing_class as parameters
144
+ and return a dict with `"prompt_ids"`, `"completion_ids"`, and `"logprobs"` fields. Any other fields that
145
+ are forwarded to the reward functions. This feature is experimental and may change or be removed at any
146
+ time without prior notice.
147
+ """
148
+
149
+ _tag_names = ["trl", "minillm"]
150
+ _name = "MiniLLM"
151
+ _paper = {
152
+ "title": "MiniLLM: Knowledge Distillation of Large Language Models",
153
+ "id": "2306.08543",
154
+ # docstyle-ignore
155
+ "citation": textwrap.dedent("""\
156
+ @inproceedings{
157
+ gu2024minillm,
158
+ title={{MiniLLM: Knowledge Distillation of Large Language Models}},
159
+ author={Yuxian Gu and Li Dong and Furu Wei and Minlie Huang},
160
+ booktitle={The Twelfth International Conference on Learning Representations},
161
+ year={2024},
162
+ url={https://openreview.net/forum?id=5h0qf7IBZZ}
163
+ }"""),
164
+ }
165
+
166
+ def __init__(
167
+ self,
168
+ model: str | PreTrainedModel,
169
+ teacher_model: PreTrainedModel | nn.Module | str,
170
+ reward_funcs: RewardFunc | list[RewardFunc] | None = None,
171
+ args: MiniLLMConfig | None = None,
172
+ train_dataset: Dataset | IterableDataset | None = None,
173
+ eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
174
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
175
+ reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None,
176
+ callbacks: list[TrainerCallback] | None = None,
177
+ optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
178
+ peft_config: "PeftConfig | None" = None,
179
+ rollout_func: RolloutFunc | None = None,
180
+ ):
181
+ if reward_funcs is None:
182
+ reward_funcs = [dummy_reward_func]
183
+
184
+ # Args
185
+ if args is None:
186
+ model_name = model if isinstance(model, str) else get_config_model_id(model.config)
187
+ model_name = model_name.split("/")[-1]
188
+ args = MiniLLMConfig(f"{model_name}-MiniLLM")
189
+
190
+ # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
191
+ # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
192
+ # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
193
+ # default to the recommended non-reentrant behavior here, while preserving any user-provided value.
194
+ if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
195
+ args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
196
+ args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
197
+
198
+ super().__init__(
199
+ model,
200
+ reward_funcs,
201
+ args=args,
202
+ train_dataset=train_dataset,
203
+ eval_dataset=eval_dataset,
204
+ processing_class=processing_class,
205
+ reward_processing_classes=reward_processing_classes,
206
+ callbacks=callbacks,
207
+ optimizers=optimizers,
208
+ peft_config=peft_config,
209
+ rollout_func=rollout_func,
210
+ )
211
+
212
+ if args.teacher_model_init_kwargs is None:
213
+ teacher_model_init_kwargs = {}
214
+ elif not isinstance(teacher_model, str):
215
+ raise ValueError(
216
+ "You passed teacher_model_init_kwargs to the MiniLLMConfig, but your teacher_model is already instantiated."
217
+ )
218
+ else:
219
+ teacher_model_init_kwargs = args.teacher_model_init_kwargs
220
+ teacher_model_init_kwargs["dtype"] = (
221
+ teacher_model_init_kwargs["dtype"]
222
+ if teacher_model_init_kwargs["dtype"] in ["auto", None]
223
+ else getattr(torch, teacher_model_init_kwargs["dtype"])
224
+ )
225
+
226
+ if isinstance(teacher_model, str):
227
+ teacher_model = AutoModelForCausalLM.from_pretrained(teacher_model, **teacher_model_init_kwargs)
228
+
229
+ # Disable dropout in the model
230
+ if args.disable_dropout:
231
+ disable_dropout_in_model(self.model)
232
+
233
+ if self.is_deepspeed_enabled:
234
+ self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator)
235
+ else:
236
+ self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True)
237
+
238
+ self.temperature = args.temperature
239
+ self.kd_temperature = args.kd_temperature
240
+ self.single_step_decomposition = args.single_step_decomposition
241
+ self.rkl_advantage = args.rkl_advantage
242
+ self.gamma = args.gamma
243
+ self.length_normalization = args.length_normalization
244
+
245
+ def _single_step_decomposition_loss(
246
+ self,
247
+ student_log_probs: torch.Tensor,
248
+ teacher_log_probs: torch.Tensor,
249
+ mask: torch.Tensor | None = None,
250
+ reduction: str = "batchmean",
251
+ ):
252
+ """
253
+ Compute the MiniLLM loss for knowledge distillation using F.kl_div. See Eq. (1) of
254
+ https://huggingface.co/papers/2306.08543 for the definition.
255
+
256
+ Args:
257
+ student_logits:
258
+ Tensor of shape (batch_size, sequence_length, vocab_size)
259
+ teacher_logits:
260
+ Tensor of shape (batch_size, sequence_length, vocab_size)
261
+ labels:
262
+ Tensor of shape (batch_size, sequence_length) with -100 for padding tokens to ignore when computing
263
+ loss
264
+ beta:
265
+ Interpolation coefficient between 0 and 1 (default: 0.5)
266
+ temperature:
267
+ Softmax temperature (default: 1.0)
268
+ reduction:
269
+ Specifies the reduction to apply to the output (default: 'batchmean')
270
+
271
+ Returns:
272
+ loss: Scalar tensor with the generalized JSD loss
273
+ """
274
+ reg_loss = F.kl_div(
275
+ teacher_log_probs, student_log_probs, reduction="none", log_target=True
276
+ ) # (batch_size, sequence_length)
277
+
278
+ # Masking
279
+ if mask is not None:
280
+ reg_loss = reg_loss[mask]
281
+
282
+ # Apply reduction
283
+ if reduction == "batchmean":
284
+ return reg_loss.sum() / mask.sum() if mask is not None else reg_loss.sum() / reg_loss.size(0)
285
+ elif reduction == "sum":
286
+ return reg_loss.sum()
287
+ elif reduction == "mean":
288
+ return reg_loss.mean()
289
+ else:
290
+ return reg_loss
291
+
292
+ def _compute_advantage(
293
+ self,
294
+ student_log_probs_on_labels: torch.Tensor,
295
+ teacher_log_probs_on_labels: torch.Tensor,
296
+ mask: torch.Tensor | None = None,
297
+ ) -> torch.Tensor:
298
+ r"""Compute the advantage for Reverse KL Divergence.
299
+
300
+ Mostly following [this
301
+ implementation](https://github.com/microsoft/LMOps/blob/e210d2c026b9958617887762400778ace81172e6/minillm/minillm/losses.py#L37-L49).
302
+
303
+ $$ \text{rewards}_t = \text{teacher\_log\_probs\_on\_labels}_t - \text{student\_log\_probs\_on\_labels}_t $$
304
+
305
+ If length normalization is enabled:
306
+
307
+ $$ \text{lengths}_t = \sum_{i=t}^{T} \gamma^{i-t} $$
308
+
309
+ $$ \text{advantages}_t = \frac{\sum_{i=t}^{T} \gamma^{i-t} R_i}{\text{lengths}_t} $$
310
+
311
+ Otherwise:
312
+
313
+ $$ \text{advantages}_t = \sum_{i=t}^{T} \gamma^{i-t} R_i $$
314
+
315
+ Args:
316
+ student_log_probs_on_labels: Log probabilities of the student model on the labels.
317
+ Shape: (batch_size, sequence_length)
318
+ teacher_log_probs_on_labels: Log probabilities of the teacher model on the labels.
319
+ Shape: (batch_size, sequence_length)
320
+ mask: Optional mask to apply to the log probabilities. Shape: (batch_size, sequence_length)
321
+ Returns:
322
+ advantage: Computed advantage. Shape: (batch_size, sequence_length)
323
+ """
324
+ response_length = student_log_probs_on_labels.size(1)
325
+ if mask is None:
326
+ mask = torch.ones_like(student_log_probs_on_labels)
327
+ mask = mask.float()
328
+ student_log_probs_on_labels = student_log_probs_on_labels * mask
329
+ teacher_log_probs_on_labels = teacher_log_probs_on_labels * mask
330
+
331
+ rewards = teacher_log_probs_on_labels - student_log_probs_on_labels # (batch_size, sequence_length)
332
+
333
+ if self.gamma > 0.0:
334
+ gamma_pow = torch.pow(self.gamma, torch.arange(response_length, device=rewards.device))
335
+
336
+ advantages = rewards * gamma_pow
337
+ advantages = advantages.flip(1).cumsum(dim=1).flip(1)
338
+
339
+ if self.length_normalization:
340
+ mask = torch.where(mask < 0.5, 1e-4, mask)
341
+ lengths = mask * gamma_pow
342
+ lengths = lengths.flip(1).cumsum(dim=1).flip(1)
343
+ advantages = advantages / lengths
344
+ else:
345
+ advantages = rewards
346
+
347
+ return advantages
348
+
349
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
350
+ input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1)
351
+ attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1)
352
+ labels = input_ids.clone()
353
+ labels[attention_mask == 0] = -100
354
+
355
+ # Compute student output
356
+ student_outputs = model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False)
357
+
358
+ # Compute teacher output in eval mode
359
+ self.teacher_model.eval()
360
+ with torch.no_grad():
361
+ teacher_outputs = self.teacher_model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False)
362
+
363
+ # Slice the logits for the generated tokens using the inputs["prompts"] lengths
364
+ prompt_lengths = inputs["prompt_ids"].shape[1]
365
+ student_logits = student_outputs.logits[:, prompt_lengths - 1 : -1, :]
366
+ teacher_logits = teacher_outputs.logits[:, prompt_lengths - 1 : -1, :]
367
+ shifted_labels = input_ids[:, prompt_lengths:]
368
+
369
+ # Apply temperature scaling
370
+ student_logits = student_logits / self.kd_temperature
371
+ teacher_logits = teacher_logits / self.kd_temperature
372
+
373
+ # Compute log probabilities for student and probabilities for teacher
374
+ student_log_probs = F.log_softmax(student_logits, dim=-1)
375
+ teacher_log_probs = F.log_softmax(teacher_logits, dim=-1)
376
+
377
+ student_log_probs_on_labels = torch.gather(
378
+ student_log_probs, dim=-1, index=shifted_labels.unsqueeze(-1)
379
+ ).squeeze(-1)
380
+ teacher_log_probs_on_labels = torch.gather(
381
+ teacher_log_probs, dim=-1, index=shifted_labels.unsqueeze(-1)
382
+ ).squeeze(-1)
383
+
384
+ mask = shifted_labels != -100
385
+
386
+ if self.rkl_advantage:
387
+ reverse_kl_advantage = self._compute_advantage(
388
+ student_log_probs_on_labels=student_log_probs_on_labels,
389
+ teacher_log_probs_on_labels=teacher_log_probs_on_labels,
390
+ mask=mask,
391
+ )
392
+
393
+ inputs["advantages"] = inputs["advantages"].unsqueeze(1) + reverse_kl_advantage
394
+
395
+ # Compute GRPO loss on verifiable reward
396
+ loss = self._compute_loss(model, inputs)
397
+
398
+ # Compute loss
399
+ if self.single_step_decomposition:
400
+ single_step_decomposition_loss = self._single_step_decomposition_loss(
401
+ student_log_probs=student_log_probs,
402
+ teacher_log_probs=teacher_log_probs,
403
+ mask=mask,
404
+ )
405
+
406
+ loss += single_step_decomposition_loss
407
+
408
+ # Empty cache
409
+ empty_cache()
410
+
411
+ # Return loss
412
+ return (loss, student_outputs) if return_outputs else loss
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/nash_md/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .nash_md_config import NashMDConfig
16
+ from .nash_md_trainer import NashMDTrainer
17
+
18
+
19
+ __all__ = ["NashMDConfig", "NashMDTrainer"]
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/nash_md/nash_md_config.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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, field
16
+
17
+ from ..online_dpo import OnlineDPOConfig
18
+
19
+
20
+ @dataclass
21
+ class NashMDConfig(OnlineDPOConfig):
22
+ r"""
23
+ Configuration class for the [`experimental.nash_md.NashMDTrainer`].
24
+
25
+ Subclass of [`experimental.online_dpo.OnlineDPOConfig`] we can use all its arguments and add the following:
26
+
27
+ Parameters:
28
+ mixture_coef (`float` or `list[float]`, *optional*, defaults to `0.5`):
29
+ Logit mixture coefficient for the model and reference model. If a list of floats is provided then the
30
+ mixture coefficient is selected for each new epoch and the last coefficient is used for the rest of the
31
+ epochs.
32
+ """
33
+
34
+ mixture_coef: list[float] = field(
35
+ default_factory=lambda: [0.5],
36
+ metadata={
37
+ "help": "Logit mixture coefficient for the model and reference model. If a list of floats is provided "
38
+ "then the mixture coefficient is selected for each new epoch and the last coefficient is used for the "
39
+ "rest of the epochs."
40
+ },
41
+ )
42
+
43
+ def __post_init__(self):
44
+ super().__post_init__()
45
+ if hasattr(self.mixture_coef, "__len__") and len(self.mixture_coef) == 1:
46
+ self.mixture_coef = self.mixture_coef[0]
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/nash_md/nash_md_trainer.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 textwrap
16
+ from collections.abc import Callable
17
+ from typing import Any
18
+
19
+ import jinja2
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ from datasets import Dataset, IterableDataset
24
+ from transformers import (
25
+ BaseImageProcessor,
26
+ FeatureExtractionMixin,
27
+ GenerationMixin,
28
+ PreTrainedModel,
29
+ PreTrainedTokenizerBase,
30
+ ProcessorMixin,
31
+ TrainerCallback,
32
+ )
33
+ from transformers.trainer_utils import EvalPrediction
34
+ from transformers.training_args import OptimizerNames
35
+ from transformers.utils import is_peft_available
36
+
37
+ from ...data_utils import is_conversational, maybe_apply_chat_template
38
+ from ...models.utils import unwrap_model_for_generation
39
+ from ...trainer.utils import selective_log_softmax
40
+ from ..judges import BasePairwiseJudge
41
+ from ..online_dpo import OnlineDPOTrainer
42
+ from ..utils import SIMPLE_CHAT_TEMPLATE, empty_cache, get_reward, truncate_right
43
+ from .nash_md_config import NashMDConfig
44
+
45
+
46
+ if is_peft_available():
47
+ from peft import PeftModel
48
+
49
+
50
+ class GeometricMixtureWrapper(GenerationMixin):
51
+ """
52
+ Geometric Mixture generation wrapper that samples from the logits of two model's geometric mixture.
53
+
54
+ Args:
55
+ model ([`~transformers.PreTrainedModel`]): The model to be wrapped.
56
+ ref_model ([`~transformers.PreTrainedModel`]): The reference model.
57
+ generation_config ([`~transformers.GenerationConfig`]): The generation config.
58
+ mixture_coef (`float`, *optional* - default: 0.5): The mixture coefficient.
59
+ """
60
+
61
+ main_input_name = "input_ids"
62
+ _supports_cache_class = False
63
+ _supports_static_cache = False
64
+ _is_stateful = False
65
+
66
+ def __init__(self, model, ref_model, generation_config, mixture_coef=0.5, device=None):
67
+ super().__init__()
68
+
69
+ self.model = model
70
+ self.config = model.config
71
+ self.ref_model = ref_model
72
+ self.generation_config = generation_config
73
+ self.mixture_coef = mixture_coef
74
+ self.device = device
75
+ if hasattr(self.model, "_is_stateful"):
76
+ self._is_stateful = self.model._is_stateful
77
+
78
+ def __call__(self, *args, **kwargs):
79
+ return self.forward(*args, **kwargs)
80
+
81
+ @torch.inference_mode()
82
+ def forward(self, *args, **kwargs):
83
+ model_outputs = self.model(*args, **kwargs)
84
+ model_logits = model_outputs.logits
85
+ ref_model_logits = self.ref_model(*args, **kwargs).logits
86
+
87
+ model_outputs.logits = torch.nn.functional.log_softmax(
88
+ self.mixture_coef * ref_model_logits + (1 - self.mixture_coef) * model_logits, dim=-1
89
+ )
90
+
91
+ return model_outputs
92
+
93
+ def prepare_inputs_for_generation(self, *args, **kwargs):
94
+ # turn off cache in the generation config
95
+ kwargs["use_cache"] = False
96
+ model_inputs = self.model.prepare_inputs_for_generation(*args, **kwargs)
97
+ _ = self.ref_model.prepare_inputs_for_generation(*args, **kwargs)
98
+
99
+ return model_inputs
100
+
101
+ def _validate_model_class(self):
102
+ self.model._validate_model_class()
103
+
104
+ def _validate_model_kwargs(self, model_kwargs):
105
+ return self.model._validate_model_kwargs(model_kwargs)
106
+
107
+
108
+ class NashMDTrainer(OnlineDPOTrainer):
109
+ """
110
+ Trainer for the Nash-MD method.
111
+
112
+ It is implemented as a subclass of [`experimental.online_dpo.OnlineDPOTrainer`].
113
+
114
+ Args:
115
+ model ([`~transformers.PreTrainedModel`]):
116
+ The model to train, preferably an `AutoModelForCausalLM`.
117
+ ref_model ([`~transformers.PreTrainedModel`]):
118
+ Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation
119
+ and loss. If no reference model is provided, the trainer will create a reference model with the same
120
+ architecture as the model to be optimized.
121
+ reward_funcs ([`~transformers.PreTrainedModel`]):
122
+ The reward model to score completions with, preferably an
123
+ [`~transformers.AutoModelForSequenceClassification`].
124
+ judge ([`experimental.judges.BasePairwiseJudge`]):
125
+ The judge to use for pairwise comparison of model completions.
126
+ args ([`experimental.nash_md.NashMDConfig`]):
127
+ The NashMD config arguments to use for training.
128
+ data_collator ([`~transformers.DataCollator`]):
129
+ The data collator to use for training. If None is specified, the default data collator
130
+ ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the
131
+ maximum length of the sequences in the batch, given a dataset of paired sequences.
132
+ train_dataset ([`~datasets.Dataset`]):
133
+ The dataset to use for training.
134
+ eval_dataset ([`~datasets.Dataset`]):
135
+ The dataset to use for evaluation.
136
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
137
+ Processing class used to process the data. If provided, will be used to automatically process the inputs
138
+ for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
139
+ reuse the fine-tuned model.
140
+ peft_config (`dict`):
141
+ The peft config to use for training.
142
+ compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
143
+ The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
144
+ metric values.
145
+ callbacks (`list[transformers.TrainerCallback]`):
146
+ The callbacks to use for training.
147
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
148
+ The optimizer and scheduler to use for training.
149
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
150
+ The function to use to preprocess the logits before computing the metrics.
151
+ """
152
+
153
+ _tag_names = ["trl", "nash-md"]
154
+ _name = "Nash-MD"
155
+ _paper = {
156
+ "title": "Nash Learning from Human Feedback",
157
+ "id": "2312.00886",
158
+ # docstyle-ignore
159
+ "citation": textwrap.dedent("""\
160
+ @inproceedings{munos2024nash,
161
+ title = {{Nash Learning from Human Feedback}},
162
+ author = {R{\'{e}}mi Munos and Michal Valko and Daniele Calandriello and Mohammad Gheshlaghi Azar and Mark Rowland and Zhaohan Daniel Guo and Yunhao Tang and Matthieu Geist and Thomas Mesnard and C{\\^{o}}me Fiegel and Andrea Michi and Marco Selvi and Sertan Girgin and Nikola Momchev and Olivier Bachem and Daniel J. Mankowitz and Doina Precup and Bilal Piot},
163
+ year = 2024,
164
+ booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024},
165
+ publisher = {OpenReview.net},
166
+ url = {https://openreview.net/forum?id=Y5AmNYiyCQ}
167
+ }"""),
168
+ }
169
+
170
+ def __init__(
171
+ self,
172
+ model: PreTrainedModel | nn.Module = None,
173
+ ref_model: PreTrainedModel | nn.Module = None,
174
+ reward_funcs: PreTrainedModel | nn.Module | None = None,
175
+ judge: BasePairwiseJudge | None = None,
176
+ args: NashMDConfig | None = None,
177
+ data_collator: Callable | None = None,
178
+ train_dataset: Dataset | IterableDataset | None = None,
179
+ eval_dataset: Dataset | dict[str, Dataset] | None = None,
180
+ processing_class: PreTrainedTokenizerBase
181
+ | BaseImageProcessor
182
+ | FeatureExtractionMixin
183
+ | ProcessorMixin
184
+ | None = None,
185
+ peft_config: dict | None = None,
186
+ compute_metrics: Callable[[EvalPrediction], dict] | None = None,
187
+ callbacks: list[TrainerCallback] | None = None,
188
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
189
+ preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
190
+ ) -> None:
191
+ super().__init__(
192
+ model=model,
193
+ ref_model=ref_model,
194
+ reward_funcs=reward_funcs,
195
+ judge=judge,
196
+ args=args,
197
+ data_collator=data_collator,
198
+ train_dataset=train_dataset,
199
+ eval_dataset=eval_dataset,
200
+ processing_class=processing_class,
201
+ reward_processing_classes=processing_class,
202
+ peft_config=peft_config,
203
+ compute_metrics=compute_metrics,
204
+ callbacks=callbacks,
205
+ optimizers=optimizers,
206
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
207
+ )
208
+
209
+ self._mixture_coef = self.args.mixture_coef
210
+
211
+ # Overwrite the stats dictionary to include NashMD specific statistics
212
+ self.stats = {
213
+ # Remove "non_score_reward", "rlhf_reward", "scores_margin"
214
+ # Add "mixture_coef"
215
+ "loss/kl": [],
216
+ "objective/entropy": [],
217
+ "loss/score": [],
218
+ "rewards/probabilities": [],
219
+ "rewards/accuracies": [],
220
+ "rewards/margins": [],
221
+ "logps/chosen": [],
222
+ "logps/rejected": [],
223
+ "val/model_contain_eos_token": [],
224
+ "val/ref_contain_eos_token": [],
225
+ "beta": [],
226
+ "mixture_coef": [],
227
+ }
228
+ if self.reward_funcs is not None:
229
+ if len(self.reward_funcs) != 1:
230
+ raise ValueError("NashMDTrainer only supports one reward function/model.")
231
+ self.reward_funcs = self.reward_funcs[0]
232
+ self.stats["rewards/chosen"] = []
233
+ self.stats["rewards/rejected"] = []
234
+
235
+ @property
236
+ def mixture_coef(self):
237
+ if isinstance(self._mixture_coef, list):
238
+ epoch = self.state.epoch
239
+ return self._mixture_coef[epoch] if epoch < len(self._mixture_coef) else self._mixture_coef[-1]
240
+ else:
241
+ return self._mixture_coef
242
+
243
+ def _generate_completions(self, model, prompts):
244
+ # Generate completions from the policy model.
245
+ with (
246
+ unwrap_model_for_generation(
247
+ model,
248
+ self.accelerator,
249
+ generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
250
+ ) as unwrapped_policy_for_gen_ctx
251
+ ):
252
+ model_output = unwrapped_policy_for_gen_ctx.generate(
253
+ input_ids=prompts["input_ids"],
254
+ attention_mask=prompts["attention_mask"],
255
+ generation_config=self.generation_config,
256
+ )
257
+
258
+ # Get the DDP/FSDP unwrapped version of the main model.
259
+ # This will be the policy model for GeometricMixtureWrapper (PEFT adapters active if PEFT is used).
260
+ policy_model_for_gmw = self.accelerator.unwrap_model(model)
261
+
262
+ # Determine the correct reference model for GeometricMixtureWrapper.
263
+ # This also needs to be DDP/FSDP unwrapped.
264
+ ref_model_for_gmw: torch.nn.Module
265
+ if self.ref_model is None:
266
+ # No explicit ref_model is provided.
267
+ # Use the base of the main `model` if it's a PEFT model.
268
+ # policy_model_for_gmw is already DDP-unwrapped.
269
+ if is_peft_available() and isinstance(policy_model_for_gmw, PeftModel):
270
+ ref_model_for_gmw = policy_model_for_gmw.get_base_model()
271
+ else:
272
+ # Not a PEFT model (or PEFT not available), or already a base model.
273
+ # Use the DDP-unwrapped policy model itself as the reference.
274
+ ref_model_for_gmw = policy_model_for_gmw
275
+ else:
276
+ # An explicit ref_model is provided. Unwrap it for DDP/FSDP.
277
+ ref_model_for_gmw = self.accelerator.unwrap_model(self.ref_model)
278
+
279
+ # Both models given to GeometricMixtureWrapper (policy_model_for_gmw and ref_model_for_gmw) are DDP-unwrapped.
280
+ with torch.no_grad(): # Ensure no_grad context for mixture model generation
281
+ mixture_model = GeometricMixtureWrapper(
282
+ model=policy_model_for_gmw,
283
+ ref_model=ref_model_for_gmw,
284
+ generation_config=self.generation_config,
285
+ mixture_coef=self.mixture_coef,
286
+ device=self.accelerator.device,
287
+ )
288
+
289
+ # TODO: use self._override_model_generation_config for both models?
290
+ mixture_output = mixture_model.generate(
291
+ input_ids=prompts["input_ids"],
292
+ attention_mask=prompts["attention_mask"],
293
+ generation_config=self.generation_config,
294
+ )
295
+
296
+ return model_output, mixture_output
297
+
298
+ def _process_completions(self, model_output, mixture_output, prompts):
299
+ context_length = prompts["input_ids"].shape[1]
300
+
301
+ # Process model completions
302
+ model_completion_ids = model_output[:, context_length:]
303
+ model_completion_ids, model_completion_mask = truncate_right(
304
+ model_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id
305
+ )
306
+ model_data = {
307
+ "input_ids": torch.cat((prompts["input_ids"], model_completion_ids), dim=1),
308
+ "attention_mask": torch.cat((prompts["attention_mask"], model_completion_mask), dim=1),
309
+ "raw": prompts["raw"],
310
+ }
311
+
312
+ # Process reference model completions
313
+ mixture_completion_ids = mixture_output[:, context_length:]
314
+ mixture_completion_ids, mixture_completion_mask = truncate_right(
315
+ mixture_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id
316
+ )
317
+ mixture_data = {
318
+ "input_ids": torch.cat((prompts["input_ids"], mixture_completion_ids), dim=1),
319
+ "attention_mask": torch.cat((prompts["attention_mask"], mixture_completion_mask), dim=1),
320
+ "raw": prompts["raw"],
321
+ }
322
+
323
+ return model_data, mixture_data
324
+
325
+ def _compute_rewards(self, model_data, mixture_data, context_length):
326
+ with torch.no_grad():
327
+ _, model_scores, _ = get_reward(
328
+ self.reward_funcs, model_data["input_ids"], self.processing_class.pad_token_id, context_length
329
+ )
330
+ _, mixture_scores, _ = get_reward(
331
+ self.reward_funcs, mixture_data["input_ids"], self.processing_class.pad_token_id, context_length
332
+ )
333
+
334
+ # Apply EOS penalty if needed
335
+ if self.args.missing_eos_penalty is not None:
336
+ model_contain_eos = torch.any(model_data["input_ids"] == self.processing_class.eos_token_id, dim=-1)
337
+ mixture_contain_eos = torch.any(mixture_data["input_ids"] == self.processing_class.eos_token_id, dim=-1)
338
+ model_scores[~model_contain_eos] -= self.args.missing_eos_penalty
339
+ mixture_scores[~mixture_contain_eos] -= self.args.missing_eos_penalty
340
+
341
+ return model_scores, mixture_scores
342
+
343
+ def _compute_judge(self, model_data, mixture_data, context_length):
344
+ prompts = model_data["raw"]
345
+ model_data_completions = self.processing_class.batch_decode(
346
+ model_data["input_ids"][:, context_length:], skip_special_tokens=True
347
+ )
348
+ model_data_completions = [completion.strip() for completion in model_data_completions]
349
+
350
+ mixture_data_completions = self.processing_class.batch_decode(
351
+ mixture_data["input_ids"][:, context_length:], skip_special_tokens=True
352
+ )
353
+ mixture_data_completions = [completion.strip() for completion in mixture_data_completions]
354
+ if is_conversational({"prompt": prompts[0]}):
355
+ model_data_completions = [
356
+ [{"role": "assistant", "content": completion}] for completion in model_data_completions
357
+ ]
358
+ environment = jinja2.Environment()
359
+ template = environment.from_string(SIMPLE_CHAT_TEMPLATE)
360
+ prompts = [template.render(messages=message) for message in prompts]
361
+ model_data_completions = [template.render(messages=completion) for completion in model_data_completions]
362
+
363
+ mixture_data_completions = [
364
+ [{"role": "assistant", "content": completion}] for completion in mixture_data_completions
365
+ ]
366
+ mixture_data_completions = [
367
+ template.render(messages=completion) for completion in mixture_data_completions
368
+ ]
369
+
370
+ probability = self.judge.judge(
371
+ prompts,
372
+ list(zip(model_data_completions, mixture_data_completions, strict=True)),
373
+ return_scores=True,
374
+ )
375
+ return torch.tensor(probability, device=model_data["input_ids"].device)
376
+
377
+ def _compute_logprobs(self, model, model_data, context_length):
378
+ def compute_logprobs_for_data(m, data):
379
+ output = m(data["input_ids"], attention_mask=data["attention_mask"])
380
+ logits = output.logits[:, context_length - 1 : -1]
381
+ token_logprobs = selective_log_softmax(logits, data["input_ids"][:, context_length:])
382
+ return token_logprobs
383
+
384
+ # Compute logprobs for model completions under the model
385
+ model_logprobs_model_data = compute_logprobs_for_data(model, model_data)
386
+
387
+ # Compute logprobs of model completions under the reference model
388
+ with torch.no_grad():
389
+ if self.ref_model is None:
390
+ with model.disable_adapter():
391
+ ref_logprobs_model_data = compute_logprobs_for_data(model, model_data)
392
+ else:
393
+ ref_logprobs_model_data = compute_logprobs_for_data(self.ref_model, model_data)
394
+
395
+ # Mask padding tokens
396
+ model_padding_mask = model_data["attention_mask"][:, context_length:] == 0
397
+ model_logprobs_model_data = model_logprobs_model_data.masked_fill(model_padding_mask, 0.0)
398
+ ref_logprobs_model_data = ref_logprobs_model_data.masked_fill(model_padding_mask, 0.0)
399
+
400
+ return (model_logprobs_model_data, ref_logprobs_model_data)
401
+
402
+ def _compute_losses(
403
+ self,
404
+ model_logprobs_model_data,
405
+ ref_logprobs_model_data,
406
+ probability,
407
+ ):
408
+ # reinforce score where 0.5 is a control variate
409
+ score = (probability - 0.5) * model_logprobs_model_data.sum(1)
410
+
411
+ # kl divergence via reinforce
412
+ with torch.no_grad():
413
+ log_ratio = model_logprobs_model_data - ref_logprobs_model_data
414
+ kl_div_log = log_ratio.sum(1)
415
+ kl_div_loss = (log_ratio * model_logprobs_model_data).sum(1)
416
+
417
+ # final loss
418
+ loss = self.beta * kl_div_loss - score
419
+
420
+ return loss.mean(), score, kl_div_log
421
+
422
+ def _log_statistics(
423
+ self,
424
+ model_data,
425
+ mixture_data,
426
+ model_logprobs_model_data,
427
+ ref_logprobs_model_data,
428
+ probability,
429
+ score,
430
+ kl_div,
431
+ context_length,
432
+ model_scores=None,
433
+ mixture_scores=None,
434
+ ):
435
+ # Helper function to gather and compute mean
436
+ def gather_mean(tensor):
437
+ return self.accelerator.gather_for_metrics(tensor).mean().item()
438
+
439
+ # Log score
440
+ self.stats["loss/score"].append(gather_mean(score))
441
+ # Log KL divergence
442
+ self.stats["loss/kl"].append(gather_mean(kl_div))
443
+
444
+ # Log logprobs
445
+ model_logprobs_model_data_sum = model_logprobs_model_data.sum(1)
446
+ ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1)
447
+
448
+ self.stats["logps/chosen"].append(gather_mean(model_logprobs_model_data_sum))
449
+ self.stats["logps/rejected"].append(gather_mean(ref_logprobs_model_data_sum))
450
+
451
+ # Log rewards
452
+ if self.reward_funcs is not None:
453
+ self.stats["rewards/chosen"].append(gather_mean(model_scores))
454
+ self.stats["rewards/rejected"].append(gather_mean(mixture_scores))
455
+
456
+ # Log probabilities
457
+ self.stats["rewards/probabilities"].append(gather_mean(probability))
458
+
459
+ # Calculate entropy for model data
460
+ entropy_model_data = -model_logprobs_model_data.sum(1)
461
+ self.stats["objective/entropy"].append(gather_mean(entropy_model_data))
462
+
463
+ # Calculate margins
464
+ margin = model_logprobs_model_data_sum - ref_logprobs_model_data_sum
465
+ self.stats["rewards/margins"].append(gather_mean(margin))
466
+
467
+ # Calculate accuracy
468
+ accuracy = (margin > 0).float()
469
+ self.stats["rewards/accuracies"].append(gather_mean(accuracy))
470
+
471
+ # Log EOS token statistics
472
+ model_eos = (model_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1)
473
+ mixture_eos = (mixture_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1)
474
+ self.stats["val/model_contain_eos_token"].append(gather_mean(model_eos.float()))
475
+ self.stats["val/ref_contain_eos_token"].append(gather_mean(mixture_eos.float()))
476
+
477
+ # Log beta and mixture coef
478
+ self.stats["beta"].append(self.beta)
479
+ self.stats["mixture_coef"].append(self.mixture_coef)
480
+
481
+ def training_step(
482
+ self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None
483
+ ) -> torch.Tensor:
484
+ model.train()
485
+
486
+ # Apply chat template and tokenize the input
487
+ batch_size = len(next(iter(inputs.values())))
488
+ prompts = inputs["prompt"]
489
+ inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)]
490
+ inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs]
491
+ inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs]
492
+ inputs = self.data_collator(inputs)
493
+
494
+ # need the prompt_ only
495
+ inputs = self._prepare_inputs(inputs)
496
+ context_length = inputs["prompt_input_ids"].shape[1]
497
+ prompts = {
498
+ "input_ids": inputs["prompt_input_ids"],
499
+ "attention_mask": inputs["prompt_attention_mask"],
500
+ "raw": prompts,
501
+ }
502
+ del inputs
503
+
504
+ # Sample completions from both the model and the reference model
505
+ model_output, mixture_output = self._generate_completions(model, prompts)
506
+
507
+ # Process model completions
508
+ model_data, mixture_data = self._process_completions(model_output, mixture_output, prompts)
509
+
510
+ # Compute rewards
511
+ if self.reward_funcs is not None:
512
+ model_scores, mixture_scores = self._compute_rewards(model_data, mixture_data, context_length)
513
+ # probability of the model data vs the mixture data
514
+ probability = F.sigmoid(model_scores - mixture_scores)
515
+ else:
516
+ model_scores, mixture_scores = None, None
517
+ probability = self._compute_judge(model_data, mixture_data, context_length)
518
+
519
+ # Compute logprobs
520
+ model_logprobs_model_data, ref_logprobs_model_data = self._compute_logprobs(model, model_data, context_length)
521
+
522
+ # Compute loss
523
+ loss, score, kl_div = self._compute_losses(model_logprobs_model_data, ref_logprobs_model_data, probability)
524
+
525
+ # Log everything
526
+ self._log_statistics(
527
+ model_data,
528
+ mixture_data,
529
+ model_logprobs_model_data.detach(),
530
+ ref_logprobs_model_data,
531
+ probability,
532
+ score.detach(),
533
+ kl_div.detach(),
534
+ context_length,
535
+ model_scores,
536
+ mixture_scores,
537
+ )
538
+
539
+ if (
540
+ self.args.torch_empty_cache_steps is not None
541
+ and self.state.global_step % self.args.torch_empty_cache_steps == 0
542
+ ):
543
+ empty_cache()
544
+
545
+ kwargs = {}
546
+ # For LOMO optimizers you need to explicitly use the learning rate
547
+ if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]:
548
+ kwargs["learning_rate"] = self._get_learning_rate()
549
+
550
+ if self.args.n_gpu > 1:
551
+ loss = loss.mean() # mean() to average on multi-gpu parallel training
552
+
553
+ self.accelerator.backward(loss, **kwargs)
554
+
555
+ return loss.detach() / self.args.gradient_accumulation_steps
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/online_dpo/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .online_dpo_config import OnlineDPOConfig
16
+ from .online_dpo_trainer import OnlineDPOTrainer
17
+
18
+
19
+ __all__ = ["OnlineDPOConfig", "OnlineDPOTrainer"]
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/online_dpo/online_dpo_config.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 warnings
16
+ from dataclasses import dataclass, field
17
+ from typing import Any
18
+
19
+ from ...trainer.base_config import _BaseConfig
20
+
21
+
22
+ @dataclass
23
+ class OnlineDPOConfig(_BaseConfig):
24
+ # docstyle-ignore
25
+ r"""
26
+ Configuration class for the [`experimental.online_dpo.OnlineDPOTrainer`].
27
+
28
+ This class includes only the parameters that are specific to Online DPO training. For a full list of training
29
+ arguments, please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this
30
+ class may differ from those in [`~transformers.TrainingArguments`].
31
+
32
+ Using [`~transformers.HfArgumentParser`] we can turn this class into
33
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
34
+ command line.
35
+
36
+ Parameters:
37
+ reward_model_path (`str`, *optional*):
38
+ Path to the reward model. Either `judge` or `reward_model_path` must be set, but not both.
39
+ judge (`str`, *optional*):
40
+ Name of the judge to use. Either `judge` or `reward_model_path` must be set, but not both.
41
+ max_new_tokens (`int`, *optional*, defaults to `64`):
42
+ Maximum number of tokens to generate per completion.
43
+ max_length (`int`, *optional*, defaults to `256`):
44
+ Maximum total length of the sequence (prompt + completion) used to compute log probabilities. If the
45
+ sequence exceeds this limit, the leftmost tokens will be truncated to preserve as much of the completion as
46
+ possible.
47
+ temperature (`float`, *optional*, defaults to `0.9`):
48
+ Temperature for sampling. The higher the temperature, the more random the completions.
49
+ missing_eos_penalty (`float`, *optional*):
50
+ Penalty applied to the score when the model fails to generate an EOS token. This is useful to encourage to
51
+ generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be a positive
52
+ value. This parameter only works when using `reward_funcs` and not when using `judge`.
53
+ beta (`float` or `list[float]`, *optional*, defaults to `0.1`):
54
+ Parameter controlling the deviation from the reference model. Higher β means less deviation from the
55
+ reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in
56
+ the [paper](https://huggingface.co/papers/2310.12036). If a list of floats is provided then the β is
57
+ selected for each new epoch and the last β is used for the rest of the epochs.
58
+ loss_type (`str`, *optional*, defaults to `"sigmoid"`):
59
+ Type of loss to use. Possible values are:
60
+
61
+ - `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper.
62
+ - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper.
63
+ disable_dropout (`bool`, *optional*, defaults to `True`):
64
+ Whether to disable dropout in the model and reference model.
65
+
66
+ > Parameters that control generation
67
+
68
+ top_p (`float`, *optional*, defaults to `1.0`):
69
+ Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to
70
+ `1.0` to consider all tokens.
71
+ top_k (`int`, *optional*, defaults to `0`):
72
+ Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is
73
+ disabled and all tokens are considered.
74
+ min_p (`float`, *optional*):
75
+ Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
76
+ value between `0.0` and `1.0`. Typical values are in the `0.01-0.2` range.
77
+ repetition_penalty (`float`, *optional*, defaults to `1.0`):
78
+ Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far.
79
+ Values > `1.0` encourage the model to use new tokens, while values < `1.0` encourage the model to repeat
80
+ tokens.
81
+ use_transformers_paged (`bool`, *optional*, defaults to `False`):
82
+ Whether to use the `transformers` paged implementation for generation. If set to `True`, the `transformers`
83
+ paged implementation will be used for generation instead of the default padded implementation. This
84
+ parameter is only effective when `use_vllm` is set to `False`.
85
+ cache_implementation (`str`, *optional*):
86
+ Implementation of the cache method for faster generation when `use_vllm` is set to `False`.
87
+ generation_kwargs (`dict[str, Any]`, *optional*):
88
+ Additional keyword arguments to pass to [`~transformers.GenerationConfig`] (if using transformers) or
89
+ `SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the
90
+ generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict
91
+ with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them.
92
+
93
+ > Parameters that control generation acceleration powered by vLLM
94
+
95
+ use_vllm (`bool`, *optional*, defaults to `False`):
96
+ Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation
97
+ instead of the default model.generate(). Requires `vllm` to be installed.
98
+ vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
99
+ Model implementation to use for vLLM. Must be one of `"transformers"` or `"vllm"`. `"transformers"`: Use
100
+ the `transformers` backend for model implementation. `"vllm"`: Use the `vllm` library for model
101
+ implementation.
102
+ vllm_mode (`str`, *optional*, defaults to `"colocate"`):
103
+ Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `"server"` or
104
+ `"colocate"`.
105
+
106
+ - `"server"`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM
107
+ server is running (start with `trl vllm-serve`).
108
+ - `"colocate"`: vLLM will run in the same process and share the training GPUs. This avoids the need for a
109
+ separate server but may cause resource contention with training.
110
+ vllm_structured_outputs_regex (`str`, *optional*):
111
+ Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled.
112
+
113
+ > Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`)
114
+
115
+ vllm_server_base_url (`str`, *optional*):
116
+ Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `vllm_server_host` and
117
+ `vllm_server_port` are ignored.
118
+ vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
119
+ Host of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
120
+ vllm_server_port (`int`, *optional*, defaults to `8000`):
121
+ Port of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
122
+ vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
123
+ Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the
124
+ timeout, a `ConnectionError` is raised.
125
+ vllm_group_port (`int`, *optional*, defaults to `51216`):
126
+ Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port
127
+ is occupied, there is no need to change it.
128
+
129
+ > Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`)
130
+
131
+ vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.55`):
132
+ Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to
133
+ `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
134
+ launching the vLLM server via the `--vllm_gpu_memory_utilization` flag.
135
+ vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
136
+ Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to
137
+ `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
138
+ launching the vLLM server via the `--vllm_tensor_parallel_size` flag.
139
+ vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`):
140
+ Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but
141
+ waking the engine adds host–device transfer latency.
142
+
143
+ > Other parameters
144
+
145
+ ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
146
+ This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation,
147
+ improving generation speed. However, disabling this option allows training models that exceed the VRAM
148
+ capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible
149
+ with vLLM generation.
150
+ model_init_kwargs (`dict[str, Any]`, *optional*):
151
+ Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a
152
+ string.
153
+
154
+ > [!NOTE]
155
+ > These parameters have default values different from [`~transformers.TrainingArguments`]:
156
+ > - `logging_steps`: Defaults to `10` instead of `500`.
157
+ > - `gradient_checkpointing`: Defaults to `True` instead of `False`.
158
+ > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
159
+ > - `learning_rate`: Defaults to `5e-7` instead of `5e-5`.
160
+ > - `remove_unused_columns`: Defaults to `False` instead of `True`.
161
+ """
162
+
163
+ _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
164
+
165
+ # Parameters whose default values are overridden from TrainingArguments
166
+ learning_rate: float = field(
167
+ default=5e-7,
168
+ metadata={"help": "The initial learning rate for AdamW."},
169
+ )
170
+ remove_unused_columns: bool = field(
171
+ default=False,
172
+ metadata={"help": "Whether or not to automatically remove the columns unused by the model forward method."},
173
+ )
174
+
175
+ reward_model_path: str | None = field(
176
+ default=None,
177
+ metadata={
178
+ "help": "Path to the reward model. Either `judge` or `reward_model_path` must be set, but not both."
179
+ },
180
+ )
181
+ judge: str | None = field(
182
+ default=None,
183
+ metadata={
184
+ "help": "Name of the judge to use. Either `judge` or `reward_model_path` must be set, but not both."
185
+ },
186
+ )
187
+ max_new_tokens: int = field(
188
+ default=64,
189
+ metadata={"help": "Maximum number of tokens to generate per completion."},
190
+ )
191
+ max_length: int = field(
192
+ default=512,
193
+ metadata={
194
+ "help": "Maximum total length of the sequence (prompt + completion) used to compute log probabilities. If "
195
+ "the sequence exceeds this limit, the leftmost tokens will be truncated to preserve as much of the "
196
+ "completion as possible."
197
+ },
198
+ )
199
+ temperature: float = field(
200
+ default=0.9,
201
+ metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."},
202
+ )
203
+ top_p: float = field(
204
+ default=1.0,
205
+ metadata={
206
+ "help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. "
207
+ "Set to 1.0 to consider all tokens."
208
+ },
209
+ )
210
+ top_k: int = field(
211
+ default=0,
212
+ metadata={
213
+ "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, "
214
+ "top-k-filtering is disabled and all tokens are considered."
215
+ },
216
+ )
217
+ min_p: float | None = field(
218
+ default=None,
219
+ metadata={
220
+ "help": "Minimum token probability, which will be scaled by the probability of the most likely token. It "
221
+ "must be a value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range."
222
+ },
223
+ )
224
+ repetition_penalty: float = field(
225
+ default=1.0,
226
+ metadata={
227
+ "help": "Float that penalizes new tokens based on whether they appear in the prompt and the generated "
228
+ "text so far. Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model "
229
+ "to repeat tokens."
230
+ },
231
+ )
232
+ generation_kwargs: dict | None = field(
233
+ default=None,
234
+ metadata={
235
+ "help": "Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or "
236
+ "`SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the "
237
+ "generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that "
238
+ "conflict with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them."
239
+ },
240
+ )
241
+ use_transformers_paged: bool = field(
242
+ default=False,
243
+ metadata={
244
+ "help": "Whether to use the `transformers` paged implementation for generation. If set to `True`, the "
245
+ "`transformers` paged implementation will be used for generation instead of the default padded "
246
+ "implementation. This parameter is only effective when `use_vllm` is set to `False`."
247
+ },
248
+ )
249
+ cache_implementation: str | None = field(
250
+ default=None,
251
+ metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."},
252
+ )
253
+ missing_eos_penalty: float | None = field(
254
+ default=None,
255
+ metadata={
256
+ "help": "Penalty applied to the score when the model fails to generate an EOS token. This is useful to "
257
+ "encourage to generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be "
258
+ "a positive value."
259
+ },
260
+ )
261
+ beta: list[float] = field(
262
+ default_factory=lambda: [0.1],
263
+ metadata={
264
+ "help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from "
265
+ "the reference model. For the IPO loss (`loss_type='ipo'`), β is the regularization parameter denoted by "
266
+ "τ in the [paper](https://huggingface.co/papers/2310.12036). If a list of floats is provided then the β "
267
+ "is selected for each new epoch and the last β is used for the rest of the epochs."
268
+ },
269
+ )
270
+ loss_type: str = field(
271
+ default="sigmoid",
272
+ metadata={
273
+ "help": "Type of loss to use.",
274
+ "choices": ["sigmoid", "ipo"],
275
+ },
276
+ )
277
+ disable_dropout: bool = field(
278
+ default=True,
279
+ metadata={"help": "Whether to disable dropout in the model."},
280
+ )
281
+ use_vllm: bool = field(
282
+ default=False,
283
+ metadata={
284
+ "help": "Whether to use vLLM for generating completions. Requires vLLM to be installed "
285
+ "(`pip install trl[vllm]`)."
286
+ },
287
+ )
288
+ vllm_model_impl: str = field(
289
+ default="vllm",
290
+ metadata={
291
+ "help": "Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: "
292
+ "Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for "
293
+ "model implementation."
294
+ },
295
+ )
296
+ vllm_structured_outputs_regex: str | None = field(
297
+ default=None,
298
+ metadata={"help": "Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled."},
299
+ )
300
+ vllm_gpu_memory_utilization: float | None = field(
301
+ default=0.55,
302
+ metadata={
303
+ "help": "Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set "
304
+ "to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when "
305
+ "launching the vLLM server via the `--vllm_gpu_memory_utilization` flag.",
306
+ },
307
+ )
308
+ vllm_mode: str = field(
309
+ default="colocate",
310
+ metadata={
311
+ "help": "Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or "
312
+ "`'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure "
313
+ "a TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same "
314
+ "process and share the training GPUs. This avoids the need for a separate server but may cause resource "
315
+ "contention with training.",
316
+ },
317
+ )
318
+ vllm_server_base_url: str | None = field(
319
+ default=None,
320
+ metadata={
321
+ "help": "Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` "
322
+ "and `vllm_server_port` are ignored.",
323
+ },
324
+ )
325
+ vllm_server_host: str = field(
326
+ default="0.0.0.0",
327
+ metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."},
328
+ )
329
+ vllm_server_port: int = field(
330
+ default=8000,
331
+ metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."},
332
+ )
333
+ vllm_server_timeout: float = field(
334
+ default=240.0,
335
+ metadata={
336
+ "help": "Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up "
337
+ "after the timeout, a `ConnectionError` is raised.",
338
+ },
339
+ )
340
+ vllm_group_port: int = field(
341
+ default=51216,
342
+ metadata={
343
+ "help": "Port number for the weight update group. This is used to communicate with the vLLM server. "
344
+ "Unless the port is occupied, there is no need to change it.",
345
+ },
346
+ )
347
+ vllm_tensor_parallel_size: int = field(
348
+ default=1,
349
+ metadata={
350
+ "help": "Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set "
351
+ "to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when "
352
+ "launching the vLLM server via the `--vllm_tensor_parallel_size` flag.",
353
+ },
354
+ )
355
+ vllm_enable_sleep_mode: bool = field(
356
+ default=False,
357
+ metadata={
358
+ "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory "
359
+ "usage low, but waking the engine adds host–device transfer latency."
360
+ },
361
+ )
362
+ ds3_gather_for_generation: bool = field(
363
+ default=True,
364
+ metadata={
365
+ "help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for "
366
+ "generation, improving generation speed. However, disabling this option allows training models that "
367
+ "exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option "
368
+ "is not compatible with vLLM generation."
369
+ },
370
+ )
371
+ model_init_kwargs: dict[str, Any] | str | None = field(
372
+ default=None,
373
+ metadata={
374
+ "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model "
375
+ "from a string."
376
+ },
377
+ )
378
+ reward_weights: list[float] | None = field(
379
+ default=None,
380
+ metadata={
381
+ "help": "Weights for combining multiple reward functions. Must match the number of reward functions. "
382
+ "If None, all reward functions are equally weighted."
383
+ },
384
+ )
385
+
386
+ def __post_init__(self):
387
+ super().__post_init__()
388
+
389
+ if hasattr(self.beta, "__len__") and len(self.beta) == 1:
390
+ self.beta = self.beta[0]
391
+
392
+ if self.max_new_tokens >= self.max_length:
393
+ warnings.warn(
394
+ f"The configuration has `max_new_tokens` ({self.max_new_tokens}) >= `max_length` ({self.max_length}). "
395
+ "This will cause prompts to be truncated or completely removed in the forward pass. "
396
+ "To preserve prompts, ensure e.g. `max_length > max_new_tokens + 512`. ",
397
+ stacklevel=3,
398
+ )
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/online_dpo/online_dpo_trainer.py ADDED
@@ -0,0 +1,1445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 re
17
+ import textwrap
18
+ from collections.abc import Callable
19
+ from contextlib import nullcontext
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ import jinja2
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ import torch.utils.data
28
+ import transformers
29
+ from accelerate import logging
30
+ from accelerate.utils import broadcast_object_list, gather_object, is_peft_model
31
+ from datasets import Dataset
32
+ from packaging.version import Version
33
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
34
+ from torch.utils.data import IterableDataset
35
+ from transformers import (
36
+ AutoModelForCausalLM,
37
+ AutoModelForSequenceClassification,
38
+ AutoTokenizer,
39
+ DataCollator,
40
+ GenerationConfig,
41
+ PreTrainedModel,
42
+ PreTrainedTokenizerBase,
43
+ ProcessorMixin,
44
+ TrainerCallback,
45
+ is_bitsandbytes_available,
46
+ )
47
+ from transformers.models.auto.modeling_auto import MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES
48
+ from transformers.trainer_utils import EvalPrediction
49
+ from transformers.training_args import OptimizerNames
50
+ from transformers.utils import is_flash_attn_2_available, is_peft_available, is_sagemaker_mp_enabled
51
+
52
+ from ...data_utils import apply_chat_template, is_conversational, maybe_apply_chat_template
53
+ from ...extras.profiling import profiling_context
54
+ from ...generation.vllm_client import VLLMClient
55
+ from ...import_utils import is_vllm_available
56
+ from ...models.utils import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation
57
+ from ...trainer.base_trainer import _BaseTrainer
58
+ from ...trainer.utils import disable_dropout_in_model, ensure_master_addr_port, get_config_model_id, pad
59
+ from ..judges import BasePairwiseJudge
60
+ from ..utils import (
61
+ SIMPLE_CHAT_TEMPLATE,
62
+ DPODataCollatorWithPadding,
63
+ create_reference_model,
64
+ empty_cache,
65
+ prepare_peft_model,
66
+ truncate_right,
67
+ )
68
+ from .online_dpo_config import OnlineDPOConfig
69
+
70
+
71
+ if is_peft_available():
72
+ from peft import PeftConfig, PeftModel
73
+
74
+
75
+ if is_sagemaker_mp_enabled():
76
+ from smdistributed.modelparallel import __version__ as SMP_VERSION
77
+
78
+ IS_SAGEMAKER_MP_POST_1_10 = Version(SMP_VERSION) >= Version("1.10")
79
+
80
+ else:
81
+ IS_SAGEMAKER_MP_POST_1_10 = False
82
+
83
+
84
+ if Version(transformers.__version__) >= Version("5.2.0"):
85
+ from transformers.trainer_pt_utils import nested_gather
86
+
87
+
88
+ if is_vllm_available():
89
+ from vllm import LLM, SamplingParams
90
+ from vllm.sampling_params import StructuredOutputsParams
91
+
92
+ if is_bitsandbytes_available():
93
+ import bitsandbytes as bnb
94
+
95
+ logger = logging.get_logger(__name__)
96
+
97
+ # A reward function can be a string, interpreted as a model ID and loaded as a pretrained model, a pretrained model, or
98
+ # a callable that returns a list of floats (the rewards). The callable receives prompts, completions, and additional
99
+ # arguments from the trainer (refer to the trainer's source for details). To ensure forward compatibility, it should
100
+ # accept **kwargs.
101
+ RewardFunc = str | PreTrainedModel | Callable[..., list[float | None]]
102
+
103
+
104
+ class OnlineDPOTrainer(_BaseTrainer):
105
+ r"""
106
+ Initialize OnlineDPOTrainer.
107
+
108
+ Args:
109
+ model (`str | nn.Module | PreTrainedModel`):
110
+ Model to be trained. Can be either:
111
+
112
+ - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
113
+ path to a *directory* containing model weights saved using
114
+ [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
115
+ using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in
116
+ `args.model_init_kwargs`.
117
+ - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
118
+ ref_model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `None`):
119
+ The reference model to use for training. If None is specified, the reference model will be created from the
120
+ model.
121
+ judge ([`experimental.judges.BasePairwiseJudge`]):
122
+ The judge to use for pairwise comparison of model completions.
123
+ reward_funcs (`RewardFunc | list[RewardFunc]`, *optional*):
124
+ Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
125
+ functions with the prompts and completions and sum the rewards. Can be either:
126
+
127
+ - A single reward function: Can be a string (path to model), a [`~transformers.PreTrainedModel`], or a
128
+ custom callable function.
129
+ - A list of reward functions: Must all be of compatible types.
130
+
131
+ Note: Only one of `judge`, or `reward_funcs` should be provided.
132
+ args ([`experimental.online_dpo.OnlineDPOConfig`]):
133
+ The online DPO config arguments to use for training.
134
+ data_collator ([`~transformers.DataCollator`]):
135
+ The data collator to use for training. If None is specified, the default data collator
136
+ ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the
137
+ maximum length of the sequences in the batch, given a dataset of paired sequences.
138
+ train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
139
+ The dataset to use for training.
140
+ eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
141
+ The dataset to use for evaluation.
142
+ processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`], *optional*):
143
+ Processing class used to process the data. If provided, will be used to automatically process the inputs
144
+ for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
145
+ reuse the fine-tuned model.
146
+ reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*):
147
+ Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:
148
+
149
+ - A single processing class: Used when `reward_funcs` contains only one reward function.
150
+ - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
151
+
152
+ If set to `None`, the tokenizer for each model-based reward function is automatically loaded using
153
+ [`~transformers.AutoTokenizer.from_pretrained`].
154
+ peft_config ([`~peft.PeftConfig`], *optional*):
155
+ PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
156
+ compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
157
+ The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
158
+ metric values.
159
+ callbacks (`list[transformers.TrainerCallback]`):
160
+ The callbacks to use for training.
161
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
162
+ The optimizer and scheduler to use for training.
163
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
164
+ The function to use to preprocess the logits before computing the metrics.
165
+ """
166
+
167
+ _tag_names = ["trl", "online-dpo"]
168
+ _name = "Online DPO"
169
+ _paper = {
170
+ "title": "Direct Language Model Alignment from Online AI Feedback",
171
+ "id": "2402.04792",
172
+ # docstyle-ignore
173
+ "citation": textwrap.dedent("""\
174
+ @article{guo2024direct,
175
+ title = {{Direct Language Model Alignment from Online AI Feedback}},
176
+ author = {Shangmin Guo and Biao Zhang and Tianlin Liu and Tianqi Liu and Misha Khalman and Felipe Llinares and Alexandre Ram{\'{e}} and Thomas Mesnard and Yao Zhao and Bilal Piot and Johan Ferret and Mathieu Blondel},
177
+ year = 2024,
178
+ eprint = {arXiv:2402.04792}
179
+ }"""),
180
+ }
181
+
182
+ def __init__(
183
+ self,
184
+ model: PreTrainedModel | nn.Module | str,
185
+ ref_model: PreTrainedModel | nn.Module | None = None,
186
+ reward_funcs: RewardFunc | list[RewardFunc] | None = None,
187
+ judge: BasePairwiseJudge | None = None,
188
+ args: OnlineDPOConfig | None = None,
189
+ data_collator: DataCollator | None = None,
190
+ train_dataset: Dataset | IterableDataset | None = None,
191
+ eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
192
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
193
+ reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None,
194
+ peft_config: "PeftConfig | None" = None,
195
+ compute_metrics: Callable[[EvalPrediction], dict] | None = None,
196
+ callbacks: list[TrainerCallback] | None = None,
197
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
198
+ preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
199
+ ) -> None:
200
+ if train_dataset is None:
201
+ raise ValueError("`train_dataset` is required")
202
+
203
+ if ref_model is model:
204
+ raise ValueError(
205
+ "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the "
206
+ "same as `model`, either omit the `ref_model` argument or pass `None`."
207
+ )
208
+
209
+ self.ref_model = ref_model
210
+
211
+ # Validate reward configuration - must have exactly one of: judge, or reward_funcs
212
+ reward_configs = sum(x is not None for x in [judge, reward_funcs])
213
+ if reward_configs == 0:
214
+ raise ValueError("One of `judge` or `reward_funcs` must be provided.")
215
+ elif reward_configs > 1:
216
+ if judge is not None:
217
+ logger.warning(
218
+ "Both `judge` and `reward_funcs` are provided. Using `judge` and ignoring `reward_funcs`.",
219
+ UserWarning,
220
+ )
221
+ reward_funcs = None
222
+ self.judge = judge
223
+
224
+ # Handle reward_funcs
225
+ if reward_funcs is not None:
226
+ if not isinstance(reward_funcs, list):
227
+ reward_funcs = [reward_funcs]
228
+ self.reward_func_names = []
229
+
230
+ # Process reward functions (convert strings to models, collect names)
231
+ model_init_kwargs = args.model_init_kwargs or {}
232
+ for i, reward_func in enumerate(reward_funcs):
233
+ if isinstance(reward_func, str):
234
+ # Load model from string path
235
+ reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained(
236
+ reward_func, num_labels=1, **model_init_kwargs
237
+ )
238
+ if isinstance(reward_funcs[i], nn.Module):
239
+ self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1])
240
+ else:
241
+ self.reward_func_names.append(reward_funcs[i].__name__)
242
+ self.reward_funcs = reward_funcs
243
+
244
+ # Handle reward processing classes for reward_funcs
245
+ if reward_processing_classes is None:
246
+ reward_processing_classes = [None] * len(reward_funcs)
247
+ elif not isinstance(reward_processing_classes, list):
248
+ reward_processing_classes = [reward_processing_classes]
249
+ else:
250
+ if len(reward_processing_classes) != len(reward_funcs):
251
+ raise ValueError(
252
+ "The number of reward processing classes must match the number of reward functions."
253
+ )
254
+
255
+ self.reward_processing_classes = []
256
+ for reward_processing_class_i, reward_func in zip(reward_processing_classes, reward_funcs, strict=True):
257
+ if isinstance(reward_func, PreTrainedModel):
258
+ if reward_processing_class_i is None:
259
+ reward_processing_class_i = AutoTokenizer.from_pretrained(reward_func.config._name_or_path)
260
+ if reward_processing_class_i.pad_token_id is None:
261
+ reward_processing_class_i.pad_token = reward_processing_class_i.eos_token
262
+ # Set pad token ID on reward model config
263
+ reward_func.config.pad_token_id = reward_processing_class_i.pad_token_id
264
+ self.reward_processing_classes.append(reward_processing_class_i)
265
+ else:
266
+ self.reward_funcs = None
267
+ self.reward_func_names = []
268
+ self.reward_processing_classes = []
269
+
270
+ # Handle reward_weights
271
+ if reward_funcs is not None:
272
+ if args.reward_weights is not None:
273
+ if len(args.reward_weights) != len(self.reward_funcs):
274
+ raise ValueError(
275
+ f"Number of reward weights ({len(args.reward_weights)}) must match number of reward "
276
+ f"functions ({len(self.reward_funcs)})"
277
+ )
278
+ self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32)
279
+ else:
280
+ self.reward_weights = torch.ones(len(self.reward_funcs), dtype=torch.float32)
281
+ else:
282
+ self.reward_weights = None
283
+
284
+ if args.missing_eos_penalty is not None and reward_funcs is None and judge is None:
285
+ raise ValueError("`missing_eos_penalty` is only supported when `reward_funcs` is provided.")
286
+
287
+ if args is None:
288
+ raise ValueError("`args` must be provided.")
289
+
290
+ # Check that the processing_class is provided
291
+ if processing_class is None:
292
+ raise ValueError("`processing_class` must be provided.")
293
+
294
+ model_init_kwargs = args.model_init_kwargs or {}
295
+ if isinstance(model, str):
296
+ model_id = model
297
+
298
+ # Handle dtype in model_init_kwargs
299
+ dtype = model_init_kwargs.get("dtype", "auto")
300
+ if isinstance(dtype, torch.dtype) or dtype == "auto" or dtype is None:
301
+ pass
302
+ elif isinstance(dtype, str):
303
+ dtype = getattr(torch, dtype)
304
+ model_init_kwargs["dtype"] = dtype
305
+ else:
306
+ raise ValueError(
307
+ "Invalid `dtype` passed to `OnlineDPOConfig`. Expected either 'auto' or a string "
308
+ f"representing a `torch.dtype` (e.g., 'float32'), but got {dtype}."
309
+ )
310
+ model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto")
311
+
312
+ model = AutoModelForCausalLM.from_pretrained(model_id, **model_init_kwargs)
313
+ else:
314
+ if args.model_init_kwargs is not None:
315
+ raise ValueError(
316
+ "You passed `model_init_kwargs` to the `OnlineDPOConfig`, but your model is already instantiated. "
317
+ "This argument can only be used when the `model` argument is a string."
318
+ )
319
+ self.is_encoder_decoder = model.config.is_encoder_decoder
320
+ self.is_vision_model = model.config.model_type in MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES.keys()
321
+
322
+ if peft_config is not None or (is_peft_available() and isinstance(model, PeftModel)):
323
+ model = prepare_peft_model(model, peft_config, args)
324
+
325
+ # Enable gradient checkpointing if requested
326
+ if args.gradient_checkpointing:
327
+ model = self._enable_gradient_checkpointing(model, args)
328
+
329
+ # Disable dropout in the model and reference model
330
+ if args.disable_dropout:
331
+ disable_dropout_in_model(model)
332
+ if self.ref_model is not None:
333
+ disable_dropout_in_model(self.ref_model)
334
+
335
+ # Handle the ref_model
336
+ # Usually, the user wants the ref model to be the initial version of the model. When using PEFT, it's easy to
337
+ # get the ref model, as it's just the model with a disabled adapter. When not using PEFT, we need to create
338
+ # the ref model from the model by copying it and disable the gradients and set it in evaluation mode.
339
+ if ref_model is None: # No ref model provided, the most common case
340
+ if peft_config is None:
341
+ self.ref_model = create_reference_model(model) # copy, disable gradients, set eval mode
342
+ else:
343
+ self.ref_model = None # we don't need a ref model here, we can just disable the adapter.
344
+ else: # rare case, the user provided a ref model
345
+ self.ref_model = ref_model
346
+ self.ref_model.eval()
347
+
348
+ # Disable the gradient and set the reward model in eval mode
349
+ if reward_funcs is not None:
350
+ for reward_func in reward_funcs:
351
+ if isinstance(reward_func, PreTrainedModel):
352
+ reward_func.eval()
353
+
354
+ self.max_length = args.max_length
355
+
356
+ self.stats = {
357
+ "objective/kl": [],
358
+ "objective/entropy": [],
359
+ "objective/non_score_reward": [],
360
+ "rewards/chosen": [],
361
+ "rewards/rejected": [],
362
+ "rewards/accuracies": [],
363
+ "rewards/margins": [],
364
+ "logps/chosen": [],
365
+ "logps/rejected": [],
366
+ "val/contain_eos_token": [],
367
+ "beta": [],
368
+ }
369
+ if self.reward_funcs is not None:
370
+ self.stats["objective/rlhf_reward"] = []
371
+ self.stats["objective/scores_margin"] = []
372
+ self.stats["objective/scores"] = []
373
+
374
+ # Store generation parameters for later use
375
+ self.use_vllm = args.use_vllm
376
+ self.num_generations = 2 # Generate 2 completions per prompt for Online DPO
377
+ self.temperature = args.temperature
378
+ self.top_p = args.top_p
379
+ self.top_k = args.top_k
380
+ self.min_p = args.min_p
381
+ self.repetition_penalty = args.repetition_penalty
382
+ self.use_transformers_paged = args.use_transformers_paged
383
+ self.vllm_mode = args.vllm_mode if args.use_vllm else None
384
+ self.vllm_gpu_memory_utilization = args.vllm_gpu_memory_utilization
385
+ self.vllm_tensor_parallel_size = args.vllm_tensor_parallel_size
386
+ self.vllm_model_impl = args.vllm_model_impl
387
+
388
+ # Handle pad token for processors or tokenizers
389
+ if isinstance(processing_class, ProcessorMixin):
390
+ tokenizer = processing_class.tokenizer
391
+ elif isinstance(processing_class, PreTrainedTokenizerBase):
392
+ tokenizer = processing_class
393
+ else:
394
+ raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
395
+
396
+ if tokenizer.pad_token is None:
397
+ tokenizer.pad_token = tokenizer.eos_token
398
+
399
+ self.pad_token = tokenizer.pad_token
400
+ self.pad_token_id = tokenizer.pad_token_id
401
+ self.eos_token_id = tokenizer.eos_token_id
402
+
403
+ # Vision tokens for VLM support
404
+ self.image_token_id = getattr(processing_class, "image_token_id", None)
405
+ self.vision_start_token_id = getattr(processing_class, "vision_start_token_id", None)
406
+ self.vision_end_token_id = getattr(processing_class, "vision_end_token_id", None)
407
+ # Get the image token string for token collapsing
408
+ self.image_token = None
409
+ if self.image_token_id is not None:
410
+ self.image_token = tokenizer.decode([self.image_token_id])
411
+
412
+ # Define the collator if not provided
413
+ if data_collator is None:
414
+ data_collator = DPODataCollatorWithPadding(pad_token_id=self.pad_token_id)
415
+
416
+ # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
417
+ # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
418
+ # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
419
+ # default to the recommended non-reentrant behavior here, while preserving any user-provided value.
420
+ if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
421
+ args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
422
+ args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
423
+
424
+ super().__init__(
425
+ model=model,
426
+ args=args,
427
+ data_collator=data_collator,
428
+ train_dataset=train_dataset,
429
+ eval_dataset=eval_dataset,
430
+ processing_class=processing_class,
431
+ compute_metrics=compute_metrics,
432
+ callbacks=callbacks,
433
+ optimizers=optimizers,
434
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
435
+ )
436
+
437
+ # Add tags for models that have been loaded with the correct transformers version
438
+ if hasattr(self.model, "add_model_tags"):
439
+ self.model.add_model_tags(self._tag_names)
440
+
441
+ self._beta = args.beta
442
+
443
+ # Set up generation configuration and vLLM after super().__init__
444
+ if self.use_vllm:
445
+ if not is_vllm_available():
446
+ raise ImportError(
447
+ "vLLM is not available and `use_vllm` is set to True. Please install vLLM with "
448
+ "`pip install trl[vllm]` to use it."
449
+ )
450
+
451
+ if self.vllm_mode == "server":
452
+ if self.accelerator.is_main_process:
453
+ if args.vllm_server_base_url is not None:
454
+ base_url = args.vllm_server_base_url
455
+ else:
456
+ base_url = f"http://{args.vllm_server_host}:{args.vllm_server_port}"
457
+ self.vllm_client = VLLMClient(
458
+ base_url=base_url, group_port=args.vllm_group_port, connection_timeout=args.vllm_server_timeout
459
+ )
460
+
461
+ # Determine device type (supports cuda, xpu, etc.)
462
+ accelerator_type = torch.accelerator.current_accelerator().type
463
+ current_device = getattr(torch, accelerator_type).current_device()
464
+ self.vllm_client.init_communicator(device=current_device)
465
+ else:
466
+ self.vllm_client = None
467
+ elif self.vllm_mode == "colocate":
468
+ # vLLM dynamically adjusts the size of the key-value cache based on available GPU memory at instantiation.
469
+ # A larger cache size improves speed, so we would expect gpu_memory_utilization=1.
470
+ # However, at this stage, the optimizer's weights are not yet loaded onto the GPU; they will be loaded
471
+ # after the first optimizer step and remain in GPU memory throughout training. So we must reserve enough
472
+ # space for them.
473
+ # Configure vLLM parameters
474
+ vllm_quantization = None
475
+ if is_bitsandbytes_available():
476
+ for _, module in model.named_modules():
477
+ if isinstance(module, bnb.nn.Linear4bit):
478
+ vllm_quantization = "bitsandbytes"
479
+ break
480
+ elif isinstance(module, bnb.nn.Linear8bitLt):
481
+ raise ValueError("vLLM does not support in-flight 8-bit quantization.")
482
+ vllm_kwargs = {
483
+ "model": model.name_or_path,
484
+ "tensor_parallel_size": self.vllm_tensor_parallel_size,
485
+ "gpu_memory_utilization": self.vllm_gpu_memory_utilization,
486
+ "model_impl": self.vllm_model_impl,
487
+ "max_num_seqs": self.args.per_device_train_batch_size * self.vllm_tensor_parallel_size,
488
+ "max_model_len": args.max_length + args.max_new_tokens, # max_length includes prompt + completion
489
+ "distributed_executor_backend": "external_launcher",
490
+ # Feed identical seed for tp groups to ensure sampling results are the same across workers
491
+ "seed": self.accelerator.process_index // self.vllm_tensor_parallel_size,
492
+ # Latest vLLM v1 memory profiler is misled by the high default value (i.e., 32768)
493
+ "max_num_batched_tokens": 4096,
494
+ "enable_sleep_mode": self.args.vllm_enable_sleep_mode,
495
+ "quantization": vllm_quantization,
496
+ }
497
+
498
+ # vLLM requires the environment variables to be set for distributed training.
499
+ os.environ["RANK"] = str(self.accelerator.process_index)
500
+ os.environ["LOCAL_RANK"] = str(self.accelerator.local_process_index)
501
+ os.environ["WORLD_SIZE"] = str(self.accelerator.num_processes)
502
+ # Ensure distributed rendezvous variables are set without colliding across concurrent runs
503
+ ensure_master_addr_port()
504
+
505
+ self.llm = LLM(**vllm_kwargs)
506
+ if self.args.vllm_enable_sleep_mode:
507
+ self.llm.sleep(level=2)
508
+ else:
509
+ raise ValueError(f"vllm_mode must be either 'server' or 'colocate', got '{self.vllm_mode}'.")
510
+ # vLLM specific sampling arguments
511
+ self.structured_outputs_regex = args.vllm_structured_outputs_regex
512
+ self._last_loaded_step = -1 # tag to avoid useless loading during grad accumulation
513
+
514
+ # Set up vLLM generation config
515
+ generation_kwargs = {
516
+ "n": 2, # 2 generations per prompt for Online DPO
517
+ "repetition_penalty": self.repetition_penalty,
518
+ "temperature": self.temperature,
519
+ "top_p": self.top_p,
520
+ "top_k": self.top_k,
521
+ "min_p": 0.0 if self.min_p is None else self.min_p,
522
+ "max_tokens": args.max_new_tokens,
523
+ "detokenize": False, # to avoid vllm to decode (we don't need it)
524
+ }
525
+ if args.generation_kwargs is not None:
526
+ generation_kwargs.update(args.generation_kwargs)
527
+ if self.structured_outputs_regex is not None:
528
+ if generation_kwargs.get("structured_outputs") is not None:
529
+ logger.warning(
530
+ "Both `vllm_structured_outputs_regex` and `generation_kwargs['structured_outputs']` are set; "
531
+ "`vllm_structured_outputs_regex` takes precedence."
532
+ )
533
+ generation_kwargs["structured_outputs"] = StructuredOutputsParams(regex=self.structured_outputs_regex)
534
+ elif isinstance(structured_outputs_kwargs := generation_kwargs.get("structured_outputs"), dict):
535
+ generation_kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs_kwargs)
536
+ self.generation_config = SamplingParams(**generation_kwargs)
537
+
538
+ # When using vLLM, the main process is responsible for loading the model weights. This can cause process
539
+ # desynchronization and seems to lead to DeepSpeed hanging during initialization. To prevent this, we
540
+ # synchronize all processes after vLLM has been fully initialized.
541
+ self.accelerator.wait_for_everyone()
542
+ else:
543
+ # Set up transformers generation config
544
+ generation_kwargs = {
545
+ "max_new_tokens": args.max_new_tokens,
546
+ "do_sample": True,
547
+ "pad_token_id": self.pad_token_id,
548
+ "bos_token_id": tokenizer.bos_token_id,
549
+ "eos_token_id": self.eos_token_id,
550
+ "temperature": self.temperature,
551
+ "top_k": self.top_k,
552
+ "top_p": self.top_p,
553
+ "repetition_penalty": self.repetition_penalty,
554
+ "use_cache": True if not self.args.gradient_checkpointing else False,
555
+ }
556
+ # Add min_p if supported
557
+ if self.min_p is not None:
558
+ generation_kwargs["min_p"] = self.min_p
559
+ if args.generation_kwargs is not None:
560
+ generation_kwargs.update(args.generation_kwargs)
561
+ # Remove None values
562
+ generation_kwargs = {k: v for k, v in generation_kwargs.items() if v is not None}
563
+ self.generation_config = GenerationConfig(**generation_kwargs)
564
+ # Keep training-specific generation kwargs to overwrite model's original generation config
565
+ self.generation_kwargs = generation_kwargs
566
+
567
+ if self.ref_model is not None:
568
+ if self.is_deepspeed_enabled:
569
+ self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator)
570
+ elif self.is_fsdp_enabled:
571
+ self.ref_model = prepare_fsdp(self.ref_model, self.accelerator)
572
+ else:
573
+ self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
574
+ if self.reward_funcs is not None:
575
+ for i, reward_func in enumerate(self.reward_funcs):
576
+ if isinstance(reward_func, PreTrainedModel):
577
+ if self.is_deepspeed_enabled:
578
+ self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator)
579
+ else:
580
+ # set device placement to True to make `prepare_model` move `reward_func` to device when using fsdp
581
+ self.reward_funcs[i] = self.accelerator.prepare_model(
582
+ reward_func, evaluation_mode=True, device_placement=True
583
+ )
584
+
585
+ @property
586
+ def beta(self):
587
+ if isinstance(self._beta, list):
588
+ epoch = self.state.epoch
589
+ return self._beta[epoch] if epoch < len(self._beta) else self._beta[-1]
590
+ else:
591
+ return self._beta
592
+
593
+ @staticmethod
594
+ def tokenize_row(feature, is_encoder_decoder: bool, tokenizer: PreTrainedTokenizerBase) -> dict[str, Any]:
595
+ """Tokenize a single row from a DPO specific dataset."""
596
+ if not is_encoder_decoder:
597
+ batch = tokenizer(feature["prompt"], add_special_tokens=False)
598
+ # Add BOS token to head of prompt. Avoid adding if it's already there
599
+ if tokenizer.bos_token_id is not None:
600
+ prompt_len_input_ids = len(batch["input_ids"])
601
+ if prompt_len_input_ids == 0 or tokenizer.bos_token_id != batch["input_ids"][0]:
602
+ batch["input_ids"] = [tokenizer.bos_token_id] + batch["input_ids"]
603
+ batch["attention_mask"] = [1] + batch["attention_mask"]
604
+ else:
605
+ batch = tokenizer(feature["prompt"], add_special_tokens=True)
606
+ batch = {f"prompt_{key}": value for key, value in batch.items()}
607
+ return batch
608
+
609
+ def _enable_gradient_checkpointing(self, model: PreTrainedModel, args: OnlineDPOConfig) -> PreTrainedModel:
610
+ """Enables gradient checkpointing for the model."""
611
+ # Ensure use_cache is disabled
612
+ model.config.use_cache = False
613
+
614
+ # Enable gradient checkpointing on the base model for PEFT
615
+ if is_peft_model(model):
616
+ model.base_model.gradient_checkpointing_enable()
617
+ # Enable gradient checkpointing for non-PEFT models
618
+ else:
619
+ model.gradient_checkpointing_enable()
620
+
621
+ model.enable_input_require_grads()
622
+ return model
623
+
624
+ def _generate_vllm(self, prompts, images=None):
625
+ eos_token_id = self.eos_token_id
626
+ pad_token_id = self.pad_token_id
627
+
628
+ # Generate completion_ids and prompt_ids based on mode
629
+ if self.vllm_mode == "server":
630
+ completion_ids, prompt_ids = self._generate_vllm_server(prompts, images)
631
+ elif self.vllm_mode == "colocate":
632
+ completion_ids, prompt_ids = self._generate_vllm_colocate(prompts, images)
633
+
634
+ # Shared padding, masking, and tensor conversion logic
635
+ max_prompt_length = max(len(ids) for ids in prompt_ids)
636
+ prompt_mask = [[0] * (max_prompt_length - len(ids)) + [1] * len(ids) for ids in prompt_ids]
637
+ prompt_ids = [[pad_token_id] * (max_prompt_length - len(ids)) + ids for ids in prompt_ids]
638
+ max_tokens = self.generation_config.max_tokens
639
+ completion_mask = [[1] * len(ids) + [0] * (max_tokens - len(ids)) for ids in completion_ids]
640
+ completion_ids = [
641
+ ids + [eos_token_id] if ids[-1] != eos_token_id and len(ids) < max_tokens else ids
642
+ for ids in completion_ids
643
+ ]
644
+ completion_ids = [ids + [pad_token_id] * (max_tokens - len(ids)) for ids in completion_ids]
645
+
646
+ # Convert to tensors
647
+ prompt_ids = torch.tensor(prompt_ids, device=self.accelerator.device)
648
+ prompt_mask = torch.tensor(prompt_mask, device=self.accelerator.device)
649
+ completion_ids = torch.tensor(completion_ids, device=self.accelerator.device)
650
+ completion_mask = torch.tensor(completion_mask, device=self.accelerator.device)
651
+
652
+ return prompt_ids, prompt_mask, completion_ids, completion_mask
653
+
654
+ def _generate_vllm_server(self, prompts, images=None):
655
+ """Generate completions using vLLM server mode"""
656
+ has_images = images is not None
657
+
658
+ # Update vLLM server weights if needed
659
+ if hasattr(self, "_last_loaded_step") and self.state.global_step != self._last_loaded_step:
660
+ self._move_model_to_vllm()
661
+ self._last_loaded_step = self.state.global_step
662
+ elif not hasattr(self, "_last_loaded_step"):
663
+ self._move_model_to_vllm()
664
+ self._last_loaded_step = self.state.global_step
665
+
666
+ # Apply chat template if conversational
667
+ if is_conversational({"prompt": prompts[0]}):
668
+ prompts_text = [apply_chat_template({"prompt": p}, self.processing_class)["prompt"] for p in prompts]
669
+ else:
670
+ prompts_text = prompts
671
+ # Gather all prompts to main process
672
+ all_prompts = gather_object(prompts_text)
673
+ if has_images:
674
+ all_images = gather_object(images)
675
+
676
+ if self.accelerator.is_main_process:
677
+ # Since 'prompts' contains 'num_generations' duplicates, we first take unique prompts, and generate
678
+ # num_generations outputs for each one. This is faster than generating outputs for each duplicate
679
+ # prompt individually.
680
+ ordered_set_of_prompts = all_prompts[:: self.num_generations]
681
+ if has_images:
682
+ ordered_set_of_images = [
683
+ [img] if img is not None else None for img in all_images[:: self.num_generations]
684
+ ]
685
+ else:
686
+ ordered_set_of_images = None
687
+ completion_ids = self.vllm_client.generate(
688
+ prompts=ordered_set_of_prompts,
689
+ images=ordered_set_of_images,
690
+ n=self.num_generations,
691
+ repetition_penalty=self.repetition_penalty,
692
+ temperature=self.temperature,
693
+ top_p=self.top_p,
694
+ top_k=-1 if self.top_k is None else self.top_k,
695
+ min_p=0.0 if self.min_p is None else self.min_p,
696
+ max_tokens=self.generation_config.max_tokens,
697
+ structured_outputs_regex=self.structured_outputs_regex
698
+ if hasattr(self, "structured_outputs_regex")
699
+ else None,
700
+ generation_kwargs=self.args.generation_kwargs,
701
+ )["completion_ids"]
702
+ # Flatten: each prompt generates 2 completions
703
+ completion_ids = [[comp_id] for prompt_completions in completion_ids for comp_id in prompt_completions]
704
+ else:
705
+ completion_ids = [None] * (len(all_prompts) * 2)
706
+
707
+ # Broadcast completions to all processes
708
+ completion_ids = broadcast_object_list(completion_ids, from_process=0)
709
+
710
+ # Each process takes its slice
711
+ process_slice = slice(
712
+ self.accelerator.process_index * len(prompts) * 2,
713
+ (self.accelerator.process_index + 1) * len(prompts) * 2,
714
+ )
715
+ completion_ids = completion_ids[process_slice]
716
+
717
+ # Create prompt_ids by tokenizing locally
718
+ prompt_inputs = self.processing_class(
719
+ text=prompts_text,
720
+ return_tensors="pt",
721
+ padding=True,
722
+ padding_side="left",
723
+ add_special_tokens=False,
724
+ )
725
+ prompt_ids = []
726
+ for prompt_tokens in prompt_inputs["input_ids"]:
727
+ prompt_ids.extend([prompt_tokens.tolist(), prompt_tokens.tolist()]) # 2 copies for 2 completions
728
+ return completion_ids, prompt_ids
729
+
730
+ def _generate_vllm_colocate(self, prompts, images=None):
731
+ """Generate completions using vLLM colocate mode"""
732
+ if self.args.vllm_enable_sleep_mode:
733
+ # wake up colocated vLLM instances if needed
734
+ torch.cuda.empty_cache() # required to avoid OOM in some cases
735
+ self.llm.wake_up(tags=["weights"])
736
+
737
+ # Update model weights if needed - only after gradient accumulation completes
738
+ if self.state.global_step != self._last_loaded_step:
739
+ self._move_model_to_vllm()
740
+ self._last_loaded_step = self.state.global_step
741
+
742
+ # Apply chat template if conversational
743
+ if is_conversational({"prompt": prompts[0]}):
744
+ prompts_text = [apply_chat_template({"prompt": p}, self.processing_class)["prompt"] for p in prompts]
745
+ else:
746
+ prompts_text = prompts
747
+
748
+ # Prepare vLLM inputs with images if available
749
+ if images is not None:
750
+ vllm_inputs = []
751
+ for prompt, image in zip(prompts_text, images, strict=True):
752
+ if image is not None:
753
+ vllm_inputs.append({"prompt": prompt, "multi_modal_data": {"image": image}})
754
+ else:
755
+ vllm_inputs.append(prompt)
756
+ else:
757
+ vllm_inputs = prompts_text
758
+
759
+ if self.args.vllm_enable_sleep_mode:
760
+ self.llm.wake_up(tags=["kv_cache"])
761
+
762
+ outputs = self.llm.generate(vllm_inputs, self.generation_config, use_tqdm=False)
763
+
764
+ completion_ids = [list(output.outputs[i].token_ids) for i in range(2) for output in outputs]
765
+ prompt_ids = [list(output.prompt_token_ids) for _ in range(2) for output in outputs]
766
+ if self.args.vllm_enable_sleep_mode:
767
+ self.llm.sleep(level=2)
768
+
769
+ return completion_ids, prompt_ids
770
+
771
+ def _sync_fsdp2_params_to_vllm(self, module: nn.Module):
772
+ # For FSDP2, module.state_dict() already covers all parameters, so no need for recursion
773
+ for name, param in module.state_dict().items():
774
+ # When using PEFT, we need to recover the original parameter name
775
+ name = name.removeprefix("base_model.model.").replace(".base_layer", "")
776
+ # Skip PEFT layers: they don’t exist in vLLM, and they are merged already.
777
+ if is_peft_model(module) and module.prefix in name:
778
+ continue
779
+ # When module to save, remove its prefix and discard the original module
780
+ if "original_module" in name:
781
+ continue
782
+ name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."])
783
+
784
+ if param.is_cpu:
785
+ param = param.to(torch.device("cuda"))
786
+ param = param.full_tensor()
787
+
788
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
789
+ self.vllm_client.update_named_param(name, param)
790
+ elif self.vllm_mode == "colocate":
791
+ llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model
792
+ llm_model.load_weights([(name, param)])
793
+
794
+ def _move_model_to_vllm(self):
795
+ # For DeepSpeed ZeRO-3 and FSDP, we need to gather all parameters before operations
796
+ deepspeed_plugin = self.accelerator.state.deepspeed_plugin
797
+ zero_stage_3 = deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3
798
+ if zero_stage_3:
799
+ import deepspeed
800
+
801
+ gather_if_zero3 = deepspeed.zero.GatheredParameters
802
+ else:
803
+ gather_if_zero3 = nullcontext
804
+
805
+ if is_peft_model(self.model):
806
+ # With PEFT and FSDP/DeepSpeed ZeRO Stage 3, we must gather the full model at once before merging, as
807
+ # merging adapters in a sharded manner is not supported.
808
+ # TODO: does this work with FSDP?
809
+ with gather_if_zero3(list(self.model.parameters())):
810
+ self.model.merge_adapter()
811
+
812
+ # Update vLLM weights while parameters are gathered
813
+ if self.is_fsdp_enabled: # note if using FSDP, gather_if_zero3 is nullcontext
814
+ # Update vLLM weights while parameters are gathered
815
+ # For PEFT with FSDP we need to use the memory efficient post-order traversal
816
+ fsdp_plugin = getattr(self.accelerator.state, "fsdp_plugin", None)
817
+ fsdp_version = getattr(fsdp_plugin, "fsdp_version", 1) if fsdp_plugin else 1
818
+ if fsdp_version == 1:
819
+ self._sync_fsdp1_params_to_vllm(
820
+ self.model
821
+ ) # use memory-efficient post-order traversal for FSDP
822
+ elif fsdp_version == 2:
823
+ self._sync_fsdp2_params_to_vllm(self.model)
824
+ else:
825
+ # DeepSpeed ZeRO-3 with PEFT
826
+ for name, param in self.model.named_parameters():
827
+ # When using PEFT, we need to recover the original parameter name
828
+ name = name.removeprefix("base_model.model.").replace(".base_layer", "")
829
+ # Skip PEFT layers: they don’t exist in vLLM, and they are merged already.
830
+ if self.model.prefix in name:
831
+ continue
832
+ # When module to save, remove its prefix and discard the original module
833
+ if "original_module" in name:
834
+ continue
835
+ name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."])
836
+
837
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
838
+ self.vllm_client.update_named_param(name, param.data)
839
+ elif self.vllm_mode == "colocate":
840
+ llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model
841
+ llm_model.load_weights([(name, param.data)])
842
+ # Unmerge adapters while parameters are still gathered
843
+ self.model.unmerge_adapter()
844
+ # Parameters will automatically be repartitioned when exiting the context
845
+ else:
846
+ # For non-PEFT models, simply gather (if needed) and update each parameter individually.
847
+ if self.is_fsdp_enabled:
848
+ fsdp_plugin = getattr(self.accelerator.state, "fsdp_plugin", None)
849
+ fsdp_version = getattr(fsdp_plugin, "fsdp_version", 1) if fsdp_plugin else 1
850
+ if fsdp_version == 1:
851
+ self._sync_fsdp1_params_to_vllm(self.model) # use memory-efficient post-order traversal for FSDP
852
+ elif fsdp_version == 2:
853
+ self._sync_fsdp2_params_to_vllm(self.model)
854
+ else:
855
+ for name, param in self.model.named_parameters():
856
+ name = self._fix_param_name_to_vllm(name)
857
+ with gather_if_zero3([param]):
858
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
859
+ self.vllm_client.update_named_param(name, param.data)
860
+ elif self.vllm_mode == "colocate":
861
+ llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model
862
+ llm_model.load_weights([(name, param.data)])
863
+
864
+ # Reset cache on vLLM
865
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
866
+ self.vllm_client.reset_prefix_cache()
867
+ elif self.vllm_mode == "colocate":
868
+ self.llm.reset_prefix_cache()
869
+
870
+ def _sync_fsdp1_params_to_vllm(self, module: nn.Module, prefix: str = "", visited=None):
871
+ """Memory-efficient post-order traversal of FSDP modules to extract full parameters and sync with vLLM."""
872
+ # For FSDP1, we need to recurse into children and also use summon_full_params
873
+ if visited is None:
874
+ visited = set()
875
+ for child_name, child_module in module.named_children():
876
+ child_prefix = f"{prefix}.{child_name}" if prefix else child_name
877
+ self._sync_fsdp1_params_to_vllm(
878
+ child_module, prefix=child_prefix, visited=visited
879
+ ) # recurse into the child
880
+
881
+ if isinstance(module, FSDP):
882
+ with FSDP.summon_full_params(module, recurse=False, writeback=False):
883
+ for param_name, param in module.named_parameters():
884
+ full_name = f"{prefix}.{param_name}" if prefix else param_name
885
+ full_name = self._fix_param_name_to_vllm(full_name, extra_prefixes=["_fsdp_wrapped_module."])
886
+
887
+ if full_name in visited:
888
+ continue # skip FSDP subtrees already traversed
889
+ visited.add(full_name)
890
+
891
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
892
+ self.vllm_client.update_named_param(full_name, param.data)
893
+ elif self.vllm_mode == "colocate":
894
+ llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model
895
+ llm_model.load_weights([(full_name, param.data)])
896
+
897
+ def _fix_param_name_to_vllm(self, name, extra_prefixes: list[str] | None = None):
898
+ """Clean parameter names for vLLM compatibility"""
899
+ extra_prefixes = extra_prefixes or []
900
+ prefixes = ["_checkpoint_wrapped_module."] + extra_prefixes
901
+ for prefix in prefixes:
902
+ name = name.replace(prefix, "")
903
+ return name
904
+
905
+ def process_vision_row(
906
+ self, features: dict[str, list | torch.Tensor], processing_class=None
907
+ ) -> dict[str, list[int]]:
908
+ """
909
+ Process a vision row for VLM models (adapted from DPO trainer)
910
+ """
911
+ processor = processing_class or self.processing_class
912
+ processed_features = processor(images=[features["image"]], text=features["prompt"], add_special_tokens=False)
913
+
914
+ prompt_input_ids = processed_features["input_ids"][0]
915
+
916
+ # Create the output dict with required fields
917
+ output = {
918
+ "prompt_input_ids": prompt_input_ids,
919
+ "prompt_attention_mask": processed_features["attention_mask"][0],
920
+ }
921
+
922
+ # Add vision-specific fields
923
+ if "pixel_values" in processed_features:
924
+ output["pixel_values"] = processed_features["pixel_values"][0]
925
+ if "pixel_attention_mask" in processed_features:
926
+ output["pixel_attention_mask"] = processed_features["pixel_attention_mask"][0]
927
+ if "image_sizes" in processed_features:
928
+ output["image_sizes"] = processed_features["image_sizes"][0]
929
+
930
+ return output
931
+
932
+ def _generate(self, model, prompts, images=None):
933
+ """Generate completions using the model"""
934
+ device = next(model.parameters()).device
935
+ eos_token_id = self.eos_token_id
936
+ pad_token_id = self.pad_token_id
937
+
938
+ # Apply chat template and tokenize the input
939
+ inputs = [{"prompt": prompt} for prompt in prompts]
940
+
941
+ # Add images if provided (VLM support)
942
+ if images is not None:
943
+ for i, image in enumerate(images):
944
+ inputs[i]["image"] = image
945
+
946
+ # Apply chat template to get text prompts
947
+ prompts_text = [maybe_apply_chat_template(x, self.processing_class)["prompt"] for x in inputs]
948
+
949
+ # Handle image token collapsing/removal
950
+ # The chat template sometimes inserts a single image token into the prompt text. However, when this text is
951
+ # later tokenized, the single image token string is expanded into multiple image token IDs, depending on the
952
+ # image size. We need to handle this properly.
953
+ if self.image_token is not None and images is not None:
954
+ escaped_img_token = re.escape(self.image_token)
955
+ # Search for the image token in the chat template
956
+ if hasattr(self.processing_class, "chat_template") and self.processing_class.chat_template:
957
+ if re.search(escaped_img_token, self.processing_class.chat_template):
958
+ # Collapse repeated image tokens back into a single token
959
+ prompts_text = [
960
+ re.sub(rf"({escaped_img_token})+", self.image_token, text) for text in prompts_text
961
+ ]
962
+ else:
963
+ # If the chat template doesn't use the image token, remove all instances
964
+ if self.vision_end_token_id is not None:
965
+ escaped_eoi_token = re.escape(
966
+ self.processing_class.tokenizer.decode([self.vision_end_token_id])
967
+ )
968
+ prompts_text = [
969
+ re.sub(rf"({escaped_img_token})+{escaped_eoi_token}", "", text) for text in prompts_text
970
+ ]
971
+ else:
972
+ # If vision_end_token_id is None, just remove the image tokens
973
+ prompts_text = [re.sub(rf"({escaped_img_token})+", "", text) for text in prompts_text]
974
+
975
+ # Prepare kwargs for processing class
976
+ kwargs = {}
977
+ if images is not None:
978
+ kwargs = {"images": [[img] for img in images]}
979
+
980
+ # Process inputs using the processing class (handles both VLM and LLM)
981
+ prompt_inputs = self.processing_class(
982
+ text=prompts_text,
983
+ return_tensors="pt",
984
+ padding=True,
985
+ padding_side="left",
986
+ add_special_tokens=False,
987
+ **kwargs,
988
+ )
989
+
990
+ prompt_inputs = {k: v.to(device) for k, v in prompt_inputs.items()}
991
+ # Convert vision inputs to model's dtype for proper computation
992
+ if "pixel_values" in prompt_inputs:
993
+ # Handle DataParallel wrapped models
994
+ model_dtype = getattr(model, "dtype", None)
995
+ if model_dtype is None and hasattr(model, "module"):
996
+ model_dtype = model.module.dtype
997
+ if model_dtype is not None:
998
+ prompt_inputs["pixel_values"] = prompt_inputs["pixel_values"].to(model_dtype)
999
+
1000
+ # Sample 2 completions per prompt of size `max_new_tokens` from the model
1001
+ prompt_ids = prompt_inputs["input_ids"].repeat(2, 1)
1002
+ prompt_mask = prompt_inputs["attention_mask"].repeat(2, 1)
1003
+
1004
+ # Prepare vision inputs if available
1005
+ vision_generation_kwargs = {}
1006
+ if self.is_vision_model and images is not None:
1007
+ if "pixel_values" in prompt_inputs:
1008
+ vision_generation_kwargs["pixel_values"] = prompt_inputs["pixel_values"].repeat(2, 1, 1, 1)
1009
+ if "pixel_attention_mask" in prompt_inputs:
1010
+ vision_generation_kwargs["pixel_attention_mask"] = prompt_inputs["pixel_attention_mask"].repeat(2, 1)
1011
+ if "image_sizes" in prompt_inputs:
1012
+ vision_generation_kwargs["image_sizes"] = prompt_inputs["image_sizes"].repeat(2, 1)
1013
+ if "image_grid_thw" in prompt_inputs:
1014
+ vision_generation_kwargs["image_grid_thw"] = prompt_inputs["image_grid_thw"].repeat(2, 1)
1015
+
1016
+ if self.use_transformers_paged:
1017
+ previous_attn = self.model_wrapped.config._attn_implementation
1018
+
1019
+ if Version(transformers.__version__).release >= Version("5.0.0").release:
1020
+ new_attn = "paged|flash_attention_2" if is_flash_attn_2_available() else "paged|sdpa"
1021
+ else:
1022
+ new_attn = "paged_attention" if is_flash_attn_2_available() else "sdpa_paged"
1023
+ self.model_wrapped.config._attn_implementation = new_attn
1024
+ with (
1025
+ profiling_context(self, "transformers.generate_batch"),
1026
+ unwrap_model_for_generation(
1027
+ model, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation
1028
+ ) as unwrapped_model,
1029
+ torch.no_grad(),
1030
+ FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(),
1031
+ ):
1032
+ # Cast to the appropriate dtype based on training configuration
1033
+ if self.args.bf16:
1034
+ unwrapped_model.to(torch.bfloat16)
1035
+ elif self.args.fp16:
1036
+ unwrapped_model.to(torch.float16)
1037
+ with torch.inference_mode():
1038
+ all_outputs = unwrapped_model.generate_batch(
1039
+ prompt_ids.tolist(),
1040
+ generation_config=self.generation_config,
1041
+ progress_bar=False,
1042
+ )
1043
+ unwrapped_model.train() # restore training mode, as generate_batch forces eval mode
1044
+ completion_ids = [output.generated_tokens for output in all_outputs.values()]
1045
+ completion_ids = [torch.tensor(ids, device=device) for ids in completion_ids]
1046
+ completion_ids = pad(completion_ids, padding_value=self.pad_token_id, padding_side="right")
1047
+ prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1)
1048
+ # Restore the original attention implementation, training mode
1049
+ self.model_wrapped.config._attn_implementation = previous_attn
1050
+
1051
+ # Extract completion_ids and create completion_mask
1052
+ prompt_length = prompt_ids.size(1)
1053
+ completion_ids = prompt_completion_ids[:, prompt_length:]
1054
+ completion_ids, completion_mask = truncate_right(completion_ids, eos_token_id, pad_token_id)
1055
+
1056
+ return prompt_ids, prompt_mask, completion_ids, completion_mask
1057
+ else:
1058
+ # Regular generation path
1059
+ with (
1060
+ profiling_context(self, "transformers.generate"),
1061
+ unwrap_model_for_generation(
1062
+ model,
1063
+ self.accelerator,
1064
+ gather_deepspeed3_params=self.args.ds3_gather_for_generation,
1065
+ generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
1066
+ ) as unwrapped_model,
1067
+ torch.no_grad(),
1068
+ FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(),
1069
+ ):
1070
+ # Setup cache implementation if specified
1071
+ if self.args.cache_implementation is not None:
1072
+ unwrapped_model.generation_config.cache_implementation = self.args.cache_implementation
1073
+
1074
+ # Standard generation
1075
+ output = unwrapped_model.generate(
1076
+ input_ids=prompt_ids,
1077
+ attention_mask=prompt_mask,
1078
+ generation_config=self.generation_config,
1079
+ **vision_generation_kwargs,
1080
+ )
1081
+
1082
+ completion_ids = output[:, prompt_ids.size(1) :]
1083
+ completion_ids, completion_mask = truncate_right(completion_ids, eos_token_id, pad_token_id)
1084
+
1085
+ return prompt_ids, prompt_mask, completion_ids, completion_mask
1086
+
1087
+ def _calculate_rewards_from_functions(self, prompts, completions, completion_ids_list, **reward_kwargs):
1088
+ """
1089
+ Calculate rewards using reward functions
1090
+ """
1091
+ device = self.accelerator.device
1092
+ rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device)
1093
+
1094
+ # Add trainer state to reward kwargs for dynamic reward shaping
1095
+ reward_kwargs["trainer_state"] = self.state
1096
+
1097
+ for i, (reward_func, reward_processing_class) in enumerate(
1098
+ zip(self.reward_funcs, self.reward_processing_classes, strict=True)
1099
+ ):
1100
+ if isinstance(reward_func, nn.Module): # Model-based reward function
1101
+ # Handle conversational vs text input
1102
+ if is_conversational({"prompt": prompts[0]}):
1103
+ messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)]
1104
+ texts = [apply_chat_template(x, reward_processing_class)["text"] for x in messages]
1105
+ else:
1106
+ texts = [p + c for p, c in zip(prompts, completions, strict=True)]
1107
+
1108
+ # Tokenize and get reward scores
1109
+ reward_inputs = reward_processing_class(
1110
+ text=texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False
1111
+ )
1112
+ reward_inputs = {k: v.to(device) for k, v in reward_inputs.items()}
1113
+
1114
+ with torch.inference_mode():
1115
+ rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,)
1116
+ else:
1117
+ # Custom reward function
1118
+ output_reward_func = reward_func(
1119
+ prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs
1120
+ )
1121
+ # Convert None values to NaN
1122
+ output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func]
1123
+ rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device)
1124
+
1125
+ # Weight and sum across all reward functions
1126
+ if self.reward_weights is not None:
1127
+ total_rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
1128
+ else:
1129
+ total_rewards = rewards_per_func.nansum(dim=1)
1130
+
1131
+ return total_rewards
1132
+
1133
+ def _forward(self, model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs=None):
1134
+ # Get the number of tokens to truncate from prompt
1135
+ num_tokens_to_truncate = max(prompt_ids.size(1) + completion_ids.size(1) - self.max_length, 0)
1136
+
1137
+ # Truncate left to avoid oom
1138
+ prompt_ids = prompt_ids[:, num_tokens_to_truncate:]
1139
+ prompt_mask = prompt_mask[:, num_tokens_to_truncate:]
1140
+
1141
+ # Concat the prompt and completion
1142
+ prompt_completion_ids = torch.cat((prompt_ids, completion_ids), dim=1)
1143
+ prompt_completion_mask = torch.cat((prompt_mask, completion_mask), dim=1)
1144
+
1145
+ # Prepare model kwargs with vision inputs if available
1146
+ model_kwargs = {"attention_mask": prompt_completion_mask}
1147
+ if vision_inputs is not None:
1148
+ if "pixel_values" in vision_inputs:
1149
+ model_kwargs["pixel_values"] = vision_inputs["pixel_values"]
1150
+ if "pixel_attention_mask" in vision_inputs:
1151
+ model_kwargs["pixel_attention_mask"] = vision_inputs["pixel_attention_mask"]
1152
+ if "image_sizes" in vision_inputs:
1153
+ model_kwargs["image_sizes"] = vision_inputs["image_sizes"]
1154
+ if "image_grid_thw" in vision_inputs:
1155
+ model_kwargs["image_grid_thw"] = vision_inputs["image_grid_thw"]
1156
+
1157
+ # Get the logprobs of the completions from the model
1158
+ output = model(prompt_completion_ids, **model_kwargs)
1159
+
1160
+ # There is 1 offset, because the model predicts the next token
1161
+ prompt_len = prompt_ids.size(1)
1162
+ start_idx = prompt_len - 1 if prompt_len > 0 else 0
1163
+ # Only slice off the last logit when we have a prompt, otherwise we need all logits
1164
+ end_idx = -1 if prompt_len > 0 else None
1165
+ logits = output.logits[:, start_idx:end_idx]
1166
+
1167
+ # Take the completion tokens logprob
1168
+ logprobs = torch.take_along_dim(logits.log_softmax(dim=-1), completion_ids.unsqueeze(-1), dim=2).squeeze(-1)
1169
+ return logprobs
1170
+
1171
+ def training_step(
1172
+ self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None
1173
+ ) -> torch.Tensor:
1174
+ model.train()
1175
+
1176
+ prompts = inputs["prompt"]
1177
+ batch_size = len(prompts)
1178
+
1179
+ # Handle images for VLM support
1180
+ has_images = "image" in inputs
1181
+ images = None
1182
+ if has_images:
1183
+ images = inputs["image"]
1184
+ # Convert conversational prompts to include image tokens
1185
+ for prompt in prompts:
1186
+ if isinstance(prompt, list):
1187
+ for message in prompt:
1188
+ if not isinstance(message, dict):
1189
+ continue
1190
+ content = message.get("content")
1191
+ role = message.get("role")
1192
+ if isinstance(content, str):
1193
+ if role == "user":
1194
+ message["content"] = [{"type": "image"}, {"type": "text", "text": content}]
1195
+ elif role == "system":
1196
+ message["content"] = [{"type": "text", "text": content}]
1197
+
1198
+ if self.args.use_vllm:
1199
+ prompt_ids, prompt_mask, completion_ids, completion_mask = self._generate_vllm(prompts, images)
1200
+ else:
1201
+ prompt_ids, prompt_mask, completion_ids, completion_mask = self._generate(model, prompts, images)
1202
+
1203
+ contain_eos_token = torch.any(completion_ids == self.eos_token_id, dim=-1)
1204
+
1205
+ # Extract vision inputs if available for VLM support
1206
+ vision_inputs = None
1207
+ if has_images and self.is_vision_model and not self.args.use_vllm:
1208
+ # For vision models with transformers generation, we need to prepare vision inputs
1209
+ # Process the images to get vision inputs that can be passed through the forward pass
1210
+ vision_inputs = {}
1211
+ kwargs = {"images": [[img] for img in images]}
1212
+ processed = self.processing_class(
1213
+ text=[""] * len(images), # Dummy text for vision processing
1214
+ return_tensors="pt",
1215
+ **kwargs,
1216
+ )
1217
+ # Handle DataParallel wrapped models
1218
+ model_device = getattr(model, "device", None)
1219
+ model_dtype = getattr(model, "dtype", None)
1220
+ if model_device is None and hasattr(model, "module"):
1221
+ model_device = model.module.device
1222
+ model_dtype = model.module.dtype
1223
+ # Move vision tensors to device and convert to model dtype
1224
+ # Need to duplicate for 2 completions per prompt
1225
+ if "pixel_values" in processed:
1226
+ vision_inputs["pixel_values"] = (
1227
+ processed["pixel_values"].to(model_device, dtype=model_dtype).repeat(2, 1, 1, 1)
1228
+ )
1229
+ if "pixel_attention_mask" in processed:
1230
+ vision_inputs["pixel_attention_mask"] = processed["pixel_attention_mask"].to(model_device).repeat(2, 1)
1231
+ if "image_sizes" in processed:
1232
+ vision_inputs["image_sizes"] = processed["image_sizes"].to(model_device).repeat(2, 1)
1233
+ if "image_grid_thw" in processed:
1234
+ vision_inputs["image_grid_thw"] = processed["image_grid_thw"].to(model_device).repeat(2, 1)
1235
+
1236
+ logprobs = self._forward(model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs)
1237
+ with torch.no_grad():
1238
+ if self.ref_model is not None:
1239
+ ref_logprobs = self._forward(
1240
+ self.ref_model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs
1241
+ )
1242
+ else: # peft case: we just need to disable the adapter
1243
+ with self.model.disable_adapter():
1244
+ ref_logprobs = self._forward(
1245
+ self.model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs
1246
+ )
1247
+
1248
+ # Decode the completions, and format them if the input is conversational
1249
+ device = logprobs.device
1250
+ completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
1251
+ if is_conversational({"prompt": prompts[0]}):
1252
+ completions = [[{"role": "assistant", "content": completion}] for completion in completions]
1253
+
1254
+ # Get the reward from reward functions or judge
1255
+ if self.reward_funcs is not None:
1256
+ # First create completion_ids_list for custom reward functions
1257
+ completion_ids_list = [completion_ids[i].tolist() for i in range(completion_ids.shape[0])]
1258
+
1259
+ # Extract additional fields from inputs for reward functions
1260
+ reward_kwargs = {}
1261
+ keys = [key for key in inputs if key not in ["prompt"]]
1262
+ for key in keys:
1263
+ if isinstance(inputs[key], (list, tuple)):
1264
+ # Repeat input fields to match number of completions (2 per prompt)
1265
+ reward_kwargs[key] = inputs[key] * 2
1266
+ else:
1267
+ reward_kwargs[key] = inputs[key]
1268
+
1269
+ # Calculate rewards using reward functions
1270
+ rewards = self._calculate_rewards_from_functions(
1271
+ prompts=2 * prompts, completions=completions, completion_ids_list=completion_ids_list, **reward_kwargs
1272
+ )
1273
+
1274
+ # Apply missing EOS penalty if configured
1275
+ if self.args.missing_eos_penalty is not None:
1276
+ rewards[~contain_eos_token] -= self.args.missing_eos_penalty
1277
+
1278
+ # Split rewards into chosen/rejected pairs
1279
+ first_half, second_half = rewards.split(batch_size)
1280
+ mask = first_half >= second_half
1281
+ elif self.judge is not None:
1282
+ # Once formatted, conversational data may contain special tokens (such as <|im_start|>) that are not
1283
+ # directly understandable by the judge and could alter its judgment. To avoid this and make the judge
1284
+ # independent of the model's chat template, we use the raw conversation data, and apply our own chat
1285
+ # template to it.
1286
+ if is_conversational({"prompt": prompts[0]}):
1287
+ environment = jinja2.Environment()
1288
+ template = environment.from_string(SIMPLE_CHAT_TEMPLATE)
1289
+ prompts = [template.render(messages=prompt) for prompt in prompts]
1290
+ completions = [template.render(messages=completion) for completion in completions]
1291
+
1292
+ ranks_of_first_completion = self.judge.judge(
1293
+ prompts, list(zip(completions[:batch_size], completions[batch_size:], strict=True))
1294
+ )
1295
+
1296
+ # convert ranks to a True/False mask:
1297
+ # when rank == 0, it means the first completion is the best
1298
+ # when rank == 1, it means the second completion is the best
1299
+ mask = torch.tensor([rank == 0 for rank in ranks_of_first_completion], device=device)
1300
+
1301
+ batch_range = torch.arange(batch_size, device=device)
1302
+ chosen_indices = batch_range + (~mask * batch_size)
1303
+ rejected_indices = batch_range + (mask * batch_size)
1304
+
1305
+ # Build tensor so that the first half is the chosen examples and the second half the rejected examples
1306
+ cr_indices = torch.cat((chosen_indices, rejected_indices), dim=0) # cr = chosen and rejected
1307
+ cr_logprobs = logprobs[cr_indices]
1308
+ cr_ref_logprobs = ref_logprobs[cr_indices]
1309
+
1310
+ # mask out the padding tokens
1311
+ padding_mask = ~completion_mask.bool()
1312
+ cr_padding_mask = padding_mask[cr_indices]
1313
+
1314
+ cr_logprobs_sum = (cr_logprobs * ~cr_padding_mask).sum(1)
1315
+ cr_ref_logprobs_sum = (cr_ref_logprobs * ~cr_padding_mask).sum(1)
1316
+
1317
+ # Split the chosen and rejected examples
1318
+ chosen_logprobs_sum, rejected_logprobs_sum = torch.split(cr_logprobs_sum, batch_size)
1319
+ chosen_ref_logprobs_sum, rejected_ref_logprobs_sum = torch.split(cr_ref_logprobs_sum, batch_size)
1320
+ pi_logratios = chosen_logprobs_sum - rejected_logprobs_sum
1321
+ ref_logratios = chosen_ref_logprobs_sum - rejected_ref_logprobs_sum
1322
+
1323
+ logits = pi_logratios - ref_logratios
1324
+
1325
+ if self.args.loss_type == "sigmoid":
1326
+ losses = -F.logsigmoid(self.beta * logits)
1327
+ elif self.args.loss_type == "ipo":
1328
+ losses = (logits - 1 / (2 * self.beta)) ** 2
1329
+ else:
1330
+ raise NotImplementedError(f"invalid loss type {self.args.loss_type}")
1331
+
1332
+ loss = losses.mean()
1333
+
1334
+ # Log everything
1335
+ if self.reward_funcs is not None:
1336
+ # When using reward_funcs, we have rewards instead of scores
1337
+ scores_margin = rewards[chosen_indices] - rewards[rejected_indices]
1338
+ self.stats["objective/scores_margin"].append(
1339
+ self.accelerator.gather_for_metrics(scores_margin.mean()).mean().item()
1340
+ )
1341
+ self.stats["objective/scores"].append(self.accelerator.gather_for_metrics(rewards.mean()).mean().item())
1342
+ self.stats["val/contain_eos_token"].append(contain_eos_token.float().mean().item())
1343
+ self.stats["logps/chosen"].append(self.accelerator.gather_for_metrics(chosen_logprobs_sum).mean().item())
1344
+ self.stats["logps/rejected"].append(self.accelerator.gather_for_metrics(rejected_logprobs_sum).mean().item())
1345
+
1346
+ kl = logprobs - ref_logprobs
1347
+ mean_kl = kl.sum(1).mean()
1348
+ self.stats["objective/kl"].append(self.accelerator.gather_for_metrics(mean_kl).mean().item())
1349
+ non_score_reward = (-self.beta * kl).sum(1)
1350
+ mean_non_score_reward = non_score_reward.mean()
1351
+ self.stats["objective/non_score_reward"].append(
1352
+ self.accelerator.gather_for_metrics(mean_non_score_reward).mean().item()
1353
+ )
1354
+ if self.reward_funcs is not None:
1355
+ # Calculate RLHF reward by combining rewards with non_score_reward
1356
+ rlhf_reward = rewards + non_score_reward
1357
+ self.stats["objective/rlhf_reward"].append(self.accelerator.gather_for_metrics(rlhf_reward).mean().item())
1358
+
1359
+ mean_entropy = -logprobs.sum(1).mean()
1360
+ self.stats["objective/entropy"].append(self.accelerator.gather_for_metrics(mean_entropy).mean().item())
1361
+ chosen_rewards = self.beta * (chosen_logprobs_sum - chosen_ref_logprobs_sum)
1362
+ gathered_chosen_rewards = self.accelerator.gather_for_metrics(chosen_rewards)
1363
+ self.stats["rewards/chosen"].append(gathered_chosen_rewards.mean().item())
1364
+ rejected_rewards = self.beta * (rejected_logprobs_sum - rejected_ref_logprobs_sum)
1365
+ gathered_rejected_rewards = self.accelerator.gather_for_metrics(rejected_rewards)
1366
+ self.stats["rewards/rejected"].append(gathered_rejected_rewards.mean().item())
1367
+ margin = gathered_chosen_rewards - gathered_rejected_rewards
1368
+ self.stats["rewards/margins"].append(margin.mean().item())
1369
+ accuracy = margin > 0
1370
+ self.stats["rewards/accuracies"].append(accuracy.float().mean().item())
1371
+ self.stats["beta"].append(self.beta)
1372
+
1373
+ if (
1374
+ self.args.torch_empty_cache_steps is not None
1375
+ and self.state.global_step % self.args.torch_empty_cache_steps == 0
1376
+ ):
1377
+ empty_cache()
1378
+
1379
+ kwargs = {}
1380
+
1381
+ # For LOMO optimizers you need to explicitly use the learning rate
1382
+ if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]:
1383
+ kwargs["learning_rate"] = self._get_learning_rate()
1384
+
1385
+ if self.args.n_gpu > 1:
1386
+ loss = loss.mean() # mean() to average on multi-gpu parallel training
1387
+
1388
+ self.accelerator.backward(loss, **kwargs)
1389
+
1390
+ return loss.detach() / self.args.gradient_accumulation_steps
1391
+
1392
+ # Same as Trainer._maybe_log_save_evaluate but log our metrics
1393
+ def _maybe_log_save_evaluate(
1394
+ self, tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval, start_time, learning_rate=None
1395
+ ):
1396
+ if self.control.should_log and self.state.global_step > self._globalstep_last_logged:
1397
+ logs: dict[str, float] = {}
1398
+
1399
+ # all_gather + mean() to get average loss over all processes
1400
+ if Version(transformers.__version__) >= Version("5.2.0"):
1401
+ tr_loss_scalar = nested_gather(tr_loss, self.args.parallel_mode).mean().item()
1402
+ else:
1403
+ tr_loss_scalar = self._nested_gather(tr_loss).mean().item()
1404
+
1405
+ # reset tr_loss to zero
1406
+ tr_loss -= tr_loss
1407
+
1408
+ logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)
1409
+ if grad_norm is not None:
1410
+ logs["grad_norm"] = grad_norm.detach().item() if isinstance(grad_norm, torch.Tensor) else grad_norm
1411
+ if learning_rate is not None:
1412
+ logs["learning_rate"] = learning_rate
1413
+ else:
1414
+ logs["learning_rate"] = self._get_learning_rate()
1415
+
1416
+ # Add our metrics
1417
+ for key, val in self.stats.items():
1418
+ logs[key] = sum(val) / len(val)
1419
+ self.stats = {key: [] for key in self.stats} # reset stats
1420
+
1421
+ self._total_loss_scalar += tr_loss_scalar
1422
+ self._globalstep_last_logged = self.state.global_step
1423
+ self.store_flos()
1424
+ self.log(logs, start_time)
1425
+
1426
+ metrics = None
1427
+ if self.control.should_evaluate:
1428
+ metrics = self._evaluate(trial, ignore_keys_for_eval)
1429
+ is_new_best_metric = self._determine_best_metric(metrics=metrics, trial=trial)
1430
+
1431
+ if self.args.save_strategy == "best":
1432
+ self.control.should_save = is_new_best_metric
1433
+
1434
+ if self.control.should_save:
1435
+ self._save_checkpoint(model, trial)
1436
+ self.control = self.callback_handler.on_save(self.args, self.state, self.control)
1437
+
1438
+ # Ensure the model card is saved along with the checkpoint
1439
+ def _save_checkpoint(self, model, trial):
1440
+ if self.args.hub_model_id is None:
1441
+ model_name = Path(self.args.output_dir).name
1442
+ else:
1443
+ model_name = self.args.hub_model_id.split("/")[-1]
1444
+ self.create_model_card(model_name=model_name)
1445
+ super()._save_checkpoint(model, trial)
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/openenv/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .utils import generate_rollout_completions
16
+
17
+
18
+ __all__ = ["generate_rollout_completions"]
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/openenv/utils.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 typing import Any
16
+
17
+ import torch
18
+
19
+ from ...data_utils import is_conversational
20
+ from ...extras.profiling import profiling_context
21
+ from ...import_utils import is_vllm_available
22
+
23
+
24
+ if is_vllm_available():
25
+ from vllm import SamplingParams
26
+ from vllm.sampling_params import StructuredOutputsParams
27
+
28
+
29
+ def _build_base_generation_kwargs(
30
+ trainer,
31
+ overrides: dict[str, Any] | None = None,
32
+ ) -> dict[str, Any]:
33
+ """Build base generation kwargs common to both colocate and server modes."""
34
+ generation_kwargs: dict[str, Any] = {
35
+ "n": 1,
36
+ "temperature": trainer.temperature,
37
+ "top_k": trainer.top_k,
38
+ "min_p": 0.0 if trainer.min_p is None else trainer.min_p,
39
+ "max_tokens": trainer.max_completion_length,
40
+ }
41
+ if trainer.repetition_penalty is not None:
42
+ generation_kwargs["repetition_penalty"] = trainer.repetition_penalty
43
+ if trainer.top_p is not None:
44
+ generation_kwargs["top_p"] = trainer.top_p
45
+
46
+ if trainer.args.generation_kwargs is not None:
47
+ generation_kwargs.update(trainer.args.generation_kwargs)
48
+
49
+ if overrides is not None:
50
+ generation_kwargs.update(overrides)
51
+
52
+ generation_kwargs = {key: value for key, value in generation_kwargs.items() if value is not None}
53
+
54
+ if generation_kwargs.get("n", 1) != 1:
55
+ raise ValueError("generate_rollout_completions expects n=1.")
56
+
57
+ return generation_kwargs
58
+
59
+
60
+ def _build_colocate_sampling_params(
61
+ trainer,
62
+ overrides: dict[str, Any] | None = None,
63
+ *,
64
+ logprobs: bool = True,
65
+ ) -> "SamplingParams":
66
+ """Build SamplingParams for colocate mode."""
67
+ generation_kwargs = _build_base_generation_kwargs(trainer, overrides)
68
+
69
+ # Add colocate-specific parameters
70
+ if trainer.vllm_generation.structured_outputs_regex:
71
+ generation_kwargs["structured_outputs"] = StructuredOutputsParams(
72
+ regex=trainer.vllm_generation.structured_outputs_regex
73
+ )
74
+ if logprobs:
75
+ generation_kwargs["logprobs"] = 0
76
+
77
+ return SamplingParams(**generation_kwargs)
78
+
79
+
80
+ def _build_server_generation_kwargs(
81
+ trainer,
82
+ overrides: dict[str, Any] | None = None,
83
+ ) -> dict[str, Any]:
84
+ """Build generation kwargs for server mode."""
85
+ return _build_base_generation_kwargs(trainer, overrides)
86
+
87
+
88
+ def generate_rollout_completions(
89
+ trainer,
90
+ prompts: list[str],
91
+ *,
92
+ generation_overrides: dict[str, Any] | None = None,
93
+ as_chat: bool | None = None,
94
+ ) -> list[dict[str, Any]]:
95
+ """
96
+ Generate completions for custom rollouts when vLLM is running in colocate or server mode.
97
+
98
+ Returns one result per prompt, containing prompt and completion token ids along with per-token log probabilities
99
+ and the generated text.
100
+ """
101
+
102
+ if not prompts:
103
+ return []
104
+
105
+ if not trainer.use_vllm:
106
+ raise RuntimeError("Custom rollouts require vLLM to call generate_rollout_completions.")
107
+
108
+ if trainer.vllm_mode == "server":
109
+ return _generate_rollout_completions_server(trainer, prompts, generation_overrides, as_chat)
110
+ elif trainer.vllm_mode == "colocate":
111
+ return _generate_rollout_completions_colocate(trainer, prompts, generation_overrides, as_chat)
112
+ else:
113
+ raise ValueError(f"vllm_mode must be 'server' or 'colocate', got '{trainer.vllm_mode}'")
114
+
115
+
116
+ def _generate_rollout_completions_server(
117
+ trainer,
118
+ prompts: list[str],
119
+ generation_overrides: dict[str, Any] | None = None,
120
+ as_chat: bool | None = None,
121
+ ) -> list[dict[str, Any]]:
122
+ """Generate completions using vLLM server mode."""
123
+ generation_kwargs = _build_server_generation_kwargs(trainer, generation_overrides)
124
+
125
+ if as_chat is None:
126
+ as_chat = prompts and is_conversational({"prompt": prompts[0]})
127
+
128
+ with profiling_context(trainer, "vLLM.generate_rollout_server"):
129
+ if as_chat:
130
+ # Prompts are raw message dicts; use .chat() so the vLLM server applies the chat template
131
+ output = trainer.vllm_generation.vllm_client.chat(
132
+ messages=prompts,
133
+ **generation_kwargs,
134
+ chat_template_kwargs=trainer.chat_template_kwargs,
135
+ tools=trainer.tools or None,
136
+ chat_template=trainer.chat_template,
137
+ )
138
+ else:
139
+ output = trainer.vllm_generation.vllm_client.generate(prompts=prompts, **generation_kwargs)
140
+
141
+ # Format results to match colocate output format
142
+ results: list[dict[str, Any]] = []
143
+ for i in range(len(prompts)):
144
+ results.append(
145
+ {
146
+ "prompt_ids": output["prompt_ids"][i],
147
+ "completion_ids": list(output["completion_ids"][i]),
148
+ "logprobs": list(output["logprobs"][i]),
149
+ "text": trainer.processing_class.decode(output["completion_ids"][i], skip_special_tokens=True),
150
+ }
151
+ )
152
+
153
+ return results
154
+
155
+
156
+ def _generate_rollout_completions_colocate(
157
+ trainer,
158
+ prompts: list[str],
159
+ generation_overrides: dict[str, Any] | None = None,
160
+ as_chat: bool | None = None,
161
+ ) -> list[dict[str, Any]]:
162
+ """Generate completions using vLLM colocate mode."""
163
+ sampling_params = _build_colocate_sampling_params(trainer, generation_overrides)
164
+ prompts_for_generation = prompts
165
+ original_size = len(prompts)
166
+
167
+ if trainer.vllm_tensor_parallel_size > 1:
168
+ gathered_prompts = [None for _ in range(trainer.vllm_tensor_parallel_size)]
169
+ torch.distributed.all_gather_object(gathered_prompts, prompts, group=trainer.vllm_generation.tp_group)
170
+ prompts_for_generation = [prompt for group_prompts in gathered_prompts for prompt in group_prompts]
171
+
172
+ if as_chat is None:
173
+ as_chat = prompts_for_generation and is_conversational({"prompt": prompts_for_generation[0]})
174
+
175
+ if trainer.args.vllm_enable_sleep_mode:
176
+ trainer.vllm_generation.llm.wake_up(tags=["kv_cache"])
177
+ # Work around for https://github.com/vllm-project/vllm/issues/29341
178
+ trainer.vllm_generation.llm.collective_rpc("reload_weights")
179
+
180
+ with profiling_context(trainer, "vLLM.generate_rollout"):
181
+ if as_chat:
182
+ vllm_outputs = trainer.vllm_generation.llm.chat(
183
+ prompts_for_generation, sampling_params=sampling_params, use_tqdm=False
184
+ )
185
+ else:
186
+ vllm_outputs = trainer.vllm_generation.llm.generate(
187
+ prompts_for_generation, sampling_params=sampling_params, use_tqdm=False
188
+ )
189
+
190
+ results: list[dict[str, Any]] = []
191
+ for request in vllm_outputs:
192
+ if not request.outputs:
193
+ results.append({"prompt_ids": request.prompt_token_ids, "completion_ids": [], "logprobs": [], "text": ""})
194
+ continue
195
+ sequence = request.outputs[0]
196
+ logprobs = [next(iter(token_logprob.values())).logprob for token_logprob in sequence.logprobs]
197
+ results.append(
198
+ {
199
+ "prompt_ids": request.prompt_token_ids,
200
+ "completion_ids": sequence.token_ids,
201
+ "logprobs": logprobs,
202
+ "text": sequence.text,
203
+ }
204
+ )
205
+
206
+ if trainer.vllm_tensor_parallel_size > 1:
207
+ local_rank_in_group = torch.distributed.get_rank(group=trainer.vllm_generation.tp_group)
208
+ tp_slice = slice(local_rank_in_group * original_size, (local_rank_in_group + 1) * original_size)
209
+ results = results[tp_slice]
210
+
211
+ if trainer.args.vllm_enable_sleep_mode:
212
+ trainer.vllm_generation.llm.sleep(level=2)
213
+
214
+ return results
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/orpo/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .orpo_config import ORPOConfig
16
+ from .orpo_trainer import ORPOTrainer
17
+
18
+
19
+ __all__ = ["ORPOConfig", "ORPOTrainer"]
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/orpo/orpo_config.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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, field
16
+ from typing import Any
17
+
18
+ from ...trainer.base_config import _BaseConfig
19
+
20
+
21
+ @dataclass
22
+ class ORPOConfig(_BaseConfig):
23
+ # docstyle-ignore
24
+ r"""
25
+ Configuration class for the [`experimental.orpo.ORPOTrainer`].
26
+
27
+ This class includes only the parameters that are specific to ORPO training. For a full list of training arguments,
28
+ please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
29
+ differ from those in [`~transformers.TrainingArguments`].
30
+
31
+ Using [`~transformers.HfArgumentParser`] we can turn this class into
32
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
33
+ command line.
34
+
35
+ Parameters:
36
+ max_length (`int` or `None`, *optional*, defaults to `1024`):
37
+ Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want
38
+ to use the default data collator.
39
+ max_completion_length (`int`, *optional*):
40
+ Maximum length of the completion. This argument is required if you want to use the default data collator
41
+ and your model is an encoder-decoder.
42
+ beta (`float`, *optional*, defaults to `0.1`):
43
+ Parameter controlling the relative ratio loss weight in the ORPO loss. In the
44
+ [paper](https://huggingface.co/papers/2403.07691), it is denoted by λ. In the
45
+ [code](https://github.com/xfactlab/orpo), it is denoted by `alpha`.
46
+ disable_dropout (`bool`, *optional*, defaults to `True`):
47
+ Whether to disable dropout in the model.
48
+ padding_value (`int`, *optional*):
49
+ Padding value to use. If `None`, the padding value of the tokenizer is used.
50
+ generate_during_eval (`bool`, *optional*, defaults to `False`):
51
+ If `True`, generates and logs completions from the model to W&B or Comet during evaluation.
52
+ is_encoder_decoder (`bool`, *optional*):
53
+ When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument,
54
+ you need to specify if the model returned by the callable is an encoder-decoder model.
55
+ model_init_kwargs (`dict[str, Any]`, *optional*):
56
+ Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a
57
+ string.
58
+ dataset_num_proc (`int`, *optional*):
59
+ Number of processes to use for processing the dataset.
60
+
61
+ > [!NOTE]
62
+ > These parameters have default values different from [`~transformers.TrainingArguments`]:
63
+ > - `logging_steps`: Defaults to `10` instead of `500`.
64
+ > - `gradient_checkpointing`: Defaults to `True` instead of `False`.
65
+ > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
66
+ > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.
67
+ """
68
+
69
+ _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
70
+
71
+ # Parameters whose default values are overridden from TrainingArguments
72
+ learning_rate: float = field(
73
+ default=1e-6,
74
+ metadata={"help": "The initial learning rate for AdamW."},
75
+ )
76
+
77
+ max_length: int | None = field(
78
+ default=1024,
79
+ metadata={"help": "Maximum length of the sequences (prompt + completion) in the batch."},
80
+ )
81
+ max_completion_length: int | None = field(
82
+ default=None,
83
+ metadata={
84
+ "help": "Maximum length of the completion. This argument is required if you want to use the default data "
85
+ "collator and your model is an encoder-decoder."
86
+ },
87
+ )
88
+ beta: float = field(
89
+ default=0.1,
90
+ metadata={
91
+ "help": "Parameter controlling the relative ratio loss weight in the ORPO loss. In the paper, it is "
92
+ "denoted by λ."
93
+ },
94
+ )
95
+ disable_dropout: bool = field(
96
+ default=True,
97
+ metadata={"help": "Whether to disable dropout in the model."},
98
+ )
99
+ padding_value: int | None = field(
100
+ default=None,
101
+ metadata={"help": "Padding value to use. If `None`, the padding value of the tokenizer is used."},
102
+ )
103
+ generate_during_eval: bool = field(
104
+ default=False,
105
+ metadata={"help": "If `True`, generates and logs completions from the model to W&B during evaluation."},
106
+ )
107
+ is_encoder_decoder: bool | None = field(
108
+ default=None,
109
+ metadata={
110
+ "help": "When using the `model_init` argument (callable) to instantiate the model instead of the `model` "
111
+ "argument, you need to specify if the model returned by the callable is an encoder-decoder model."
112
+ },
113
+ )
114
+ model_init_kwargs: dict[str, Any] | str | None = field(
115
+ default=None,
116
+ metadata={
117
+ "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model "
118
+ "from a string."
119
+ },
120
+ )
121
+ dataset_num_proc: int | None = field(
122
+ default=None,
123
+ metadata={"help": "Number of processes to use for processing the dataset."},
124
+ )
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/orpo/orpo_trainer.py ADDED
@@ -0,0 +1,1030 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 inspect
16
+ import random
17
+ import textwrap
18
+ from collections import defaultdict
19
+ from collections.abc import Callable
20
+ from contextlib import nullcontext
21
+ from pathlib import Path
22
+ from typing import Any, Literal
23
+
24
+ import numpy as np
25
+ import pandas as pd
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+ import transformers
30
+ from accelerate import PartialState, logging
31
+ from datasets import Dataset
32
+ from packaging.version import Version
33
+ from torch import autocast
34
+ from torch.utils.data import DataLoader
35
+ from transformers import (
36
+ AutoModelForCausalLM,
37
+ BaseImageProcessor,
38
+ DataCollator,
39
+ FeatureExtractionMixin,
40
+ PreTrainedModel,
41
+ PreTrainedTokenizerBase,
42
+ ProcessorMixin,
43
+ TrainerCallback,
44
+ is_comet_available,
45
+ is_torch_xla_available,
46
+ is_wandb_available,
47
+ )
48
+ from transformers.trainer_utils import EvalLoopOutput
49
+ from transformers.utils import is_peft_available, is_torch_fx_proxy
50
+
51
+ from ...data_utils import maybe_apply_chat_template, maybe_extract_prompt
52
+ from ...trainer.base_trainer import _BaseTrainer
53
+ from ...trainer.utils import disable_dropout_in_model, log_table_to_comet_experiment, selective_log_softmax
54
+ from ..utils import (
55
+ DPODataCollatorWithPadding,
56
+ add_bos_token_if_needed,
57
+ add_eos_token_if_needed,
58
+ pad_to_length,
59
+ peft_module_casting_to_bf16,
60
+ )
61
+ from .orpo_config import ORPOConfig
62
+
63
+
64
+ if is_peft_available():
65
+ from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training
66
+
67
+
68
+ if is_wandb_available():
69
+ import wandb
70
+
71
+ if is_torch_xla_available():
72
+ import torch_xla.core.xla_model as xm
73
+
74
+
75
+ logger = logging.get_logger(__name__)
76
+
77
+
78
+ def log1mexp(x: torch.FloatTensor) -> torch.FloatTensor:
79
+ """Numerically stable computation of log(1-exp(x))."""
80
+ # branch at -ln 2 ~ -0.693 to avoid cancellation
81
+ t = -0.6931471805599453
82
+ return torch.where(x < t, torch.log1p(-torch.exp(x)), torch.log(-torch.expm1(x)))
83
+
84
+
85
+ class ORPOTrainer(_BaseTrainer):
86
+ r"""
87
+ Initialize ORPOTrainer.
88
+
89
+ Args:
90
+ model ([`~transformers.PreTrainedModel`]):
91
+ The model to train, preferably an [`~transformers.AutoModelForSequenceClassification`].
92
+ args ([`experimental.orpo.ORPOConfig`]):
93
+ The ORPO config arguments to use for training.
94
+ data_collator ([`~transformers.DataCollator`]):
95
+ The data collator to use for training. If None is specified, the default data collator
96
+ ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the
97
+ maximum length of the sequences in the batch, given a dataset of paired sequences.
98
+ train_dataset ([`~datasets.Dataset`]):
99
+ The dataset to use for training.
100
+ eval_dataset ([`~datasets.Dataset`]):
101
+ The dataset to use for evaluation.
102
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
103
+ Processing class used to process the data. If provided, will be used to automatically process the inputs
104
+ for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
105
+ reuse the fine-tuned model.
106
+ model_init (`Callable[[], transformers.PreTrainedModel]`):
107
+ The model initializer to use for training. If None is specified, the default model initializer will be
108
+ used.
109
+ callbacks (`list[transformers.TrainerCallback]`):
110
+ The callbacks to use for training.
111
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
112
+ The optimizer and scheduler to use for training.
113
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
114
+ The function to use to preprocess the logits before computing the metrics.
115
+ peft_config (`dict`, defaults to `None`):
116
+ The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in
117
+ a PEFT model.
118
+ compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
119
+ The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
120
+ metric values.
121
+ """
122
+
123
+ _tag_names = ["trl", "orpo"]
124
+ _name = "ORPO"
125
+ _paper = {
126
+ "title": "ORPO: Monolithic Preference Optimization without Reference Model",
127
+ "id": "2403.07691",
128
+ # docstyle-ignore
129
+ "citation": textwrap.dedent("""\
130
+ @article{hong2024orpo,
131
+ title = {{ORPO: Monolithic Preference Optimization without Reference Model}},
132
+ author = {Jiwoo Hong and Noah Lee and James Thorne},
133
+ year = 2024,
134
+ eprint = {arXiv:2403.07691}
135
+ }"""),
136
+ }
137
+
138
+ def __init__(
139
+ self,
140
+ model: PreTrainedModel | nn.Module | str | None = None,
141
+ args: ORPOConfig | None = None,
142
+ data_collator: DataCollator | None = None,
143
+ train_dataset: Dataset | None = None,
144
+ eval_dataset: Dataset | dict[str, Dataset] | None = None,
145
+ processing_class: PreTrainedTokenizerBase
146
+ | BaseImageProcessor
147
+ | FeatureExtractionMixin
148
+ | ProcessorMixin
149
+ | None = None,
150
+ model_init: Callable[[], PreTrainedModel] | None = None,
151
+ callbacks: list[TrainerCallback] | None = None,
152
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
153
+ preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
154
+ peft_config: dict | None = None,
155
+ compute_metrics: Callable[[EvalLoopOutput], dict] | None = None,
156
+ ):
157
+ if train_dataset is None:
158
+ raise ValueError("`train_dataset` is required")
159
+
160
+ if args.model_init_kwargs is None:
161
+ model_init_kwargs = {}
162
+ elif not isinstance(model, str):
163
+ raise ValueError("You passed model_kwargs to the ORPOTrainer. But your model is already instantiated.")
164
+ else:
165
+ model_init_kwargs = args.model_init_kwargs
166
+ dtype = model_init_kwargs.get("dtype", "auto")
167
+ if dtype is not None:
168
+ # Convert to `torch.dtype` if an str is passed
169
+ if isinstance(dtype, str) and dtype != "auto":
170
+ dtype = getattr(torch, dtype)
171
+ if dtype != "auto" and not isinstance(dtype, torch.dtype):
172
+ raise ValueError(
173
+ f"Invalid `dtype` passed to the ORPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {dtype}."
174
+ )
175
+ model_init_kwargs["dtype"] = dtype
176
+ model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto")
177
+
178
+ if isinstance(model, str):
179
+ model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
180
+
181
+ # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16`
182
+ # has been called in order to properly call autocast if needed.
183
+ self._peft_has_been_casted_to_bf16 = False
184
+
185
+ if not is_peft_available() and peft_config is not None:
186
+ raise ValueError(
187
+ "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models"
188
+ )
189
+ elif is_peft_available() and peft_config is not None:
190
+ if isinstance(model, PeftModel):
191
+ raise ValueError(
192
+ "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first "
193
+ "merge and unload the existing adapter, save the resulting base model, and then pass that base "
194
+ "model along with the new `peft_config` to the trainer."
195
+ )
196
+
197
+ if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False):
198
+ _support_gc_kwargs = hasattr(
199
+ args, "gradient_checkpointing_kwargs"
200
+ ) and "gradient_checkpointing_kwargs" in list(
201
+ inspect.signature(prepare_model_for_kbit_training).parameters
202
+ )
203
+
204
+ prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing}
205
+
206
+ if _support_gc_kwargs:
207
+ prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs
208
+
209
+ model = prepare_model_for_kbit_training(model, **prepare_model_kwargs)
210
+ elif args.gradient_checkpointing:
211
+ # For backward compatibility with older versions of transformers
212
+ if hasattr(model, "enable_input_require_grads"):
213
+ model.enable_input_require_grads()
214
+ else:
215
+
216
+ def make_inputs_require_grad(module, input, output):
217
+ output.requires_grad_(True)
218
+
219
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
220
+
221
+ # get peft model with the given config
222
+ model = get_peft_model(model, peft_config)
223
+ if args.bf16 and getattr(model, "is_loaded_in_4bit", False):
224
+ peft_module_casting_to_bf16(model)
225
+ # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager
226
+ self._peft_has_been_casted_to_bf16 = True
227
+
228
+ # For models that use gradient_checkpointing, we need to attach a hook that enables input
229
+ # to explicitly have `requires_grad=True`, otherwise training will either silently
230
+ # fail or completely fail.
231
+ elif args.gradient_checkpointing:
232
+ # For backward compatibility with older versions of transformers
233
+ if hasattr(model, "enable_input_require_grads"):
234
+ model.enable_input_require_grads()
235
+ else:
236
+
237
+ def make_inputs_require_grad(module, input, output):
238
+ output.requires_grad_(True)
239
+
240
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
241
+
242
+ if args.generate_during_eval and not (is_wandb_available() or is_comet_available()):
243
+ raise ValueError(
244
+ "`generate_during_eval=True` requires Weights and Biases or Comet to be installed."
245
+ " Please install `wandb` or `comet-ml` to resolve."
246
+ )
247
+
248
+ if model is not None:
249
+ self.is_encoder_decoder = model.config.is_encoder_decoder
250
+ elif args.is_encoder_decoder is None:
251
+ raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.")
252
+ else:
253
+ self.is_encoder_decoder = args.is_encoder_decoder
254
+
255
+ if self.is_encoder_decoder:
256
+ self.decoder_start_token_id = model.config.decoder_start_token_id
257
+ self.pad_token_id = model.config.pad_token_id
258
+
259
+ if processing_class is None:
260
+ raise ValueError("processing_class must be specified to tokenize a ORPO dataset.")
261
+ if args.max_length is None:
262
+ logger.warning(
263
+ "`max_length` is not set in the ORPOConfig's init"
264
+ " it will default to `512` by default, but you should do it yourself in the future.",
265
+ )
266
+ max_length = 512
267
+ else:
268
+ max_length = args.max_length
269
+
270
+ if args.max_completion_length is None and self.is_encoder_decoder:
271
+ logger.warning(
272
+ "When using an encoder decoder architecture, you should set `max_completion_length` in the ORPOConfig's init"
273
+ " it will default to `128` by default, but you should do it yourself in the future.",
274
+ )
275
+ self.max_completion_length = 128
276
+ else:
277
+ self.max_completion_length = args.max_completion_length
278
+
279
+ if data_collator is None:
280
+ data_collator = DPODataCollatorWithPadding(
281
+ pad_token_id=processing_class.pad_token_id,
282
+ is_encoder_decoder=self.is_encoder_decoder,
283
+ )
284
+
285
+ if args.remove_unused_columns:
286
+ args.remove_unused_columns = False
287
+ # warn users
288
+ logger.warning(
289
+ "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments"
290
+ " we have set it for you, but you should do it yourself in the future.",
291
+ )
292
+
293
+ self.use_dpo_data_collator = True
294
+ else:
295
+ self.use_dpo_data_collator = False
296
+
297
+ # Disable dropout in the model and reference model
298
+ if args.disable_dropout:
299
+ disable_dropout_in_model(model)
300
+
301
+ self.max_length = max_length
302
+ self.generate_during_eval = args.generate_during_eval
303
+ self.padding_value = args.padding_value if args.padding_value is not None else processing_class.pad_token_id
304
+ self.processing_class = processing_class
305
+
306
+ self.beta = args.beta
307
+ self.aux_loss_enabled = getattr(model.config, "output_router_logits", False)
308
+ self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0)
309
+ if self.aux_loss_enabled and self.aux_loss_coef == 0.0:
310
+ logger.warning(
311
+ "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to "
312
+ "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value "
313
+ "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary "
314
+ "loss.",
315
+ )
316
+
317
+ self._stored_metrics = defaultdict(lambda: defaultdict(list))
318
+
319
+ # Compute that only on the main process for faster data processing.
320
+ # see: https://github.com/huggingface/trl/pull/1255
321
+ with PartialState().main_process_first():
322
+ # Extract the prompt if needed, and apply the chat template if needed
323
+ train_dataset = train_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc)
324
+ train_dataset = train_dataset.map(
325
+ maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}, num_proc=args.dataset_num_proc
326
+ )
327
+ train_dataset = train_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc)
328
+ if eval_dataset is not None:
329
+ eval_dataset = eval_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc)
330
+ eval_dataset = eval_dataset.map(
331
+ maybe_apply_chat_template,
332
+ fn_kwargs={"tokenizer": processing_class},
333
+ num_proc=args.dataset_num_proc,
334
+ )
335
+ eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc)
336
+
337
+ # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
338
+ # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
339
+ # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
340
+ # default to the recommended non-reentrant behavior here, while preserving any user-provided value.
341
+ if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
342
+ args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
343
+ args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
344
+
345
+ super().__init__(
346
+ model=model,
347
+ args=args,
348
+ data_collator=data_collator,
349
+ train_dataset=train_dataset,
350
+ eval_dataset=eval_dataset,
351
+ processing_class=processing_class,
352
+ model_init=model_init,
353
+ compute_metrics=compute_metrics,
354
+ callbacks=callbacks,
355
+ optimizers=optimizers,
356
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
357
+ )
358
+
359
+ # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
360
+ # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
361
+ # self.model_accepts_loss_kwargs to False to enable scaling.
362
+ self.model_accepts_loss_kwargs = False
363
+
364
+ # Add tags for models that have been loaded with the correct transformers version
365
+ if hasattr(self.model, "add_model_tags"):
366
+ self.model.add_model_tags(self._tag_names)
367
+
368
+ if not hasattr(self, "accelerator"):
369
+ raise AttributeError(
370
+ "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`."
371
+ )
372
+
373
+ def build_tokenized_answer(self, prompt, answer):
374
+ """
375
+ Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. It does ensure `enc(a + b) = enc(a) + enc(a +
376
+ b)[len(enc(a)):]`. Reference:
377
+ https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
378
+ """
379
+
380
+ full_tokenized = self.processing_class(prompt + answer, add_special_tokens=False)
381
+ prompt_input_ids = self.processing_class(prompt, add_special_tokens=False)["input_ids"]
382
+
383
+ answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :]
384
+ answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :]
385
+
386
+ # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]`
387
+ full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids])
388
+
389
+ # Prepare input tokens for token by token comparison
390
+ full_input_ids = np.array(full_tokenized["input_ids"])
391
+
392
+ if len(full_input_ids) != len(full_concat_input_ids):
393
+ raise ValueError("Prompt input ids and answer input ids should have the same length.")
394
+
395
+ # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens
396
+ # can be merged together when tokenizing prompt+answer. This could result
397
+ # on the last token from the prompt being different when tokenized on its own
398
+ # vs when done as prompt+answer.
399
+ response_token_ids_start_idx = len(prompt_input_ids)
400
+
401
+ # If tokenized prompt is different than both prompt+answer, then it means the
402
+ # last token has changed due to merging.
403
+ if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]:
404
+ response_token_ids_start_idx -= 1
405
+
406
+ prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx]
407
+ prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx]
408
+
409
+ if len(prompt_input_ids) != len(prompt_attention_mask):
410
+ raise ValueError("Prompt input ids and attention mask should have the same length.")
411
+
412
+ answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:]
413
+ answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:]
414
+
415
+ return dict(
416
+ prompt_input_ids=prompt_input_ids,
417
+ prompt_attention_mask=prompt_attention_mask,
418
+ input_ids=answer_input_ids,
419
+ attention_mask=answer_attention_mask,
420
+ )
421
+
422
+ def tokenize_row(self, feature, model: PreTrainedModel | nn.Module | None = None) -> dict:
423
+ """Tokenize a single row from a ORPO specific dataset.
424
+
425
+ At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt +
426
+ chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long,
427
+ we truncate the chosen/rejected.
428
+
429
+ We also create the labels for the chosen/rejected responses, which are of length equal to the sum of the length
430
+ of the prompt and the chosen/rejected response, with `-100` for the prompt tokens.
431
+ """
432
+ batch = {}
433
+ prompt = feature["prompt"]
434
+ chosen = feature["chosen"]
435
+ rejected = feature["rejected"]
436
+
437
+ if not self.is_encoder_decoder:
438
+ # Check issues below for more details
439
+ # 1. https://github.com/huggingface/trl/issues/907
440
+ # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
441
+ # 3. https://github.com/LianjiaTech/BELLE/issues/337
442
+
443
+ if not isinstance(prompt, str):
444
+ raise ValueError(f"prompt should be an str but got {type(prompt)}")
445
+ prompt_tokens = self.processing_class(prompt, add_special_tokens=False)
446
+ prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()}
447
+
448
+ if not isinstance(chosen, str):
449
+ raise ValueError(f"chosen should be an str but got {type(chosen)}")
450
+ chosen_tokens = self.build_tokenized_answer(prompt, chosen)
451
+
452
+ if not isinstance(rejected, str):
453
+ raise ValueError(f"rejected should be an str but got {type(rejected)}")
454
+ rejected_tokens = self.build_tokenized_answer(prompt, rejected)
455
+
456
+ # Last prompt token might get merged by tokenizer and
457
+ # it should not be included for generation if that happens
458
+ prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"])
459
+
460
+ chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"])
461
+ rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"])
462
+ prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids)
463
+
464
+ for k, v in prompt_tokens.items():
465
+ prompt_tokens[k] = v[:prompt_len_input_ids]
466
+
467
+ # Make sure prompts only have one different token at most an
468
+ # and length only differs by 1 at most
469
+ num_diff_tokens = sum(
470
+ a != b
471
+ for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"], strict=False)
472
+ )
473
+ num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids)
474
+ if num_diff_tokens > 1 or num_diff_len > 1:
475
+ raise ValueError(
476
+ "Chosen and rejected prompt_input_ids might only differ on the "
477
+ "last token due to tokenizer merge ops."
478
+ )
479
+
480
+ # add BOS token to head of prompt. Avoid adding if it's already there
481
+ prompt_tokens, chosen_tokens, rejected_tokens = add_bos_token_if_needed(
482
+ self.processing_class.bos_token_id,
483
+ prompt_len_input_ids,
484
+ prompt_tokens,
485
+ chosen_prompt_len_input_ids,
486
+ chosen_tokens,
487
+ rejected_prompt_len_input_ids,
488
+ rejected_tokens,
489
+ )
490
+
491
+ # add EOS token to end of answer. Avoid adding if it's already there
492
+ chosen_tokens, rejected_tokens = add_eos_token_if_needed(
493
+ self.processing_class.eos_token_id, chosen_tokens, rejected_tokens
494
+ )
495
+
496
+ longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"]))
497
+
498
+ # if combined sequence is too long, truncate the response
499
+ for answer_tokens in [chosen_tokens, rejected_tokens]:
500
+ if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length:
501
+ for k in ["input_ids", "attention_mask"]:
502
+ answer_tokens[k] = answer_tokens[k][: self.max_length - longer_response_length]
503
+
504
+ # Create labels
505
+ chosen_sequence_tokens = {
506
+ k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"]
507
+ }
508
+ rejected_sequence_tokens = {
509
+ k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"]
510
+ }
511
+ chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:]
512
+ chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [-100] * len(
513
+ chosen_tokens["prompt_input_ids"]
514
+ )
515
+ rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:]
516
+ rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [-100] * len(
517
+ rejected_tokens["prompt_input_ids"]
518
+ )
519
+
520
+ for k, toks in {
521
+ "chosen_": chosen_sequence_tokens,
522
+ "rejected_": rejected_sequence_tokens,
523
+ "": prompt_tokens,
524
+ }.items():
525
+ for type_key, tokens in toks.items():
526
+ if type_key == "token_type_ids":
527
+ continue
528
+ batch[f"{k}{type_key}"] = tokens
529
+
530
+ else:
531
+ chosen_tokens = self.processing_class(
532
+ chosen, truncation=True, max_length=self.max_completion_length, add_special_tokens=True
533
+ )
534
+ rejected_tokens = self.processing_class(
535
+ rejected, truncation=True, max_length=self.max_completion_length, add_special_tokens=True
536
+ )
537
+ prompt_tokens = self.processing_class(prompt, add_special_tokens=True)
538
+
539
+ batch["chosen_labels"] = chosen_tokens["input_ids"]
540
+ batch["rejected_labels"] = rejected_tokens["input_ids"]
541
+ batch["prompt_input_ids"] = prompt_tokens["input_ids"]
542
+ batch["prompt_attention_mask"] = prompt_tokens["attention_mask"]
543
+
544
+ if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"):
545
+ batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(
546
+ labels=torch.tensor(batch["rejected_labels"])
547
+ )
548
+ batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(
549
+ labels=torch.tensor(batch["chosen_labels"])
550
+ )
551
+
552
+ if is_torch_xla_available():
553
+ # Pad the sequences to global max_length to avoid TorchXLA recompilation
554
+ for k in batch:
555
+ if "labels" in k or self.is_encoder_decoder:
556
+ pad_value = -100
557
+ elif k.endswith("_input_ids"):
558
+ pad_value = self.padding_value
559
+ elif k.endswith("_attention_mask"):
560
+ pad_value = 0
561
+ batch[k] = batch[k] + [pad_value] * (self.max_length - len(batch[k]))
562
+ return batch
563
+
564
+ @staticmethod
565
+ def concatenated_inputs(
566
+ batch: dict[str, list | torch.LongTensor],
567
+ is_encoder_decoder: bool = False,
568
+ padding_value: int = 0,
569
+ device: torch.device | None = None,
570
+ ) -> dict[str, torch.LongTensor]:
571
+ """Concatenate the chosen and rejected inputs into a single tensor.
572
+
573
+ Args:
574
+ batch:
575
+ A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors
576
+ of shape (batch_size, sequence_length).
577
+ is_encoder_decoder:
578
+ Whether the model is an encoder-decoder model.
579
+ padding_value:
580
+ The padding value to use for the concatenated inputs_ids.
581
+ device:
582
+ The device for the concatenated inputs.
583
+
584
+ Returns:
585
+ A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'.
586
+ """
587
+ concatenated_batch = {}
588
+
589
+ if is_encoder_decoder:
590
+ max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1])
591
+ else:
592
+ max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1])
593
+
594
+ for k in batch:
595
+ if k.startswith("chosen") and isinstance(batch[k], torch.Tensor):
596
+ if "labels" in k or is_encoder_decoder:
597
+ pad_value = -100
598
+ elif k.endswith("_input_ids"):
599
+ pad_value = padding_value
600
+ elif k.endswith("_attention_mask"):
601
+ pad_value = 0
602
+ concatenated_key = k.replace("chosen", "concatenated")
603
+ concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value)
604
+ for k in batch:
605
+ if k.startswith("rejected") and isinstance(batch[k], torch.Tensor):
606
+ if "labels" in k or is_encoder_decoder:
607
+ pad_value = -100
608
+ elif k.endswith("_input_ids"):
609
+ pad_value = padding_value
610
+ elif k.endswith("_attention_mask"):
611
+ pad_value = 0
612
+ concatenated_key = k.replace("rejected", "concatenated")
613
+ concatenated_batch[concatenated_key] = torch.cat(
614
+ (
615
+ concatenated_batch[concatenated_key],
616
+ pad_to_length(batch[k], max_length, pad_value=pad_value),
617
+ ),
618
+ dim=0,
619
+ ).to(device=device)
620
+
621
+ if is_encoder_decoder:
622
+ concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device)
623
+ concatenated_batch["concatenated_attention_mask"] = (
624
+ batch["prompt_attention_mask"].repeat(2, 1).to(device=device)
625
+ )
626
+
627
+ return concatenated_batch
628
+
629
+ def odds_ratio_loss(
630
+ self,
631
+ policy_chosen_logps: torch.FloatTensor,
632
+ policy_rejected_logps: torch.FloatTensor,
633
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
634
+ """Compute ORPO's odds ratio (OR) loss for a batch of policy and reference model log probabilities.
635
+
636
+ Args:
637
+ policy_chosen_logps:
638
+ Log probabilities of the policy model for the chosen responses. Shape: (batch_size,)
639
+ policy_rejected_logps:
640
+ Log probabilities of the policy model for the rejected responses. Shape: (batch_size,)
641
+
642
+ Returns:
643
+ A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). The losses tensor contains the ORPO
644
+ loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for
645
+ the chosen and rejected responses, respectively. The log odds ratio of the chosen responses over the
646
+ rejected responses ratio for logging purposes. The `log(sigmoid(log_odds_chosen))` for logging purposes.
647
+ """
648
+
649
+ # Derived from Eqs. (4) and (7) from https://huggingface.co/papers/2403.07691 by using log identities and exp(log(P(y|x)) = P(y|x)
650
+ policy_chosen_logps = policy_chosen_logps.float()
651
+ policy_rejected_logps = policy_rejected_logps.float()
652
+ log_odds = (policy_chosen_logps - policy_rejected_logps) - (
653
+ log1mexp(policy_chosen_logps) - log1mexp(policy_rejected_logps)
654
+ )
655
+ ratio = F.logsigmoid(log_odds)
656
+ losses = self.beta * ratio
657
+
658
+ chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device)).detach()
659
+ rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device)).detach()
660
+
661
+ return losses, chosen_rewards, rejected_rewards, torch.mean(ratio), torch.mean(log_odds)
662
+
663
+ @staticmethod
664
+ def get_batch_logps(
665
+ logits: torch.FloatTensor,
666
+ labels: torch.LongTensor,
667
+ average_log_prob: bool = False,
668
+ is_encoder_decoder: bool = False,
669
+ ) -> torch.FloatTensor:
670
+ """Compute the log probabilities of the given labels under the given logits.
671
+
672
+ Args:
673
+ logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size)
674
+ labels:
675
+ Labels for which to compute the log probabilities. Label tokens with a value of `-100` are ignored.
676
+ Shape: (batch_size, sequence_length)
677
+ average_log_prob:
678
+ If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the
679
+ log probabilities of the (non-masked) tokens.
680
+ is_encoder_decoder: Whether the model is an encoder-decoder model.
681
+
682
+ Returns:
683
+ A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the
684
+ given logits.
685
+ """
686
+ if logits.shape[:-1] != labels.shape:
687
+ raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.")
688
+
689
+ if not is_encoder_decoder:
690
+ labels = labels[:, 1:].clone()
691
+ logits = logits[:, :-1, :]
692
+ loss_mask = labels != -100
693
+
694
+ # dummy token; we'll ignore the losses on these tokens later
695
+ labels = torch.where(labels == -100, 0, labels)
696
+
697
+ per_token_logps = selective_log_softmax(logits, labels)
698
+
699
+ if average_log_prob:
700
+ return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1)
701
+ else:
702
+ return (per_token_logps * loss_mask).sum(-1)
703
+
704
+ def concatenated_forward(
705
+ self, model: nn.Module, batch: dict[str, list | torch.LongTensor]
706
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
707
+ """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together.
708
+
709
+ We do this to avoid doing two forward passes, because it's faster for FSDP.
710
+ """
711
+ concatenated_batch = self.concatenated_inputs(
712
+ batch,
713
+ is_encoder_decoder=self.is_encoder_decoder,
714
+ padding_value=self.padding_value,
715
+ device=self.accelerator.device,
716
+ )
717
+ len_chosen = batch["chosen_labels"].shape[0]
718
+
719
+ model_kwargs = (
720
+ {
721
+ "decoder_input_ids": self._shift_right(concatenated_batch["concatenated_labels"]),
722
+ }
723
+ if self.is_encoder_decoder
724
+ else {}
725
+ )
726
+
727
+ if self.aux_loss_enabled:
728
+ model_kwargs["output_router_logits"] = True
729
+
730
+ outputs = model(
731
+ concatenated_batch["concatenated_input_ids"],
732
+ attention_mask=concatenated_batch["concatenated_attention_mask"],
733
+ use_cache=False,
734
+ **model_kwargs,
735
+ )
736
+ all_logits = outputs.logits
737
+
738
+ def cross_entropy_loss(logits, labels):
739
+ if not self.is_encoder_decoder:
740
+ # Shift so that tokens < n predict n
741
+ logits = logits[..., :-1, :].contiguous()
742
+ labels = labels[..., 1:].contiguous()
743
+ # Flatten the tokens
744
+ loss_fct = nn.CrossEntropyLoss()
745
+ logits = logits.view(-1, logits.shape[-1])
746
+ labels = labels.view(-1)
747
+ # Enable model parallelism
748
+ labels = labels.to(logits.device)
749
+ loss = loss_fct(logits, labels)
750
+ return loss
751
+
752
+ if self.is_encoder_decoder:
753
+ labels = concatenated_batch["concatenated_labels"].clone()
754
+ else:
755
+ labels = concatenated_batch["concatenated_input_ids"].clone()
756
+ attention_mask = concatenated_batch["concatenated_attention_mask"]
757
+ labels = torch.where(attention_mask == 1, labels, -100)
758
+ # orpo chosen nll loss is computed over the full prompt and response
759
+ chosen_nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen])
760
+
761
+ all_logps = self.get_batch_logps(
762
+ all_logits,
763
+ concatenated_batch["concatenated_labels"],
764
+ average_log_prob=True,
765
+ is_encoder_decoder=self.is_encoder_decoder,
766
+ )
767
+
768
+ chosen_logps = all_logps[:len_chosen]
769
+ rejected_logps = all_logps[len_chosen:]
770
+
771
+ if not self.is_encoder_decoder:
772
+ chosen_logits = all_logits[:len_chosen, :-1, :]
773
+ rejected_logits = all_logits[len_chosen:, :-1, :]
774
+ else:
775
+ chosen_logits = all_logits[:len_chosen]
776
+ rejected_logits = all_logits[len_chosen:]
777
+
778
+ if self.aux_loss_enabled:
779
+ return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss, outputs.aux_loss)
780
+
781
+ return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss)
782
+
783
+ def get_batch_loss_metrics(
784
+ self,
785
+ model,
786
+ batch: dict[str, list | torch.LongTensor],
787
+ train_eval: Literal["train", "eval"] = "train",
788
+ ):
789
+ """Compute the ORPO loss and other metrics for the given batch of inputs for train or test."""
790
+ metrics = {}
791
+
792
+ forward_output = self.concatenated_forward(model, batch)
793
+ (
794
+ policy_chosen_logps,
795
+ policy_rejected_logps,
796
+ policy_chosen_logits,
797
+ policy_rejected_logits,
798
+ policy_nll_loss,
799
+ ) = forward_output[:5]
800
+ if self.aux_loss_enabled:
801
+ aux_loss = forward_output[5]
802
+
803
+ losses, chosen_rewards, rejected_rewards, log_odds_ratio, log_odds_chosen = self.odds_ratio_loss(
804
+ policy_chosen_logps, policy_rejected_logps
805
+ )
806
+ # full ORPO loss
807
+ loss = policy_nll_loss - losses.mean()
808
+
809
+ reward_accuracies = (chosen_rewards > rejected_rewards).float()
810
+
811
+ prefix = "eval_" if train_eval == "eval" else ""
812
+ metrics[f"{prefix}rewards/chosen"] = self.accelerator.gather_for_metrics(chosen_rewards).mean()
813
+ metrics[f"{prefix}rewards/rejected"] = self.accelerator.gather_for_metrics(rejected_rewards).mean()
814
+ metrics[f"{prefix}rewards/accuracies"] = self.accelerator.gather_for_metrics(reward_accuracies).mean()
815
+ metrics[f"{prefix}rewards/margins"] = self.accelerator.gather_for_metrics(
816
+ chosen_rewards - rejected_rewards
817
+ ).mean()
818
+ metrics[f"{prefix}logps/rejected"] = self.accelerator.gather_for_metrics(policy_rejected_logps).detach().mean()
819
+ metrics[f"{prefix}logps/chosen"] = self.accelerator.gather_for_metrics(policy_chosen_logps).detach().mean()
820
+ metrics[f"{prefix}logits/rejected"] = self.accelerator.gather_for_metrics(
821
+ policy_rejected_logits.detach().mean()
822
+ ).mean()
823
+ metrics[f"{prefix}logits/chosen"] = self.accelerator.gather_for_metrics(
824
+ policy_chosen_logits.detach().mean()
825
+ ).mean()
826
+ metrics[f"{prefix}nll_loss"] = self.accelerator.gather_for_metrics(policy_nll_loss).detach().mean()
827
+ metrics[f"{prefix}log_odds_ratio"] = self.accelerator.gather_for_metrics(log_odds_ratio).detach().mean()
828
+ metrics[f"{prefix}log_odds_chosen"] = self.accelerator.gather_for_metrics(log_odds_chosen).detach().mean()
829
+ if is_torch_xla_available():
830
+ xm.mark_step() # needed because .item() calls
831
+ for k, v in metrics.items():
832
+ metrics[k] = v.item()
833
+ if self.aux_loss_enabled:
834
+ loss += self.aux_loss_coef * aux_loss
835
+
836
+ return loss, metrics
837
+
838
+ def compute_loss(
839
+ self,
840
+ model: PreTrainedModel | nn.Module,
841
+ inputs: dict[str, torch.Tensor | Any],
842
+ return_outputs=False,
843
+ num_items_in_batch=None,
844
+ ) -> torch.Tensor | tuple[torch.Tensor, dict[str, torch.Tensor]]:
845
+ compute_loss_context_manager = (
846
+ autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
847
+ )
848
+
849
+ with compute_loss_context_manager:
850
+ loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train")
851
+
852
+ # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class:
853
+ loss = loss.to(self.args.device)
854
+
855
+ # force log the metrics
856
+ self.store_metrics(metrics, train_eval="train")
857
+
858
+ if return_outputs:
859
+ return (loss, metrics)
860
+ return loss
861
+
862
+ def generate_from_model(self, model, batch: dict[str, torch.LongTensor]) -> str:
863
+ """Generate samples from the model and reference model for the given batch of inputs."""
864
+
865
+ # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with
866
+ # the torch amp context manager as some hidden states are silently casted to full precision.
867
+ generate_context_manager = (
868
+ autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
869
+ )
870
+
871
+ with generate_context_manager:
872
+ policy_output = model.generate(
873
+ input_ids=batch["prompt_input_ids"],
874
+ attention_mask=batch["prompt_attention_mask"],
875
+ max_length=self.max_length,
876
+ do_sample=True,
877
+ pad_token_id=self.processing_class.pad_token_id,
878
+ )
879
+
880
+ policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id)
881
+ policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True)
882
+
883
+ return policy_output_decoded
884
+
885
+ def prediction_step(
886
+ self,
887
+ model: PreTrainedModel | nn.Module,
888
+ inputs: dict[str, torch.Tensor | Any],
889
+ prediction_loss_only: bool,
890
+ ignore_keys: list[str] | None = None,
891
+ ):
892
+ if not self.use_dpo_data_collator:
893
+ logger.warning(
894
+ "prediction_step is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than "
895
+ "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator"
896
+ )
897
+ if ignore_keys is None:
898
+ if hasattr(model, "config"):
899
+ ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", [])
900
+ else:
901
+ ignore_keys = []
902
+
903
+ prediction_context_manager = (
904
+ autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
905
+ )
906
+
907
+ with torch.no_grad(), prediction_context_manager:
908
+ loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval")
909
+
910
+ # force log the metrics
911
+ self.store_metrics(metrics, train_eval="eval")
912
+
913
+ if prediction_loss_only:
914
+ return (loss.detach(), None, None)
915
+
916
+ # logits for the chosen and rejected samples from model
917
+ logits_dict = {
918
+ "eval_logits/chosen": metrics["eval_logits/chosen"],
919
+ "eval_logits/rejected": metrics["eval_logits/rejected"],
920
+ }
921
+ logits = [v for k, v in logits_dict.items() if k not in ignore_keys]
922
+ logits = torch.tensor(logits, device=self.accelerator.device)
923
+ labels = torch.zeros(logits.shape[0], device=self.accelerator.device)
924
+
925
+ return (loss.detach(), logits, labels)
926
+
927
+ def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None:
928
+ for key, value in metrics.items():
929
+ self._stored_metrics[train_eval][key].append(value)
930
+
931
+ def evaluation_loop(
932
+ self,
933
+ dataloader: DataLoader,
934
+ description: str,
935
+ prediction_loss_only: bool | None = None,
936
+ ignore_keys: list[str] | None = None,
937
+ metric_key_prefix: str = "eval",
938
+ ) -> EvalLoopOutput:
939
+ """
940
+ Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by
941
+ `Trainer.evaluate()` and `Trainer.predict()`.
942
+
943
+ Works both with or without labels.
944
+ """
945
+
946
+ # Sample and save to game log if requested (for one batch to save time)
947
+ if self.generate_during_eval:
948
+ # Generate random indices within the range of the total number of samples
949
+ num_samples = len(dataloader.dataset)
950
+ random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size)
951
+
952
+ # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader
953
+ random_batch_dataset = dataloader.dataset.select(random_indices)
954
+ random_batch = self.data_collator(random_batch_dataset)
955
+ random_batch = self._prepare_inputs(random_batch)
956
+
957
+ policy_output_decoded = self.generate_from_model(self.model, random_batch)
958
+
959
+ table = pd.DataFrame(
960
+ columns=["Prompt", "Policy"],
961
+ data=[
962
+ [prompt, pol[len(prompt) :]]
963
+ for prompt, pol in zip(random_batch["prompt"], policy_output_decoded, strict=True)
964
+ ],
965
+ )
966
+ if "wandb" in self.args.report_to:
967
+ wandb.log({"game_log": wandb.Table(data=table)})
968
+
969
+ if "comet_ml" in self.args.report_to:
970
+ log_table_to_comet_experiment(
971
+ name="game_log.csv",
972
+ table=table,
973
+ )
974
+
975
+ # Base evaluation
976
+ initial_output = super().evaluation_loop(
977
+ dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix
978
+ )
979
+
980
+ return initial_output
981
+
982
+ def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
983
+ """
984
+ Log `logs` on the various objects watching training, including stored metrics.
985
+
986
+ Args:
987
+ logs (`dict[str, float]`):
988
+ The values to log.
989
+ start_time (`float`, *optional*):
990
+ Start time of the training.
991
+ """
992
+ # logs either has 'loss' or 'eval_loss'
993
+ train_eval = "train" if "loss" in logs else "eval"
994
+ # Add averaged stored metrics to logs
995
+ for key, metrics in self._stored_metrics[train_eval].items():
996
+ logs[key] = torch.tensor(metrics).mean().item()
997
+ del self._stored_metrics[train_eval]
998
+ return super().log(logs, start_time)
999
+
1000
+ def _shift_right(self, input_ids):
1001
+ if self.decoder_start_token_id is None:
1002
+ raise ValueError(
1003
+ "model.config.decoder_start_token_id has to be defined. It is usually set to the pad_token_id."
1004
+ )
1005
+
1006
+ # shift inputs to the right
1007
+ if is_torch_fx_proxy(input_ids):
1008
+ # Item assignment is not supported natively for proxies.
1009
+ shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), self.decoder_start_token_id)
1010
+ shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1)
1011
+ else:
1012
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
1013
+ shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
1014
+ shifted_input_ids[..., 0] = self.decoder_start_token_id
1015
+
1016
+ if self.pad_token_id is None:
1017
+ raise ValueError("model.config.pad_token_id has to be defined.")
1018
+ # replace possible -100 values in labels by `pad_token_id`
1019
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, self.pad_token_id)
1020
+
1021
+ return shifted_input_ids
1022
+
1023
+ # Ensure the model card is saved along with the checkpoint
1024
+ def _save_checkpoint(self, model, trial):
1025
+ if self.args.hub_model_id is None:
1026
+ model_name = Path(self.args.output_dir).name
1027
+ else:
1028
+ model_name = self.args.hub_model_id.split("/")[-1]
1029
+ self.create_model_card(model_name=model_name)
1030
+ super()._save_checkpoint(model, trial)
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/papo/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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
+
16
+ from .papo_config import PAPOConfig
17
+ from .papo_trainer import PAPOTrainer
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/papo/papo_config.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 Literal
17
+
18
+ from ...trainer.grpo_config import GRPOConfig
19
+
20
+
21
+ @dataclass
22
+ class PAPOConfig(GRPOConfig):
23
+ """
24
+ Configuration class for PAPOTrainer.
25
+
26
+ PAPO (Perception-Aware Policy Optimization) extends GRPO/DAPO for multimodal reasoning by adding an implicit
27
+ perception loss and double entropy regularization.
28
+
29
+ Args:
30
+ perception_loss_weight (`float`, *optional*, defaults to `0.1`):
31
+ gamma Weight coefficient for the perception loss term. This encourages the model to be sensitive to visual
32
+ changes.
33
+
34
+ mask_ratio (`float`, *optional*, defaults to `0.3`):
35
+ Ratio of the image to mask when computing perception loss.
36
+
37
+ mask_type (`Literal["random", "patch", "grid"]`, *optional*, defaults to `"random"`):
38
+ Type of masking strategy to use.
39
+
40
+ der_loss_weight1 (`float`, *optional*, defaults to `0.03`):
41
+ eta1 Weight coefficient for the Double Entropy Regularization (DER) term. This term encourages confident
42
+ predictions with original images (low entropy) and uncertain predictions with masked images (high entropy).
43
+
44
+ der_loss_weight2 (`float`, *optional*, defaults to `0.03`):
45
+ eta2 Weight coefficient for the Double Entropy Regularization (DER) term. This term encourages confident
46
+ predictions with original images (low entropy) and uncertain predictions with masked images (high entropy).
47
+
48
+ loss_type (`Literal["grpo", "dapo"]`, inherited from GRPOConfig):
49
+ Base loss type to use. Set to "grpo" for PAPO-G or "dapo" for PAPO-D.
50
+ """
51
+
52
+ perception_loss_weight: float = 0.1
53
+ mask_ratio: float = 0.3
54
+ mask_type: Literal["random", "patch", "grid"] = "random"
55
+
56
+ # Added for Double Entropy Regularization
57
+ der_loss_weight1: float = 0.03
58
+ der_loss_weight2: float = 0.03
59
+
60
+ def __post_init__(self):
61
+ super().__post_init__()
62
+
63
+ # Validation
64
+ if not 0.0 <= self.mask_ratio <= 1.0:
65
+ raise ValueError(f"mask_ratio must be between 0 and 1, got {self.mask_ratio}")
66
+
67
+ if self.der_loss_weight1 < 0 or self.der_loss_weight2 < 0:
68
+ raise ValueError(
69
+ f"der_loss_weight1 and der_loss_weight2 must be non-negative, got {self.der_loss_weight1} and {self.der_loss_weight2}"
70
+ )
71
+
72
+ if self.mask_type not in ["random", "patch", "grid"]:
73
+ raise ValueError(f"mask_type must be one of ['random', 'patch', 'grid'], got {self.mask_type}")
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/papo/papo_trainer.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 random
16
+ import textwrap
17
+
18
+ import torch
19
+ from datasets import Dataset, IterableDataset
20
+ from transformers import PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin
21
+
22
+ from ...trainer.grpo_trainer import GRPOTrainer, RewardFunc
23
+ from ...trainer.utils import nanmax, nanmin
24
+ from .papo_config import PAPOConfig
25
+
26
+
27
+ class PAPOTrainer(GRPOTrainer):
28
+ """
29
+ Trainer for Perception-Aware Policy Optimization (PAPO).
30
+
31
+ PAPO extends GRPO/DAPO for multimodal reasoning by adding an implicit perception loss that encourages the model to
32
+ better utilize visual information. The key innovation is computing KL divergence between model outputs on original
33
+ vs. corrupted (masked) images.
34
+
35
+ Two variants are supported:
36
+ - PAPO-G: PAPO + GRPO (use loss_type="grpo")
37
+ - PAPO-D: PAPO + DAPO (use loss_type="dapo")
38
+
39
+ Example:
40
+
41
+ ```python
42
+ from datasets import load_dataset
43
+ from trl.experimental.papo import PAPOTrainer, PAPOConfig
44
+
45
+ dataset = load_dataset("your-vlm-dataset", split="train")
46
+
47
+
48
+ def reward_func(completions, **kwargs):
49
+ # Your reward function for multimodal reasoning
50
+ return [compute_reward(c) for c in completions]
51
+
52
+
53
+ # PAPO-G
54
+ config = PAPOConfig(
55
+ loss_type="grpo", # Use GRPO as base
56
+ perception_loss_weight=0.1,
57
+ mask_ratio=0.3,
58
+ )
59
+
60
+ # PAPO-G
61
+ config = PAPOConfig(
62
+ loss_type="dapo", # Use DAPO as base
63
+ perception_loss_weight=0.1,
64
+ mask_ratio=0.3,
65
+ )
66
+
67
+ trainer = PAPOTrainer(
68
+ model="Qwen/Qwen2-VL-2B-Instruct",
69
+ reward_funcs=reward_func,
70
+ args=config,
71
+ train_dataset=dataset,
72
+ )
73
+
74
+ trainer.train()
75
+ ```
76
+
77
+ Args:
78
+ model (`Union[str, PreTrainedModel]`):
79
+ Model to be trained (must be a vision-language model).
80
+ reward_funcs (`Union[RewardFunc, list[RewardFunc]]`):
81
+ Reward functions for computing rewards (same as GRPO).
82
+ args ([`PAPOConfig`], *optional*, defaults to `None`):
83
+ Configuration for this trainer. If `None`, a default configuration is used.
84
+ train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
85
+ Dataset to use for training. Must include "prompt" and "image" columns.
86
+ eval_dataset: Same requirements as train_dataset.
87
+ processing_class: Processing class (tokenizer/processor) for the model.
88
+ reward_processing_classes: Processing classes for reward models.
89
+ callbacks: Training callbacks.
90
+ optimizers: Optimizer and scheduler tuple.
91
+ peft_config: PEFT configuration if using parameter-efficient fine-tuning.
92
+ """
93
+
94
+ _tag_names = ["trl", "papo"]
95
+ _name = "PAPO"
96
+ _paper = {
97
+ "title": "Perception-Aware Policy Optimization for Multimodal Reasoning",
98
+ "id": "2507.06448",
99
+ # docstyle-ignore
100
+ "citation": textwrap.dedent(
101
+ """\
102
+ @misc{wang2025perceptionawarepolicyoptimizationmultimodal,
103
+ title = {{Perception-Aware Policy Optimization for Multimodal Reasoning}},
104
+ author = {Zhenhailong Wang and Xuehang Guo and Sofia Stoica and Haiyang Xu and Hongru Wang and Hyeonjeong Ha and Xiusi Chen and Yangyi Chen and Ming Yan and Fei Huang and Heng Ji},
105
+ year = 2025,
106
+ url = {https://arxiv.org/abs/2507.06448},
107
+ archivePrefix= {arXiv},
108
+ eprint = {2507.06448},
109
+ primaryClass = {cs.CL}
110
+ }"""
111
+ ),
112
+ }
113
+
114
+ def __init__(
115
+ self,
116
+ model: str | PreTrainedModel,
117
+ reward_funcs: RewardFunc | list[RewardFunc],
118
+ args: PAPOConfig | None = None,
119
+ train_dataset: Dataset | IterableDataset | None = None,
120
+ eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
121
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
122
+ reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None,
123
+ callbacks=None,
124
+ optimizers=(None, None),
125
+ peft_config=None,
126
+ ):
127
+ # Initialize with default PAPO config if not provided
128
+ if args is None:
129
+ model_name = model if isinstance(model, str) else model.config._name_or_path
130
+ model_name = model_name.split("/")[-1]
131
+ args = PAPOConfig(f"{model_name}-PAPO")
132
+
133
+ # Store PAPO-specific parameters
134
+ self.perception_loss_weight = args.perception_loss_weight
135
+ self.mask_ratio = args.mask_ratio
136
+ self.mask_type = args.mask_type
137
+ self.der_loss_weight1 = args.der_loss_weight1
138
+ self.der_loss_weight2 = args.der_loss_weight2
139
+
140
+ # Initialize parent GRPO trainer
141
+ super().__init__(
142
+ model=model,
143
+ reward_funcs=reward_funcs,
144
+ args=args,
145
+ train_dataset=train_dataset,
146
+ eval_dataset=eval_dataset,
147
+ processing_class=processing_class,
148
+ reward_processing_classes=reward_processing_classes,
149
+ callbacks=callbacks,
150
+ optimizers=optimizers,
151
+ peft_config=peft_config,
152
+ )
153
+
154
+ def _mask_image(self, pixel_values: torch.Tensor, mask_ratio: float = None) -> torch.Tensor:
155
+ """
156
+ Apply masking to image pixel values.
157
+
158
+ Args:
159
+ pixel_values: Image tensor of shape (B, C, H, W) or (B, N, C, H, W) for multi-image
160
+ mask_ratio: Ratio of image to mask (defaults to self.mask_ratio)
161
+
162
+ Returns:
163
+ Masked pixel values tensor
164
+ """
165
+ if mask_ratio is None:
166
+ mask_ratio = self.mask_ratio
167
+
168
+ masked_pixel_values = pixel_values.clone()
169
+
170
+ if self.mask_type == "random":
171
+ # Random pixel masking
172
+ mask = torch.rand_like(pixel_values) > mask_ratio
173
+ masked_pixel_values = masked_pixel_values * mask
174
+
175
+ elif self.mask_type == "patch":
176
+ # Patch-based masking (mask contiguous regions)
177
+ B = pixel_values.shape[0]
178
+ if pixel_values.ndim == 4: # (B, C, H, W)
179
+ C, H, W = pixel_values.shape[1:]
180
+ for i in range(B):
181
+ # Calculate patch size to mask
182
+ patch_h = int(H * mask_ratio**0.5)
183
+ patch_w = int(W * mask_ratio**0.5)
184
+ # Random starting position
185
+ start_h = random.randint(0, max(0, H - patch_h))
186
+ start_w = random.randint(0, max(0, W - patch_w))
187
+ # Apply mask
188
+ masked_pixel_values[i, :, start_h : start_h + patch_h, start_w : start_w + patch_w] = 0
189
+
190
+ elif pixel_values.ndim == 5: # (B, N, C, H, W) for multi-image
191
+ N, C, H, W = pixel_values.shape[1:]
192
+ for i in range(B):
193
+ for n in range(N):
194
+ patch_h = int(H * mask_ratio**0.5)
195
+ patch_w = int(W * mask_ratio**0.5)
196
+ start_h = random.randint(0, max(0, H - patch_h))
197
+ start_w = random.randint(0, max(0, W - patch_w))
198
+ masked_pixel_values[i, n, :, start_h : start_h + patch_h, start_w : start_w + patch_w] = 0
199
+
200
+ elif self.mask_type == "grid":
201
+ # Grid-based masking (mask regular grid cells)
202
+ if pixel_values.ndim == 4:
203
+ C, H, W = pixel_values.shape[1:]
204
+ grid_size = int((1 / mask_ratio) ** 0.5)
205
+ cell_h, cell_w = H // grid_size, W // grid_size
206
+
207
+ for i in range(grid_size):
208
+ for j in range(grid_size):
209
+ if random.random() < mask_ratio:
210
+ masked_pixel_values[:, :, i * cell_h : (i + 1) * cell_h, j * cell_w : (j + 1) * cell_w] = 0
211
+
212
+ return masked_pixel_values
213
+
214
+ def _compute_loss(self, model, inputs):
215
+ # >>> 1. GRPO loss
216
+ # Compute the per-token log probabilities for the model
217
+ prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
218
+ completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
219
+ input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
220
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
221
+ logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
222
+
223
+ # Compute the per_token_logps and the entropy at each position in the completion
224
+ per_token_logps, entropies = self._get_per_token_logps_and_entropies(
225
+ model,
226
+ input_ids,
227
+ attention_mask,
228
+ logits_to_keep,
229
+ compute_entropy=True,
230
+ pixel_values=inputs.get("pixel_values"),
231
+ image_grid_thw=inputs.get("image_grid_thw"),
232
+ num_images=inputs.get("num_images"),
233
+ pixel_attention_mask=inputs.get("pixel_attention_mask"),
234
+ image_sizes=inputs.get("image_sizes"),
235
+ )
236
+
237
+ if self.top_entropy_quantile < 1.0:
238
+ entropy_mask = self.get_high_entropy_mask(entropies, completion_mask, 1 - self.top_entropy_quantile)
239
+ else:
240
+ entropy_mask = None
241
+
242
+ # Compute the KL divergence between the model and the reference model
243
+ if self.beta != 0.0:
244
+ ref_per_token_logps = inputs["ref_per_token_logps"]
245
+ per_token_kl = (
246
+ torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
247
+ )
248
+
249
+ # Compute the loss
250
+ advantages = inputs["advantages"]
251
+ # When using num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps
252
+ # old_per_token_logps == per_token_logps, so we can skip it's computation
253
+ # (see _generate_and_score_completions) and use per_token_logps.detach() instead.
254
+ old_per_token_logps = inputs.get("old_per_token_logps")
255
+ old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps
256
+
257
+ log_ratio = per_token_logps - old_per_token_logps
258
+ if self.importance_sampling_level == "token":
259
+ log_importance_weights = log_ratio
260
+ elif self.importance_sampling_level == "sequence":
261
+ log_importance_weights = (log_ratio * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)
262
+ log_importance_weights = log_importance_weights.unsqueeze(-1)
263
+ else:
264
+ raise ValueError(
265
+ f"Unknown importance sampling level: {self.importance_sampling_level}. Possible values are 'token' "
266
+ "and 'sequence'."
267
+ )
268
+ # From here, log_importance_weights (and all subsequent tensors, coef_1, coef_2, etc.) shape depends on
269
+ # importance_sampling_level: "token" level: (B, T); "sequence" level: (B, 1)
270
+
271
+ coef_1 = torch.exp(log_importance_weights)
272
+ coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
273
+
274
+ # Two-sided clipping
275
+ if self.args.delta is not None:
276
+ coef_1 = torch.clamp(coef_1, max=self.args.delta)
277
+
278
+ per_token_loss1 = coef_1 * advantages.unsqueeze(1)
279
+ per_token_loss2 = coef_2 * advantages.unsqueeze(1)
280
+ per_token_loss = -torch.min(per_token_loss1, per_token_loss2)
281
+ if entropy_mask is not None:
282
+ per_token_loss = per_token_loss * entropy_mask
283
+ if self.beta != 0.0:
284
+ per_token_loss = per_token_loss + self.beta * per_token_kl
285
+
286
+ if self.loss_type == "grpo":
287
+ loss = ((per_token_loss * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)).mean()
288
+ loss = loss / self.current_gradient_accumulation_steps
289
+ elif self.loss_type == "dapo":
290
+ normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes
291
+ loss = (per_token_loss * completion_mask).sum() / normalizer
292
+ else:
293
+ raise ValueError(f"Unknown loss type: {self.loss_type}")
294
+ # >>> 2. Implicit Perception Loss
295
+ inputs["pixel_values"] = self._mask_image(inputs["pixel_values"], self.mask_ratio)
296
+ mask_img_per_token_logps, mask_img_entropies = self._get_per_token_logps_and_entropies(
297
+ model,
298
+ input_ids,
299
+ attention_mask,
300
+ logits_to_keep,
301
+ compute_entropy=True,
302
+ pixel_values=inputs.get("pixel_values"),
303
+ image_grid_thw=inputs.get("image_grid_thw"),
304
+ num_images=inputs.get("num_images"),
305
+ pixel_attention_mask=inputs.get("pixel_attention_mask"),
306
+ image_sizes=inputs.get("image_sizes"),
307
+ )
308
+ perception_kl = (
309
+ torch.exp(mask_img_per_token_logps - per_token_logps) - (mask_img_per_token_logps - per_token_logps) - 1
310
+ )
311
+ perception_kl = torch.clamp(perception_kl, min=0.0, max=0.2)
312
+ perception_loss = self.perception_loss_weight * perception_kl
313
+
314
+ # >>> 3. Double Entropy Loss
315
+ der_loss = self.der_loss_weight1 * entropies + self.der_loss_weight2 * mask_img_entropies
316
+
317
+ # PAPO Loss
318
+ loss = (loss - perception_loss + der_loss).mean()
319
+ # Log the metrics
320
+ mode = "train" if self.model.training else "eval"
321
+
322
+ completion_token_count = completion_mask.sum().clamp(min=1.0)
323
+
324
+ def masked_batch_mean(x):
325
+ if x.shape[1] == 1: # when importance_sampling_level == "sequence"
326
+ return x.mean()
327
+ else:
328
+ return (x * completion_mask).sum() / completion_token_count
329
+
330
+ if self.beta != 0.0:
331
+ mean_kl = masked_batch_mean(per_token_kl)
332
+ self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
333
+
334
+ mean_entropy = masked_batch_mean(entropies)
335
+ self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item())
336
+
337
+ # Compute the clipped probability ratios
338
+ is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages.unsqueeze(1) < 0)
339
+ is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages.unsqueeze(1) > 0)
340
+ is_region_clipped = is_low_clipped | is_high_clipped
341
+
342
+ low_clip = masked_batch_mean(is_low_clipped.float())
343
+ high_clip = masked_batch_mean(is_high_clipped.float())
344
+ clip_ratio = masked_batch_mean(is_region_clipped.float())
345
+
346
+ gathered_low_clip = self.accelerator.gather(low_clip)
347
+ self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item())
348
+ self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item())
349
+ gathered_high_clip = self.accelerator.gather(high_clip)
350
+ self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item())
351
+ self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item())
352
+ gathered_clip_ratio = self.accelerator.gather(clip_ratio)
353
+ self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item())
354
+ return loss
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/ppo/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .modeling_value_head import (
16
+ AutoModelForCausalLMWithValueHead,
17
+ AutoModelForSeq2SeqLMWithValueHead,
18
+ PreTrainedModelWrapper,
19
+ )
20
+ from .ppo_config import PPOConfig
21
+ from .ppo_trainer import PPOTrainer
22
+
23
+
24
+ __all__ = [
25
+ "AutoModelForCausalLMWithValueHead",
26
+ "AutoModelForSeq2SeqLMWithValueHead",
27
+ "PreTrainedModelWrapper",
28
+ "PPOConfig",
29
+ "PPOTrainer",
30
+ ]
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/ppo/modeling_value_head.py ADDED
@@ -0,0 +1,1007 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 json
16
+ import logging
17
+ import os
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 (
31
+ AutoModelForCausalLM,
32
+ AutoModelForSeq2SeqLM,
33
+ PreTrainedModel,
34
+ is_torch_npu_available,
35
+ is_torch_xpu_available,
36
+ )
37
+ from transformers.utils import is_peft_available
38
+
39
+
40
+ if is_peft_available():
41
+ from peft import (
42
+ PeftConfig,
43
+ PeftModel,
44
+ PeftModelForCausalLM,
45
+ PeftModelForSeq2SeqLM,
46
+ PromptLearningConfig,
47
+ get_peft_model,
48
+ prepare_model_for_kbit_training,
49
+ )
50
+
51
+
52
+ class PreTrainedModelWrapper(nn.Module):
53
+ """
54
+ Wrapper for a [`~transformers.PreTrainedModel`] implemented as a standard PyTorch [`torch.nn.Module`].
55
+
56
+ This class provides a compatibility layer that preserves the key attributes and methods of the original
57
+ [`~transformers.PreTrainedModel`], while exposing a uniform interface consistent with PyTorch modules. It enables
58
+ seamless integration of pretrained Transformer models into custom training, evaluation, or inference workflows.
59
+
60
+ Attributes:
61
+ pretrained_model ([`~transformers.PreTrainedModel`]):
62
+ The model to be wrapped.
63
+ parent_class ([`~transformers.PreTrainedModel`]):
64
+ The parent class of the model to be wrapped.
65
+ supported_args (`list`):
66
+ The list of arguments that are supported by the wrapper class.
67
+ """
68
+
69
+ transformers_parent_class = None
70
+ supported_args = None
71
+ supported_modules = ("v_head",)
72
+ supported_rm_modules = ("score",)
73
+ supported_pretrained_model_architectures = (
74
+ (PreTrainedModel)
75
+ if not is_peft_available()
76
+ else (PreTrainedModel, PeftModelForCausalLM, PeftModelForSeq2SeqLM)
77
+ )
78
+
79
+ def __init__(
80
+ self, pretrained_model=None, score_module=None, supports_rm_adapter=False, rm_adapter_name=None, **kwargs
81
+ ):
82
+ super().__init__()
83
+ self.pretrained_model = pretrained_model
84
+
85
+ self.config = pretrained_model.config
86
+ self.prepare_inputs_for_generation = pretrained_model.prepare_inputs_for_generation
87
+ self.is_loaded_in_8bit = getattr(pretrained_model, "is_loaded_in_8bit", False)
88
+ self.is_loaded_in_4bit = getattr(pretrained_model, "is_loaded_in_4bit", False)
89
+ self.is_sequential_parallel = False
90
+
91
+ if hasattr(pretrained_model, "gradient_checkpointing_disable"):
92
+ self.gradient_checkpointing_disable = pretrained_model.gradient_checkpointing_disable
93
+
94
+ if hasattr(pretrained_model, "gradient_checkpointing_enable"):
95
+ self.gradient_checkpointing_enable = pretrained_model.gradient_checkpointing_enable
96
+
97
+ if hasattr(pretrained_model, "enable_input_require_grads"):
98
+ self.enable_input_require_grads = pretrained_model.enable_input_require_grads
99
+
100
+ self.supports_rm_adapter = supports_rm_adapter
101
+ self.rm_adapter_name = rm_adapter_name
102
+ self.policy_adapter_name = "default"
103
+ if score_module is not None:
104
+ self.score = score_module
105
+
106
+ @classmethod
107
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
108
+ r"""
109
+ Instantiates a new model from a pretrained model from `transformers`. The pretrained model is loaded using the
110
+ `from_pretrained` method of the [`~transformers.PreTrainedModel`] class. The arguments that are specific to the
111
+ [`~transformers.PreTrainedModel`] class are passed along this method and filtered out from the `kwargs`
112
+ argument.
113
+
114
+ Args:
115
+ pretrained_model_name_or_path (`str` or [`~transformers.PreTrainedModel`]):
116
+ The path to the pretrained model or its name.
117
+ *model_args (`list`, *optional*):
118
+ Additional positional arguments passed along to the underlying model's `from_pretrained` method.
119
+ **kwargs (`dict`, *optional*):
120
+ Additional keyword arguments passed along to the underlying model's `from_pretrained` method. We also
121
+ pre-process the kwargs to extract the arguments that are specific to the
122
+ [`~transformers.PreTrainedModel`] class and the arguments that are specific to trl models. The kwargs
123
+ also support `prepare_model_for_kbit_training` arguments from `peft` library.
124
+ """
125
+ if kwargs is not None:
126
+ peft_config = kwargs.pop("peft_config", None)
127
+ reward_adapter = kwargs.pop("reward_adapter", None)
128
+ reward_adapter_name = kwargs.pop("reward_adapter_name", "reward_adapter")
129
+ is_trainable = kwargs.pop("is_trainable", False)
130
+ trl_model_args, pretrained_kwargs, peft_quantization_kwargs = cls._split_kwargs(kwargs)
131
+ token = pretrained_kwargs.get("token", None)
132
+ else:
133
+ peft_config = None
134
+ is_trainable = False
135
+ trl_model_args = {}
136
+ pretrained_kwargs = {}
137
+ peft_quantization_kwargs = {}
138
+ token = None
139
+
140
+ if reward_adapter is not None and not isinstance(reward_adapter, str):
141
+ raise ValueError(
142
+ "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
+
145
+ is_peft_model = False
146
+
147
+ current_device = cls._get_current_device()
148
+ if isinstance(pretrained_model_name_or_path, str):
149
+ quantization_config = pretrained_kwargs.get("quantization_config", None)
150
+ if quantization_config is not None:
151
+ is_loaded_in_8bit = getattr(quantization_config, "load_in_8bit", False)
152
+ is_loaded_in_4bit = getattr(quantization_config, "load_in_4bit", False)
153
+ else:
154
+ is_loaded_in_8bit = pretrained_kwargs["load_in_8bit"] if "load_in_8bit" in pretrained_kwargs else False
155
+ is_loaded_in_4bit = pretrained_kwargs["load_in_4bit"] if "load_in_4bit" in pretrained_kwargs else False
156
+ else:
157
+ is_loaded_in_8bit = getattr(pretrained_model_name_or_path, "is_loaded_in_8bit", False)
158
+ is_loaded_in_4bit = getattr(pretrained_model_name_or_path, "is_loaded_in_4bit", False)
159
+
160
+ if (is_loaded_in_8bit or is_loaded_in_4bit) and "device_map" not in pretrained_kwargs:
161
+ # warn users
162
+ logging.warning(
163
+ "The `device_map` argument is not provided. We will override the device_map argument."
164
+ " to set the entire"
165
+ " model on the current device. If you want to set the model on multiple devices, please provide"
166
+ " a custom `device_map` argument."
167
+ )
168
+ pretrained_kwargs["device_map"] = {"": current_device}
169
+
170
+ if is_peft_available() and peft_config is not None and not isinstance(peft_config, PeftConfig):
171
+ raise ValueError("The `peft_config` argument should be an instance of `peft.PeftConfig` class.")
172
+
173
+ # First, load the pre-trained model using the parent-class
174
+ # either `AutoModelForCausalLM` or `AutoModelForSeq2SeqLM`
175
+ if isinstance(pretrained_model_name_or_path, str):
176
+ if is_peft_available():
177
+ try:
178
+ # If there is a trained peft adapter in the hub, load its config.
179
+ remote_adapter_config = hf_hub_download(
180
+ pretrained_model_name_or_path,
181
+ "adapter_config.json",
182
+ token=token,
183
+ )
184
+ except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError):
185
+ remote_adapter_config = None
186
+ else:
187
+ remote_adapter_config = None
188
+
189
+ local_adapter_present = os.path.exists(os.path.join(pretrained_model_name_or_path, "adapter_config.json"))
190
+
191
+ if (local_adapter_present or remote_adapter_config is not None) and is_peft_available():
192
+ if peft_config is not None:
193
+ logging.warning(
194
+ "`peft_config` argument ignored since a peft config file was found in "
195
+ f"{pretrained_model_name_or_path}"
196
+ )
197
+
198
+ # Load the trained peft adapter config
199
+ if local_adapter_present:
200
+ trained_adapter_config = PeftConfig.from_pretrained(pretrained_model_name_or_path)
201
+ else:
202
+ remote_adapter_dir = os.path.dirname(remote_adapter_config)
203
+ trained_adapter_config = PeftConfig.from_pretrained(remote_adapter_dir)
204
+
205
+ # Load the pretrained base model
206
+ pretrained_model = cls.transformers_parent_class.from_pretrained(
207
+ trained_adapter_config.base_model_name_or_path, *model_args, **pretrained_kwargs
208
+ )
209
+
210
+ # Wrap the pretrained model with the trained peft adapter
211
+ pretrained_model = PeftModel.from_pretrained(
212
+ pretrained_model, pretrained_model_name_or_path, is_trainable=is_trainable, token=token
213
+ )
214
+ logging.info("Trained peft adapter loaded")
215
+ else:
216
+ pretrained_model = cls.transformers_parent_class.from_pretrained(
217
+ pretrained_model_name_or_path, *model_args, **pretrained_kwargs
218
+ )
219
+
220
+ if peft_config is not None:
221
+ # Initialize a new peft adapter with the given config
222
+ if is_loaded_in_8bit or is_loaded_in_4bit:
223
+ pretrained_model = prepare_model_for_kbit_training(
224
+ pretrained_model,
225
+ **peft_quantization_kwargs,
226
+ )
227
+ pretrained_model = get_peft_model(pretrained_model, peft_config)
228
+ logging.info("peft adapter initialised")
229
+
230
+ elif isinstance(pretrained_model_name_or_path, cls.supported_pretrained_model_architectures):
231
+ pretrained_model = pretrained_model_name_or_path
232
+
233
+ if peft_config is not None and isinstance(pretrained_model, PreTrainedModel):
234
+ # Initialize a new peft adapter with the given config
235
+ if is_loaded_in_8bit or is_loaded_in_4bit:
236
+ pretrained_model = prepare_model_for_kbit_training(
237
+ pretrained_model,
238
+ **peft_quantization_kwargs,
239
+ )
240
+ pretrained_model = get_peft_model(pretrained_model, peft_config)
241
+ logging.info("peft adapter initialised")
242
+ else:
243
+ raise ValueError(
244
+ "pretrained_model_name_or_path should be a string or a PreTrainedModel, "
245
+ f"but is {type(pretrained_model_name_or_path)}"
246
+ )
247
+
248
+ if is_peft_available():
249
+ if isinstance(pretrained_model, PeftModel):
250
+ is_peft_model = True
251
+ # for backward compatibility
252
+ if hasattr(pretrained_model, "active_peft_config") and isinstance(
253
+ pretrained_model.active_peft_config, PromptLearningConfig
254
+ ):
255
+ raise ValueError("PromptLearningConfig is not supported for PPO training.")
256
+
257
+ # Add reward modeling adapter if specified
258
+ if not is_peft_model and reward_adapter is not None:
259
+ raise ValueError("reward_adapter can only be used with a PeftModel. ")
260
+ elif is_peft_model and reward_adapter is not None:
261
+ score_module = cls.add_and_load_reward_modeling_adapter(
262
+ pretrained_model, reward_adapter, reward_adapter_name, token=token
263
+ )
264
+ multi_adapter_args = {
265
+ "score_module": score_module,
266
+ "supports_rm_adapter": True,
267
+ "rm_adapter_name": reward_adapter_name,
268
+ }
269
+ else:
270
+ multi_adapter_args = {"supports_rm_adapter": False}
271
+
272
+ # Then, create the full model by instantiating the wrapper class
273
+ model = cls(pretrained_model, **multi_adapter_args, **trl_model_args)
274
+
275
+ # if resume_training, load the state_dict again - this is ok since the
276
+ # state_dict is removed from the model after loading it.
277
+ is_resuming_training = True
278
+ if isinstance(pretrained_model_name_or_path, str):
279
+ safe_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors")
280
+ filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin")
281
+
282
+ sharded_index_filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin.index.json")
283
+ safe_sharded_index_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors.index.json")
284
+ is_sharded = False
285
+ use_safe = os.path.exists(safe_filename)
286
+
287
+ if not (os.path.exists(filename) or os.path.exists(safe_filename)):
288
+ # Try with `pytorch_model.bin`
289
+ filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub(
290
+ pretrained_model,
291
+ pretrained_model_name_or_path,
292
+ sharded_index_filename,
293
+ token=token,
294
+ )
295
+ # Try with safetensors
296
+ if filename is None and files_to_download is None:
297
+ safe_filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub(
298
+ pretrained_model,
299
+ pretrained_model_name_or_path,
300
+ safe_sharded_index_filename,
301
+ token=token,
302
+ model_name="model.safetensors",
303
+ model_index_name="model.safetensors.index.json",
304
+ )
305
+ use_safe = True
306
+ else:
307
+ use_safe = False
308
+
309
+ loading_func = safe_load_file if use_safe else torch.load
310
+ load_kwargs = {} if use_safe else {"map_location": "cpu", "weights_only": True}
311
+
312
+ if is_resuming_training:
313
+ if is_sharded:
314
+ # download each file and add it to the state_dict
315
+ state_dict = {}
316
+
317
+ for shard_file in files_to_download:
318
+ filename = hf_hub_download(
319
+ pretrained_model_name_or_path,
320
+ shard_file,
321
+ token=token,
322
+ )
323
+ state_dict.update(loading_func(filename, **load_kwargs))
324
+ else:
325
+ state_dict = loading_func(filename if not use_safe else safe_filename, **load_kwargs)
326
+
327
+ else:
328
+ state_dict = pretrained_model_name_or_path.state_dict()
329
+
330
+ model.is_peft_model = is_peft_model
331
+ model.current_device = current_device
332
+
333
+ if is_resuming_training:
334
+ model.post_init(state_dict=state_dict)
335
+
336
+ return model
337
+
338
+ @classmethod
339
+ def _get_checkpoint_from_hub(
340
+ cls,
341
+ pretrained_model,
342
+ pretrained_model_name_or_path,
343
+ index_filename,
344
+ token=None,
345
+ model_name="pytorch_model.bin",
346
+ model_index_name="pytorch_model.bin.index.json",
347
+ ):
348
+ files_to_download = None
349
+ filename = None
350
+ is_resuming_training = True
351
+ is_sharded = False
352
+
353
+ try:
354
+ filename = hf_hub_download(
355
+ pretrained_model_name_or_path,
356
+ model_name,
357
+ token=token,
358
+ )
359
+ # sharded
360
+ except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError):
361
+ if os.path.exists(index_filename):
362
+ index_file_name = index_filename
363
+ else:
364
+ try:
365
+ index_file_name = hf_hub_download(
366
+ pretrained_model_name_or_path,
367
+ model_index_name,
368
+ token=token,
369
+ )
370
+ except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError):
371
+ # not continue training, do not have v_head weight
372
+ is_resuming_training = False
373
+ logging.warning(
374
+ f"A {type(pretrained_model)} model is loaded from '{pretrained_model_name_or_path}', "
375
+ f"and no v_head weight is found. This IS expected if you are not resuming PPO training."
376
+ )
377
+ # load json
378
+ if is_resuming_training:
379
+ with open(index_file_name) as f:
380
+ index = json.load(f)
381
+ # check filename with `v_head` or any known extra module:
382
+ files_to_download = set()
383
+ for k, v in index["weight_map"].items():
384
+ if any(module in k for module in cls.supported_modules):
385
+ files_to_download.add(v)
386
+ is_sharded = True
387
+
388
+ return filename, files_to_download, is_sharded, is_resuming_training
389
+
390
+ @classmethod
391
+ def _get_current_device(cls):
392
+ r"""
393
+ Get the current device. For GPU & XPU, we return the local process index using the `accelerate.PartialState`
394
+ object to handle corner cases when running scripts in distributed environments.
395
+
396
+ Returns:
397
+ current_device (`int | str`):
398
+ The current device.
399
+ """
400
+ state = PartialState()
401
+ if torch.cuda.is_available() or is_torch_xpu_available():
402
+ return state.local_process_index
403
+ elif is_torch_npu_available():
404
+ return f"npu:{state.local_process_index}"
405
+ else:
406
+ return "cpu"
407
+
408
+ @classmethod
409
+ def _split_kwargs(cls, kwargs):
410
+ """
411
+ Separate the kwargs from the arguments that we support inside `supported_args` and the ones that we don't.
412
+ """
413
+ check_peft_kwargs = False
414
+
415
+ if is_peft_available():
416
+ from peft import prepare_model_for_kbit_training
417
+
418
+ check_peft_kwargs = True
419
+
420
+ supported_kwargs = {}
421
+ unsupported_kwargs = {}
422
+ peft_kwargs = {}
423
+
424
+ for key, value in kwargs.items():
425
+ if key in cls.supported_args:
426
+ supported_kwargs[key] = value
427
+ else:
428
+ unsupported_kwargs[key] = value
429
+
430
+ if check_peft_kwargs:
431
+ if key in prepare_model_for_kbit_training.__code__.co_varnames:
432
+ peft_kwargs[key] = value
433
+ if key in unsupported_kwargs:
434
+ unsupported_kwargs.pop(key)
435
+
436
+ return supported_kwargs, unsupported_kwargs, peft_kwargs
437
+
438
+ @classmethod
439
+ def add_and_load_reward_modeling_adapter(
440
+ cls, pretrained_model, adapter_model_id, adapter_name="reward_model_adapter", token=None
441
+ ):
442
+ r"""
443
+ Add and load a reward modeling adapter. This method can only be used if the model is a `PeftModel` and if you
444
+ have initialized the model with the `reward_modeling_adapter_id` argument, pointing to the id of the reward
445
+ modeling adapter. The latest needs also to contain the score head in order to produce the reward.
446
+ """
447
+ pretrained_model.load_adapter(adapter_model_id, adapter_name, is_trainable=False)
448
+ pretrained_model.train()
449
+
450
+ filename = os.path.join(adapter_model_id, "adapter_model.bin")
451
+ safe_loading = False
452
+ if not os.path.exists(filename):
453
+ try:
454
+ local_filename = hf_hub_download(
455
+ adapter_model_id,
456
+ "adapter_model.bin",
457
+ token=token,
458
+ )
459
+ except Exception:
460
+ filename = os.path.join(adapter_model_id, "adapter_model.safetensors")
461
+ safe_loading = True
462
+ if not os.path.exists(filename):
463
+ try:
464
+ local_filename = hf_hub_download(
465
+ adapter_model_id,
466
+ "adapter_model.safetensors",
467
+ token=token,
468
+ )
469
+ except Exception as exc:
470
+ raise ValueError(
471
+ "Could not find adapter model in the Hub, make sure you have the correct adapter model id."
472
+ ) from exc
473
+ else:
474
+ local_filename = filename
475
+ else:
476
+ local_filename = filename
477
+
478
+ loading_func = safe_load_file if safe_loading else torch.load
479
+ load_kwargs = {} if safe_loading else {"map_location": "cpu", "weights_only": True}
480
+
481
+ adapter_state_dict = loading_func(local_filename, **load_kwargs)
482
+
483
+ for score_name_candidate in cls.supported_rm_modules:
484
+ if any(score_name_candidate in name for name in adapter_state_dict.keys()):
485
+ score_name = score_name_candidate
486
+ # we have found the correct head name and can break
487
+ break
488
+
489
+ score_dict = {}
490
+
491
+ for name, param in adapter_state_dict.items():
492
+ if score_name in name:
493
+ key_name = ".".join(name.split(".")[-1:])
494
+ score_dict[key_name] = param.to(cls._get_current_device())
495
+
496
+ num_labels, hidden_dim = score_dict["weight"].shape
497
+ has_bias = any("bias" in name for name in adapter_state_dict.keys())
498
+
499
+ score = nn.Linear(hidden_dim, num_labels, bias=has_bias).to(
500
+ device=cls._get_current_device(),
501
+ dtype=pretrained_model.dtype,
502
+ )
503
+ score.load_state_dict(score_dict)
504
+ for param in score.parameters():
505
+ param.requires_grad = False
506
+
507
+ return score
508
+
509
+ def push_to_hub(self, *args, **kwargs):
510
+ r"""
511
+ Push the pretrained model to the hub. This method is a wrapper around
512
+ [`~transformers.PreTrainedModel.push_to_hub`]. Please refer to the documentation of
513
+ [`~transformers.PreTrainedModel.push_to_hub`] for more information.
514
+
515
+ Args:
516
+ *args (`list`, *optional*):
517
+ Positional arguments passed along to the underlying model's `push_to_hub` method.
518
+ **kwargs (`dict`, *optional*):
519
+ Keyword arguments passed along to the underlying model's `push_to_hub` method.
520
+ """
521
+ raise NotImplementedError
522
+
523
+ def save_pretrained(self, *args, **kwargs):
524
+ r"""
525
+ Save the pretrained model to a directory. This method is a wrapper around
526
+ [`~transformers.PreTrainedModel.save_pretrained`]. Please refer to the documentation of
527
+ [`~transformers.PreTrainedModel.save_pretrained`] for more information.
528
+
529
+ Args:
530
+ *args (`list`, *optional*):
531
+ Positional arguments passed along to the underlying model's `save_pretrained` method.
532
+ **kwargs (`dict`, *optional*):
533
+ Keyword arguments passed along to the underlying model's `save_pretrained` method.
534
+ """
535
+ state_dict = kwargs.get("state_dict")
536
+ if state_dict is None:
537
+ state_dict = self.state_dict()
538
+ kwargs["state_dict"] = state_dict
539
+
540
+ # if it is a peft model only save the `v_head` state_dict and
541
+ # pop the `state_dict` from the kwargs to avoid silent bugs with `peft`
542
+ if self.is_peft_model:
543
+ save_path = args[0]
544
+ save_path = os.path.join(save_path, "pytorch_model.bin")
545
+ torch.save(state_dict, save_path)
546
+ _ = kwargs.pop("state_dict", None)
547
+
548
+ return self.pretrained_model.save_pretrained(*args, **kwargs)
549
+
550
+ def state_dict(self, *args, **kwargs):
551
+ r"""
552
+ Return the state_dict of the pretrained model.
553
+ """
554
+ raise NotImplementedError
555
+
556
+ def post_init(self, *args, **kwargs):
557
+ r"""
558
+ Post initialization method. This method is called after the model is instantiated and loaded from a checkpoint.
559
+ It can be used to perform additional operations such as loading the state_dict.
560
+ """
561
+ raise NotImplementedError
562
+
563
+ def compute_reward_score(self, input_ids, attention_mask=None, **kwargs):
564
+ r"""
565
+ Computes the reward score for a given input. The method has first to enable the adapter and then compute the
566
+ reward score. After that the model disables the reward modeling adapter and enables the default ppo adapter
567
+ again.
568
+ """
569
+ if not self.supports_rm_adapter:
570
+ raise ValueError("This model does not support reward modeling adapter.")
571
+
572
+ # enable rm adapter
573
+ self.pretrained_model.set_adapter(self.rm_adapter_name)
574
+ self.pretrained_model.eval()
575
+
576
+ with torch.no_grad():
577
+ base_model_output = self.pretrained_model(
578
+ input_ids=input_ids,
579
+ attention_mask=attention_mask,
580
+ output_hidden_states=True,
581
+ return_dict=True,
582
+ **kwargs,
583
+ )
584
+
585
+ last_hidden_states = base_model_output.hidden_states[-1]
586
+ scores = self.score(last_hidden_states)
587
+
588
+ self.pretrained_model.set_adapter(self.policy_adapter_name)
589
+ self.pretrained_model.eval()
590
+
591
+ return scores
592
+
593
+
594
+ class ValueHead(nn.Module):
595
+ r"""
596
+ The ValueHead class implements a head for GPT2 that returns a scalar for each output token.
597
+ """
598
+
599
+ def __init__(self, config, **kwargs):
600
+ super().__init__()
601
+ if not hasattr(config, "summary_dropout_prob"):
602
+ summary_dropout_prob = kwargs.pop("summary_dropout_prob", 0.1)
603
+ else:
604
+ summary_dropout_prob = config.summary_dropout_prob
605
+
606
+ self.dropout = nn.Dropout(summary_dropout_prob) if summary_dropout_prob else nn.Identity()
607
+
608
+ # some models such as OPT have a projection layer before the word embeddings - e.g. OPT-350m
609
+ if hasattr(config, "hidden_size"):
610
+ hidden_size = config.hidden_size
611
+ if hasattr(config, "word_embed_proj_dim"):
612
+ hidden_size = config.word_embed_proj_dim
613
+ elif hasattr(config, "is_encoder_decoder"):
614
+ if config.is_encoder_decoder and hasattr(config, "decoder"):
615
+ if hasattr(config.decoder, "hidden_size"):
616
+ hidden_size = config.decoder.hidden_size
617
+
618
+ self.summary = nn.Linear(hidden_size, 1)
619
+
620
+ self.flatten = nn.Flatten()
621
+
622
+ def forward(self, hidden_states):
623
+ output = self.dropout(hidden_states)
624
+
625
+ # For now force upcast in fp32 if needed. Let's keep the
626
+ # output in fp32 for numerical stability.
627
+ if output.dtype != self.summary.weight.dtype:
628
+ output = output.to(self.summary.weight.dtype)
629
+
630
+ output = self.summary(output)
631
+ return output
632
+
633
+
634
+ class AutoModelForCausalLMWithValueHead(PreTrainedModelWrapper):
635
+ """
636
+ An autoregressive model with a value head in addition to the language model head. This class inherits from
637
+ [`experimental.ppo.PreTrainedModelWrapper`] and wraps a [`~transformers.PreTrainedModel`] class. The wrapper class
638
+ supports classic functions such as `from_pretrained`, `push_to_hub` and `generate`. To call a method of the wrapped
639
+ model, simply manipulate the `pretrained_model` attribute of this class.
640
+
641
+ Class attributes:
642
+ - **transformers_parent_class** ([`~transformers.PreTrainedModel`]) -- The parent class of the wrapped model.
643
+ This
644
+ should be set to `transformers.AutoModelForCausalLM` for this class.
645
+ - **supported_args** (`tuple`) -- A tuple of strings that are used to identify the arguments that are supported
646
+ by the [`ValueHead`] class. Currently, the supported args are:
647
+ - **summary_dropout_prob** (`float`, `optional`, defaults to `None`) -- The dropout probability for the
648
+ [`ValueHead`] class.
649
+ - **v_head_initializer_range** (`float`, `optional`, defaults to `0.2`) -- The initializer range for the
650
+ [`ValueHead`] if a specific initialization strategy is selected.
651
+ - **v_head_init_strategy** (`str`, `optional`, defaults to `None`) -- The initialization strategy for the
652
+ [`ValueHead`]. Currently, the supported strategies are:
653
+ - **`None`** -- Initializes the weights of the [`ValueHead`] with a random distribution. This is the
654
+ default strategy.
655
+ - **"normal"** -- Initializes the weights of the [`ValueHead`] with a normal distribution.
656
+ """
657
+
658
+ transformers_parent_class = AutoModelForCausalLM
659
+ supported_args = (
660
+ "summary_dropout_prob",
661
+ "v_head_initializer_range",
662
+ "v_head_init_strategy",
663
+ )
664
+
665
+ def __init__(self, pretrained_model, **kwargs):
666
+ """
667
+ Initializes the model.
668
+
669
+ Args:
670
+ pretrained_model ([`~transformers.PreTrainedModel`]):
671
+ The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the
672
+ `AutoModelForCausalLM` class.
673
+ kwargs (`dict`, `optional`):
674
+ Additional keyword arguments, that are passed to the [`ValueHead`] class.
675
+ """
676
+ super().__init__(pretrained_model, **kwargs)
677
+ v_head_kwargs, _, _ = self._split_kwargs(kwargs)
678
+ self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs)
679
+ self._init_weights(**v_head_kwargs)
680
+
681
+ def _init_weights(self, **kwargs):
682
+ r"""
683
+ Initializes the weights of the value head. The default initialization strategy is random. Users can pass a
684
+ different initialization strategy by passing the `v_head_init_strategy` argument when calling
685
+ `.from_pretrained`. Supported strategies are:
686
+ - `normal`: initializes the weights with a normal distribution.
687
+
688
+ Args:
689
+ **kwargs (`dict`, `optional`):
690
+ Additional keyword arguments, that are passed to the [`ValueHead`] class. These arguments can contain
691
+ the `v_head_init_strategy` argument as well as the `v_head_initializer_range` argument.
692
+ """
693
+ initializer_range = kwargs.pop("v_head_initializer_range", 0.2)
694
+ # random init by default
695
+ init_strategy = kwargs.pop("v_head_init_strategy", None)
696
+ if init_strategy is None:
697
+ # do nothing
698
+ pass
699
+ elif init_strategy == "normal":
700
+ self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range)
701
+ self.v_head.summary.bias.data.zero_()
702
+
703
+ def forward(
704
+ self,
705
+ input_ids=None,
706
+ past_key_values=None,
707
+ attention_mask=None,
708
+ return_past_key_values=False,
709
+ **kwargs,
710
+ ):
711
+ r"""
712
+ Applies a forward pass to the wrapped model and returns the logits of the value head.
713
+
714
+ Args:
715
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
716
+ Indices of input sequence tokens in the vocabulary.
717
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, `optional`):
718
+ Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model
719
+ (see `past_key_values` input) to speed up sequential decoding.
720
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, `optional`):
721
+ Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
722
+ - 1 for tokens that are **not masked**,
723
+ - 0 for tokens that are **masked**.
724
+ return_past_key_values (bool): A flag indicating if the computed hidden-states should be returned.
725
+ kwargs (`dict`, `optional`):
726
+ Additional keyword arguments, that are passed to the wrapped model.
727
+ """
728
+ kwargs["output_hidden_states"] = True # this had already been set in the LORA / PEFT examples
729
+ kwargs["past_key_values"] = past_key_values
730
+
731
+ if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING":
732
+ kwargs.pop("past_key_values")
733
+
734
+ base_model_output = self.pretrained_model(
735
+ input_ids=input_ids,
736
+ attention_mask=attention_mask,
737
+ **kwargs,
738
+ )
739
+
740
+ last_hidden_state = base_model_output.hidden_states[-1]
741
+ lm_logits = base_model_output.logits
742
+ loss = base_model_output.loss
743
+
744
+ if last_hidden_state.device != self.v_head.summary.weight.device:
745
+ last_hidden_state = last_hidden_state.to(self.v_head.summary.weight.device)
746
+
747
+ value = self.v_head(last_hidden_state).squeeze(-1)
748
+
749
+ # force upcast in fp32 if logits are in half-precision
750
+ if lm_logits.dtype != torch.float32:
751
+ lm_logits = lm_logits.float()
752
+
753
+ if return_past_key_values:
754
+ return (lm_logits, loss, value, base_model_output.past_key_values)
755
+ else:
756
+ return (lm_logits, loss, value)
757
+
758
+ def generate(self, *args, **kwargs):
759
+ r"""
760
+ A simple wrapper around the `generate` method of the wrapped model. Please refer to the
761
+ [`generate`](https://huggingface.co/docs/transformers/internal/generation_utils) method of the wrapped model
762
+ for more information about the supported arguments.
763
+
764
+ Args:
765
+ *args (`list`, *optional*):
766
+ Positional arguments passed to the `generate` method of the wrapped model.
767
+ **kwargs (`dict`, *optional*):
768
+ Keyword arguments passed to the `generate` method of the wrapped model.
769
+ """
770
+ return self.pretrained_model.generate(*args, **kwargs)
771
+
772
+ def state_dict(self, *args, **kwargs):
773
+ r"""
774
+ Returns the state dictionary of the model. We add the state dictionary of the value head to the state
775
+ dictionary of the wrapped model by prepending the key with `v_head.`.
776
+ """
777
+ if not self.is_peft_model:
778
+ pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs)
779
+ else:
780
+ # if it is a peft model, only save the v_head
781
+ pretrained_model_state_dict = {}
782
+
783
+ v_head_state_dict = self.v_head.state_dict(*args, **kwargs)
784
+ for k, v in v_head_state_dict.items():
785
+ pretrained_model_state_dict[f"v_head.{k}"] = v
786
+ return pretrained_model_state_dict
787
+
788
+ def push_to_hub(self, *args, **kwargs):
789
+ self.pretrained_model.v_head = self.v_head
790
+
791
+ return self.pretrained_model.push_to_hub(*args, **kwargs)
792
+
793
+ def post_init(self, state_dict):
794
+ r"""
795
+ We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the
796
+ key with `v_head.`. This function removes the `v_head.` prefix from the keys of the value head state
797
+ dictionary.
798
+ """
799
+ for k in list(state_dict.keys()):
800
+ if "v_head." in k:
801
+ state_dict[k.replace("v_head.", "")] = state_dict.pop(k)
802
+ self.v_head.load_state_dict(state_dict, strict=False)
803
+ del state_dict
804
+
805
+ if hasattr(self.pretrained_model, "hf_device_map"):
806
+ if (
807
+ "cpu" in self.pretrained_model.hf_device_map.values()
808
+ or "disk" in self.pretrained_model.hf_device_map.values()
809
+ ):
810
+ raise ValueError(
811
+ "The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models."
812
+ )
813
+
814
+ first_device = list(set(self.pretrained_model.hf_device_map.values()))[0]
815
+ if isinstance(first_device, int):
816
+ if is_torch_npu_available():
817
+ first_device = f"npu:{first_device}"
818
+ elif is_torch_xpu_available():
819
+ first_device = f"xpu:{first_device}"
820
+ else:
821
+ first_device = f"cuda:{first_device}"
822
+ self.v_head = self.v_head.to(first_device)
823
+
824
+ def set_device_hook(module, input, outputs):
825
+ new_output = ()
826
+ for output in outputs:
827
+ if isinstance(output, torch.Tensor):
828
+ new_output += (output.to(first_device),)
829
+ else:
830
+ new_output += (output,)
831
+ return new_output
832
+
833
+ self.register_forward_hook(set_device_hook)
834
+
835
+ self.is_sequential_parallel = True
836
+
837
+
838
+ class AutoModelForSeq2SeqLMWithValueHead(PreTrainedModelWrapper):
839
+ """
840
+ A seq2seq model with a value head in addition to the language model head. This class inherits from
841
+ [`experimental.ppo.PreTrainedModelWrapper`] and wraps a [`~transformers.PreTrainedModel`] class. The wrapper class
842
+ supports classic functions such as `from_pretrained` and `push_to_hub` and also provides some additional
843
+ functionalities such as `generate`.
844
+
845
+ Args:
846
+ pretrained_model ([`~transformers.PreTrainedModel`]):
847
+ The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the
848
+ [`~transformers.AutoModelForSeq2SeqLM`] class.
849
+ kwargs:
850
+ Additional keyword arguments passed along to the [`ValueHead`] class.
851
+ """
852
+
853
+ transformers_parent_class = AutoModelForSeq2SeqLM
854
+ lm_head_namings = ["lm_head", "embed_out", "output_projection"]
855
+ supported_args = (
856
+ "summary_dropout_prob",
857
+ "v_head_initializer_range",
858
+ "v_head_init_strategy",
859
+ )
860
+
861
+ def __init__(self, pretrained_model, **kwargs):
862
+ super().__init__(pretrained_model, **kwargs)
863
+ v_head_kwargs, _, _ = self._split_kwargs(kwargs)
864
+ self.is_encoder_decoder = True
865
+
866
+ if not self._has_lm_head():
867
+ raise ValueError("The model does not have a language model head, please use a model that has one.")
868
+
869
+ self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs)
870
+
871
+ self._init_weights(**v_head_kwargs)
872
+
873
+ def _has_lm_head(self):
874
+ # check module names of all modules inside `pretrained_model` to find the language model head
875
+ for name, _module in self.pretrained_model.named_modules():
876
+ if any(attribute in name for attribute in self.lm_head_namings):
877
+ return True
878
+ return False
879
+
880
+ def post_init(self, state_dict):
881
+ r"""
882
+ We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the
883
+ key with `v_head.`. This function removes the `v_head.` prefix from the keys of the value head state
884
+ dictionary.
885
+ """
886
+ for k in list(state_dict.keys()):
887
+ if "v_head." in k:
888
+ state_dict[k.replace("v_head.", "")] = state_dict.pop(k)
889
+ self.v_head.load_state_dict(state_dict, strict=False)
890
+ del state_dict
891
+
892
+ if hasattr(self.pretrained_model, "hf_device_map"):
893
+ if (
894
+ "cpu" in self.pretrained_model.hf_device_map.values()
895
+ or "disk" in self.pretrained_model.hf_device_map.values()
896
+ ):
897
+ raise ValueError(
898
+ "The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models."
899
+ )
900
+
901
+ # get the lm_head device
902
+ for name, module in self.pretrained_model.named_modules():
903
+ if any(attribute in name for attribute in self.lm_head_namings):
904
+ lm_head_device = module.weight.device
905
+ break
906
+
907
+ # put v_head on the same device as the lm_head to avoid issues
908
+ self.v_head = self.v_head.to(lm_head_device)
909
+
910
+ def set_device_hook(module, input, outputs):
911
+ r"""
912
+ A hook that sets the device of the output of the model to the device of the first parameter of the
913
+ model.
914
+
915
+ Args:
916
+ module (`nn.Module`):
917
+ The module to which the hook is attached.
918
+ input (`tuple`):
919
+ The input to the module.
920
+ outputs (`tuple`):
921
+ The output of the module.
922
+ """
923
+ new_output = ()
924
+ for output in outputs:
925
+ if isinstance(output, torch.Tensor):
926
+ new_output += (output.to(lm_head_device),)
927
+ else:
928
+ new_output += (output,)
929
+ return new_output
930
+
931
+ self.register_forward_hook(set_device_hook)
932
+ self.is_sequential_parallel = True
933
+
934
+ def state_dict(self, *args, **kwargs):
935
+ r"""
936
+ Returns the state dictionary of the model. We add the state dictionary of the value head to the state
937
+ dictionary of the wrapped model by prepending the key with `v_head.`.
938
+ """
939
+ if not self.is_peft_model:
940
+ pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs)
941
+ else:
942
+ # if it is a peft model, only save the v_head
943
+ pretrained_model_state_dict = {}
944
+
945
+ v_head_state_dict = self.v_head.state_dict(*args, **kwargs)
946
+ for k, v in v_head_state_dict.items():
947
+ pretrained_model_state_dict[f"v_head.{k}"] = v
948
+ return pretrained_model_state_dict
949
+
950
+ def push_to_hub(self, *args, **kwargs):
951
+ self.pretrained_model.v_head = self.v_head
952
+
953
+ return self.pretrained_model.push_to_hub(*args, **kwargs)
954
+
955
+ def _init_weights(self, **kwargs):
956
+ r"""
957
+ We initialize the weights of the value head.
958
+ """
959
+ initializer_range = kwargs.pop("v_head_initializer_range", 0.2)
960
+ # random init by default
961
+ init_strategy = kwargs.pop("v_head_init_strategy", None)
962
+ if init_strategy is None:
963
+ # do nothing
964
+ pass
965
+ elif init_strategy == "normal":
966
+ self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range)
967
+ self.v_head.summary.bias.data.zero_()
968
+
969
+ def forward(
970
+ self,
971
+ input_ids=None,
972
+ past_key_values=None,
973
+ attention_mask=None,
974
+ return_past_key_values=False,
975
+ **kwargs,
976
+ ):
977
+ kwargs["past_key_values"] = past_key_values
978
+ if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING":
979
+ kwargs.pop("past_key_values")
980
+
981
+ base_model_output = self.pretrained_model(
982
+ input_ids=input_ids,
983
+ attention_mask=attention_mask,
984
+ output_hidden_states=True, # We force the model to output hidden states
985
+ **kwargs,
986
+ )
987
+
988
+ last_hidden_state = base_model_output.decoder_hidden_states[-1]
989
+ lm_logits = base_model_output.logits
990
+ loss = base_model_output.loss
991
+
992
+ value = self.v_head(last_hidden_state).squeeze(-1)
993
+
994
+ # force upcast in fp32 if logits are in half-precision
995
+ if lm_logits.dtype != torch.float32:
996
+ lm_logits = lm_logits.float()
997
+
998
+ if return_past_key_values:
999
+ return (lm_logits, loss, value, base_model_output.past_key_values)
1000
+ else:
1001
+ return (lm_logits, loss, value)
1002
+
1003
+ def generate(self, *args, **kwargs):
1004
+ r"""
1005
+ We call `generate` on the wrapped model.
1006
+ """
1007
+ return self.pretrained_model.generate(*args, **kwargs)
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/ppo/ppo_config.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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, field
16
+ from typing import Literal
17
+
18
+ from ...trainer.base_config import _BaseConfig
19
+
20
+
21
+ @dataclass
22
+ class PPOConfig(_BaseConfig):
23
+ # docstyle-ignore
24
+ r"""
25
+ Configuration class for the [`experimental.ppo.PPOTrainer`].
26
+
27
+ This class includes only the parameters that are specific to PPO training. For a full list of training arguments,
28
+ please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
29
+ differ from those in [`~transformers.TrainingArguments`].
30
+
31
+ Using [`~transformers.HfArgumentParser`] we can turn this class into
32
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
33
+ command line.
34
+
35
+ Parameters:
36
+ dataset_num_proc (`int`, *optional*):
37
+ Number of processes to use for processing the dataset.
38
+ num_mini_batches (`int`, *optional*, defaults to `1`):
39
+ Number of minibatches to split a batch into.
40
+ total_episodes (`int`, *optional*):
41
+ Total number of episodes in the dataset.
42
+ local_rollout_forward_batch_size (`int`, *optional*, defaults to `64`):
43
+ Per rank no grad forward pass in the rollout phase.
44
+ num_sample_generations (`int`, *optional*, defaults to `10`):
45
+ Number of debugging samples generations (i.e., `generate_completions` calls) throughout training.
46
+ response_length (`int`, *optional*, defaults to `53`):
47
+ Length of the response.
48
+ stop_token (`str`, *optional*):
49
+ Specifies the stop token to use for text generation. This parameter is mutually exclusive with
50
+ `stop_token_id`.
51
+
52
+ - `None`: No stop token is applied, unless `stop_token_id` is specified.
53
+ - `'eos'`: Uses the tokenizer's `eos_token`.
54
+
55
+ stop_token_id (`int`, *optional*):
56
+ Specifies the ID of the stop token to use for text generation. If `None`, no stop token ID is applied,
57
+ unless `stop_token` is specified. This parameter is mutually exclusive with `stop_token`.
58
+ temperature (`float`, *optional*, defaults to `0.7`):
59
+ Sampling temperature.
60
+ missing_eos_penalty (`float`, *optional*):
61
+ Penalty applied to the score when the model fails to generate an EOS token. This is useful to encourage to
62
+ generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be a positive
63
+ value.
64
+ sft_model_path (`str`, *optional*, defaults to `"EleutherAI/pythia-160m"`):
65
+ Path to the SFT model.
66
+ world_size (`int`, *optional*):
67
+ Number of processes (GPUs) to use for the training.
68
+ num_total_batches (`int`, *optional*):
69
+ Number of total batches to train.
70
+ micro_batch_size (`int`, *optional*):
71
+ Micro batch size across devices (HF's `per_device_train_batch_size` * `world_size`).
72
+ local_batch_size (`int`, *optional*):
73
+ Batch size per GPU (HF's `per_device_train_batch_size` * `gradient_accumulation_steps`).
74
+ batch_size (`int`, *optional*):
75
+ Batch size across devices (HF's `per_device_train_batch_size` * `world_size` *
76
+ `gradient_accumulation_steps`).
77
+ local_mini_batch_size (`int`, *optional*):
78
+ Mini batch size per GPU.
79
+ mini_batch_size (`int`, *optional*):
80
+ Mini batch size across GPUs.
81
+ push_to_hub (`bool`, *optional*, defaults to `False`):
82
+ Whether to push the model to the Hub after training.
83
+ reward_model_path (`str`, *optional*, defaults to `"EleutherAI/pythia-160m"`):
84
+ Path to the reward model.
85
+ model_adapter_name (`str`, *optional*):
86
+ Name of the train target PEFT adapter, when using LoRA with multiple adapters.
87
+ ref_adapter_name (`str`, *optional*):
88
+ Name of the reference PEFT adapter, when using LoRA with multiple adapters.
89
+ num_ppo_epochs (`int`, *optional*, defaults to `4`):
90
+ Number of epochs to train.
91
+ whiten_rewards (`bool`, *optional*, defaults to `False`):
92
+ Whether to whiten the rewards.
93
+ kl_coef (`float`, *optional*, defaults to `0.05`):
94
+ KL coefficient.
95
+ kl_estimator (`Literal["k1", "k3"]`, *optional*, defaults to `"k1"`):
96
+ Which estimator for KL-Divergence to use from [Approximating KL
97
+ Divergence](http://joschu.net/blog/kl-approx.html). Defaults to "k1", a straightforward, unbiased
98
+ estimator. Can be set to "k3", an unbiased estimator with lower variance which "appears to be a strictly
99
+ better estimator". Cannot be set to "k2", as it is used for logging purposes.
100
+ cliprange (`float`, *optional*, defaults to `0.2`):
101
+ Clip range.
102
+ vf_coef (`float`, *optional*, defaults to `0.1`):
103
+ Value function coefficient.
104
+ cliprange_value (`float`, *optional*, defaults to `0.2`):
105
+ Clip range for the value function.
106
+ gamma (`float`, *optional*, defaults to `1.0`):
107
+ Discount factor.
108
+ lam (`float`, *optional*, defaults to `0.95`):
109
+ Lambda value for GAE.
110
+ ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
111
+ This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation,
112
+ improving generation speed. However, disabling this option allows training models that exceed the VRAM
113
+ capacity of a single GPU, albeit at the cost of slower generation.
114
+
115
+ > [!NOTE]
116
+ > These parameters have default values different from [`~transformers.TrainingArguments`]:
117
+ > - `logging_steps`: Defaults to `10` instead of `500`.
118
+ > - `gradient_checkpointing`: Defaults to `True` instead of `False`.
119
+ > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
120
+ > - `learning_rate`: Defaults to `3e-6` instead of `5e-5`.
121
+ """
122
+
123
+ # Parameters whose default values are overridden from TrainingArguments
124
+ learning_rate: float = field(
125
+ default=3e-6,
126
+ metadata={"help": "The initial learning rate for AdamW."},
127
+ )
128
+
129
+ dataset_num_proc: int | None = field(
130
+ default=None,
131
+ metadata={"help": "Number of processes to use for processing the dataset."},
132
+ )
133
+ num_mini_batches: int = field(
134
+ default=1,
135
+ metadata={"help": "Number of minibatches to split a batch into."},
136
+ )
137
+ total_episodes: int | None = field(
138
+ default=None,
139
+ metadata={"help": "Total number of episodes in the dataset."},
140
+ )
141
+ local_rollout_forward_batch_size: int = field(
142
+ default=64,
143
+ metadata={"help": "Per rank no grad forward pass in the rollout phase."},
144
+ )
145
+ num_sample_generations: int = field(
146
+ default=10,
147
+ metadata={
148
+ "help": "Number of debugging samples generations (i.e., `generate_completions` calls) throughout training."
149
+ },
150
+ )
151
+ response_length: int = field(
152
+ default=53,
153
+ metadata={"help": "Length of the response."},
154
+ )
155
+ stop_token: Literal["eos"] | None = field(
156
+ default=None,
157
+ metadata={
158
+ "help": "Specifies the stop token to use for text generation. This parameter is mutually exclusive with "
159
+ "`stop_token_id`."
160
+ },
161
+ )
162
+ stop_token_id: int | None = field(
163
+ default=None,
164
+ metadata={
165
+ "help": "Specifies the ID of the stop token to use for text generation. If `None`, no stop token ID is "
166
+ "applied, unless `stop_token` is specified. This parameter is mutually exclusive with `stop_token`."
167
+ },
168
+ )
169
+ temperature: float = field(
170
+ default=0.7,
171
+ metadata={"help": "Sampling temperature."},
172
+ )
173
+ missing_eos_penalty: float | None = field(
174
+ default=None,
175
+ metadata={
176
+ "help": "Penalty applied to the score when the model fails to generate an EOS token. This is useful to "
177
+ "encourage to generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be "
178
+ "a positive value."
179
+ },
180
+ )
181
+ sft_model_path: str = field(
182
+ default="EleutherAI/pythia-160m",
183
+ metadata={"help": "Path to the SFT model."},
184
+ )
185
+ world_size: int | None = field(
186
+ default=None,
187
+ metadata={"help": "Number of processes (GPUs) to use for the training."},
188
+ )
189
+ num_total_batches: int | None = field(
190
+ default=None,
191
+ metadata={"help": "Number of total batches to train."},
192
+ )
193
+ micro_batch_size: int | None = field(
194
+ default=None,
195
+ metadata={"help": "Micro batch size across devices (HF's `per_device_train_batch_size` * `world_size`)."},
196
+ )
197
+ local_batch_size: int | None = field(
198
+ default=None,
199
+ metadata={"help": "Batch size per GPU (HF's `per_device_train_batch_size` * `gradient_accumulation_steps`)."},
200
+ )
201
+ batch_size: int | None = field(
202
+ default=None,
203
+ metadata={
204
+ "help": "Batch size across devices (HF's `per_device_train_batch_size` * `world_size` * "
205
+ "`gradient_accumulation_steps`)."
206
+ },
207
+ )
208
+ local_mini_batch_size: int | None = field(
209
+ default=None,
210
+ metadata={"help": "Mini batch size per GPU."},
211
+ )
212
+ mini_batch_size: int | None = field(
213
+ default=None,
214
+ metadata={"help": "Mini batch size across GPUs."},
215
+ )
216
+ push_to_hub: bool = field(
217
+ default=False,
218
+ metadata={"help": "Whether to push the model to the Hub after training."},
219
+ )
220
+ reward_model_path: str = field(
221
+ default="EleutherAI/pythia-160m",
222
+ metadata={"help": "Path to the reward model."},
223
+ )
224
+ model_adapter_name: str | None = field(
225
+ default=None,
226
+ metadata={"help": "Name of the train target PEFT adapter, when using LoRA with multiple adapters."},
227
+ )
228
+ ref_adapter_name: str | None = field(
229
+ default=None,
230
+ metadata={"help": "Name of the reference PEFT adapter, when using LoRA with multiple adapters."},
231
+ )
232
+ num_ppo_epochs: int = field(
233
+ default=4,
234
+ metadata={"help": "Number of epochs to train."},
235
+ )
236
+ whiten_rewards: bool = field(
237
+ default=False,
238
+ metadata={"help": "Whether to whiten the rewards."},
239
+ )
240
+ kl_coef: float = field(
241
+ default=0.05,
242
+ metadata={"help": "KL coefficient."},
243
+ )
244
+ kl_estimator: Literal["k1", "k3"] = field(
245
+ default="k1",
246
+ metadata={
247
+ "help": "Which estimator for KL-Divergence to use from Approximating KL Divergence "
248
+ "(http://joschu.net/blog/kl-approx.html). Defaults to 'k1', a straightforward, unbiased estimator. Can be "
249
+ "set to 'k3', an unbiased estimator with lower variance which 'appears to be a strictly better "
250
+ "estimator'. Cannot be set to 'k2', as it is used for logging purposes."
251
+ },
252
+ )
253
+ cliprange: float = field(
254
+ default=0.2,
255
+ metadata={"help": "Clip range."},
256
+ )
257
+ vf_coef: float = field(
258
+ default=0.1,
259
+ metadata={"help": "Value function coefficient."},
260
+ )
261
+ cliprange_value: float = field(
262
+ default=0.2,
263
+ metadata={"help": "Clip range for the value function."},
264
+ )
265
+ gamma: float = field(
266
+ default=1.0,
267
+ metadata={"help": "Discount factor."},
268
+ )
269
+ lam: float = field(
270
+ default=0.95,
271
+ metadata={"help": "Lambda value for GAE."},
272
+ )
273
+ ds3_gather_for_generation: bool = field(
274
+ default=True,
275
+ metadata={
276
+ "help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for "
277
+ "generation, improving generation speed. However, disabling this option allows training models that "
278
+ "exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation."
279
+ },
280
+ )
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/ppo/ppo_trainer.py ADDED
@@ -0,0 +1,1031 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 gc
16
+ import math
17
+ import os
18
+ import textwrap
19
+ import time
20
+ from collections import defaultdict
21
+ from contextlib import contextmanager, nullcontext
22
+ from dataclasses import dataclass
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+ import pandas as pd
27
+ import torch
28
+ import torch.nn as nn
29
+ import transformers
30
+ from accelerate import Accelerator, logging
31
+ from accelerate.utils import gather_object
32
+ from datasets import Dataset
33
+ from packaging.version import Version
34
+ from torch.utils.data import DataLoader
35
+ from transformers import (
36
+ BaseImageProcessor,
37
+ DataCollatorWithPadding,
38
+ FeatureExtractionMixin,
39
+ GenerationConfig,
40
+ PreTrainedTokenizerBase,
41
+ ProcessorMixin,
42
+ TrainerCallback,
43
+ TrainerControl,
44
+ TrainerState,
45
+ )
46
+ from transformers.integrations import get_reporting_integration_callbacks
47
+ from transformers.trainer import DEFAULT_CALLBACKS, DEFAULT_PROGRESS_CALLBACK
48
+ from transformers.trainer_callback import CallbackHandler, ExportableState, PrinterCallback
49
+ from transformers.utils import ModelOutput, is_peft_available, is_rich_available
50
+
51
+ from ...models.utils import prepare_deepspeed, unwrap_model_for_generation
52
+ from ...trainer.base_trainer import _BaseTrainer
53
+ from ...trainer.utils import (
54
+ disable_dropout_in_model,
55
+ log_table_to_comet_experiment,
56
+ pad,
57
+ selective_log_softmax,
58
+ )
59
+ from ..utils import (
60
+ create_reference_model,
61
+ empty_cache,
62
+ first_true_indices,
63
+ get_reward,
64
+ peft_module_casting_to_bf16,
65
+ )
66
+ from .ppo_config import PPOConfig
67
+
68
+
69
+ if is_rich_available():
70
+ from rich.console import Console
71
+ from rich.table import Table
72
+
73
+
74
+ logger = logging.get_logger(__name__)
75
+
76
+ if is_peft_available():
77
+ from peft import PeftConfig, PeftModel, get_peft_model
78
+
79
+
80
+ INVALID_LOGPROB = 1.0
81
+
82
+
83
+ def generate(
84
+ lm_backbone: torch.nn.Module, queries: torch.Tensor, pad_token_id: int, generation_config: GenerationConfig
85
+ ) -> tuple[torch.Tensor, torch.Tensor]:
86
+ """
87
+ Generates sequences from the language model backbone in a way that does not affect padding tokens.
88
+
89
+ Args:
90
+ lm_backbone (`torch.nn.Module`):
91
+ The language model backbone used for generation.
92
+ queries (`torch.Tensor`):
93
+ The tensor containing the input queries.
94
+ pad_token_id (`int`):
95
+ The token ID representing the pad token.
96
+ generation_config ([`~transformers.GenerationConfig`]):
97
+ The configuration for the generation process.
98
+
99
+ Returns:
100
+ tuple:
101
+ - `generated_sequences` (`torch.Tensor`):
102
+ The concatenated tensor of input queries and generated sequences.
103
+ - `logits` (`torch.Tensor`):
104
+ The logits output from the generation process.
105
+ """
106
+ context_length = queries.shape[1]
107
+ attention_mask = queries != pad_token_id
108
+ input_ids = torch.masked_fill(queries, ~attention_mask, 0)
109
+ output = lm_backbone.generate(
110
+ input_ids=input_ids,
111
+ attention_mask=attention_mask,
112
+ # position_ids=attention_mask.cumsum(1) - attention_mask.long(), # not needed: already adjusted in generations
113
+ # https://github.com/huggingface/transformers/blob/ac33aeeeee2a7a89b89c93c2962e6feb90daef0a/src/transformers/models/gpt2/modeling_gpt2.py#L1227-L1250
114
+ generation_config=generation_config,
115
+ return_dict_in_generate=True,
116
+ output_scores=True,
117
+ )
118
+ logits = torch.stack(output.scores, 1)
119
+ return torch.cat((queries, output.sequences[:, context_length:]), dim=1), logits
120
+
121
+
122
+ @torch.no_grad()
123
+ def batch_generation(
124
+ model: torch.nn.Module,
125
+ queries: torch.Tensor,
126
+ local_rollout_forward_batch_size: int,
127
+ pad_token_id: int,
128
+ generation_config: GenerationConfig,
129
+ ):
130
+ query_responses = []
131
+ logitss = []
132
+ batch_size = queries.shape[0]
133
+ for i in range(0, batch_size, local_rollout_forward_batch_size):
134
+ query = queries[i : i + local_rollout_forward_batch_size]
135
+ query_response, logits = generate(
136
+ model,
137
+ query,
138
+ pad_token_id,
139
+ generation_config,
140
+ )
141
+ query_responses.append(query_response)
142
+ logitss.append(logits)
143
+
144
+ # padding tensors
145
+ padded_query_responses = pad(query_responses, padding_value=pad_token_id, padding_side="right")
146
+ padded_logitss = pad(logitss, padding_value=0, padding_side="right")
147
+
148
+ # reshaping
149
+ padded_query_responses = padded_query_responses.view(-1, padded_query_responses.shape[-1])[:batch_size]
150
+ padded_logitss = padded_logitss.view(-1, *padded_logitss.shape[2:])[:batch_size]
151
+
152
+ return padded_query_responses, padded_logitss
153
+
154
+
155
+ def exact_div(a, b, custom_error_message=""):
156
+ q = a // b
157
+ if a != q * b:
158
+ raise ValueError(f"{custom_error_message}, inexact division: {a} / {b} = {a / b}")
159
+ return q
160
+
161
+
162
+ def print_rich_table(df: pd.DataFrame) -> None:
163
+ if not is_rich_available():
164
+ raise ImportError(
165
+ "The function `print_rich_table` requires the `rich` library. Please install it with `pip install rich`."
166
+ )
167
+ console = Console()
168
+ table = Table(show_lines=True)
169
+ for column in df.columns:
170
+ table.add_column(column)
171
+ for _, row in df.iterrows():
172
+ table.add_row(*row.astype(str).tolist())
173
+ console.print(table)
174
+
175
+
176
+ def truncate_response(stop_token_id: int, pad_token_id: int, responses: torch.Tensor) -> torch.Tensor:
177
+ """
178
+ Truncates the responses at the first occurrence of the stop token, filling the rest with pad tokens.
179
+
180
+ Args:
181
+ stop_token_id (`int`):
182
+ The token ID representing the stop token where truncation occurs.
183
+ pad_token_id (`int`):
184
+ The token ID representing the pad token used to fill the truncated responses.
185
+ responses (`torch.Tensor`):
186
+ The tensor containing the responses to be truncated.
187
+
188
+ Returns:
189
+ `torch.Tensor`:
190
+ The truncated responses tensor with pad tokens filled after the stop token.
191
+ """
192
+ trunc_idxs = first_true_indices(responses == stop_token_id).unsqueeze(-1)
193
+ new_size = [1] * (len(responses.size()) - 1) + [responses.shape[1]]
194
+ idxs = torch.arange(responses.shape[1], device=responses.device).view(*new_size)
195
+ postprocessed_responses = torch.masked_fill(responses, idxs > trunc_idxs, pad_token_id)
196
+ return postprocessed_responses
197
+
198
+
199
+ def forward(
200
+ model: torch.nn.Module,
201
+ query_responses: torch.Tensor,
202
+ pad_token_id: int,
203
+ ) -> ModelOutput:
204
+ """
205
+ Performs a forward pass through the model with the given query responses and pad token ID.
206
+
207
+ Args:
208
+ model (`torch.nn.Module`):
209
+ The model to perform the forward pass.
210
+ query_responses (`torch.Tensor`):
211
+ The tensor containing the query responses.
212
+ pad_token_id (`int`):
213
+ The token ID representing the pad token.
214
+
215
+ Returns:
216
+ `ModelOutput`:
217
+ The output of the model, including hidden states.
218
+ """
219
+ attention_mask = query_responses != pad_token_id
220
+ position_ids = attention_mask.cumsum(1) - attention_mask.long()
221
+ input_ids = torch.masked_fill(query_responses, ~attention_mask, 0)
222
+ return model(
223
+ input_ids=input_ids,
224
+ attention_mask=attention_mask,
225
+ position_ids=position_ids,
226
+ return_dict=True,
227
+ output_hidden_states=True,
228
+ )
229
+
230
+
231
+ @dataclass
232
+ class OnlineTrainerState(TrainerState):
233
+ """
234
+ Training state for online/on-policy trainers.
235
+
236
+ Extends [`~transformers.TrainerState`] with an `episode` counter to track the current rollout/episode.
237
+
238
+ Args:
239
+ episode (`int`, defaults to 0): Zero-based episode index.
240
+ """
241
+
242
+ episode: int = 0
243
+
244
+
245
+ def masked_mean(values: torch.Tensor, mask: torch.Tensor, axis: bool | None = None) -> torch.Tensor:
246
+ """Compute mean of tensor with a masked values."""
247
+ if axis is not None:
248
+ return (values * mask).sum(axis=axis) / mask.sum(axis=axis)
249
+ else:
250
+ return (values * mask).sum() / mask.sum()
251
+
252
+
253
+ def masked_var(values: torch.Tensor, mask: torch.Tensor, unbiased: bool = True) -> torch.Tensor:
254
+ """Compute variance of tensor with masked values."""
255
+ mean = masked_mean(values, mask)
256
+ centered_values = values - mean
257
+ variance = masked_mean(centered_values**2, mask)
258
+ if unbiased:
259
+ mask_sum = mask.sum()
260
+ if mask_sum == 0:
261
+ raise ValueError(
262
+ "The sum of the mask is zero, which can happen when `mini_batch_size=1`;"
263
+ "try increase the `mini_batch_size` or `gradient_accumulation_steps`"
264
+ )
265
+ # note that if mask_sum == 1, then there is a division by zero issue
266
+ # to avoid it you just need to use a larger minibatch_size
267
+ bessel_correction = mask_sum / (mask_sum - 1)
268
+ variance = variance * bessel_correction
269
+ return variance
270
+
271
+
272
+ def masked_whiten(values: torch.Tensor, mask: torch.Tensor, shift_mean: bool = True) -> torch.Tensor:
273
+ """Whiten values with masked values."""
274
+ mean, var = masked_mean(values, mask), masked_var(values, mask)
275
+ whitened = (values - mean) * torch.rsqrt(var + 1e-8)
276
+ if not shift_mean:
277
+ whitened += mean
278
+ return whitened
279
+
280
+
281
+ # taken from https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/ppo/ppo_trainer.py#L29
282
+ # we did this we can do a single `model = accelerator.prepare(model)`
283
+ class PolicyAndValueWrapper(nn.Module):
284
+ def __init__(self, policy, value_model) -> None:
285
+ super().__init__()
286
+ self.policy = policy
287
+ self.value_model = value_model
288
+ self.critic_backbone = getattr(value_model, value_model.base_model_prefix)
289
+ self.is_gradient_checkpointing = policy.is_gradient_checkpointing
290
+
291
+ def gradient_checkpointing_enable(self, **kwargs):
292
+ self.policy.gradient_checkpointing_enable(**kwargs)
293
+ self.is_gradient_checkpointing = True
294
+
295
+ def gradient_checkpointing_disable(self):
296
+ self.policy.gradient_checkpointing_disable()
297
+ self.is_gradient_checkpointing = False
298
+
299
+ def forward(self, **kwargs):
300
+ output = self.critic_backbone(**kwargs)
301
+ logits = self.value_model.score(output.hidden_states[-1])
302
+ return self.policy(**kwargs), logits
303
+
304
+
305
+ class PPOTrainer(_BaseTrainer):
306
+ """Trainer for Proximal Policy Optimization (PPO).
307
+
308
+ For details on PPO, see the paper: [Proximal Policy Optimization
309
+ Algorithms](https://huggingface.co/papers/1707.06347).
310
+
311
+ Args:
312
+ args ([`experimental.ppo.PPOConfig`]):
313
+ Training arguments.
314
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`]):
315
+ Class to process the data.
316
+ model (`torch.nn.Module`):
317
+ Model to be trained. This is the policy model.
318
+ ref_model (`torch.nn.Module`, *optional*):
319
+ Reference model used to compute the KL divergence. If `None`, a copy of the policy model is created.
320
+ reward_model (`torch.nn.Module`):
321
+ Reward model used to compute the rewards.
322
+ train_dataset ([`~datasets.Dataset`]):
323
+ Dataset for training.
324
+ value_model (`torch.nn.Module`):
325
+ Value model used to predict the value of a state.
326
+ data_collator ([`~transformers.DataCollatorWithPadding`], *optional*):
327
+ Data collator to batch and pad samples from the dataset. If `None`, a default data collator is created
328
+ using the `processing_class`.
329
+ eval_dataset ([`~datasets.Dataset`] or `dict` of [`~datasets.Dataset`], *optional*):
330
+ Dataset for evaluation.
331
+ optimizers (`tuple` of `torch.optim.Optimizer` and `torch.optim.lr_scheduler.LambdaLR`, *optional*, defaults to `(None, None)`):
332
+ Tuple containing the optimizer and the learning rate scheduler to use for training. If `None`, the
333
+ optimizer and the learning rate scheduler are created using the
334
+ [`~transformers.Trainer.create_optimizer_and_scheduler`] method.
335
+ callbacks (`list` of [`~transformers.TrainerCallback`], *optional*):
336
+ Callbacks to use during training.
337
+ peft_config ([`~peft.PeftConfig`], *optional*):
338
+ PEFT configuration to use PEFT for training. If `None`, PEFT is not used. If provided, the policy `model`
339
+ will be wrapped with the specified PEFT adapter.
340
+ """
341
+
342
+ _tag_names = ["trl", "ppo"]
343
+ _name = "PPO"
344
+ _paper = {
345
+ "title": "Fine-Tuning Language Models from Human Preferences",
346
+ "id": "1909.08593",
347
+ # docstyle-ignore
348
+ "citation": textwrap.dedent("""\
349
+ @article{mziegler2019fine-tuning,
350
+ title = {{Fine-Tuning Language Models from Human Preferences}},
351
+ author = {Daniel M. Ziegler and Nisan Stiennon and Jeffrey Wu and Tom B. Brown and Alec Radford and Dario Amodei and Paul F. Christiano and Geoffrey Irving},
352
+ year = 2019,
353
+ eprint = {arXiv:1909.08593}
354
+ }"""),
355
+ }
356
+
357
+ def __init__(
358
+ self,
359
+ args: PPOConfig,
360
+ processing_class: PreTrainedTokenizerBase | BaseImageProcessor | FeatureExtractionMixin | ProcessorMixin,
361
+ model: nn.Module,
362
+ ref_model: nn.Module | None,
363
+ reward_model: nn.Module,
364
+ train_dataset: Dataset,
365
+ value_model: nn.Module,
366
+ data_collator: DataCollatorWithPadding | None = None,
367
+ eval_dataset: Dataset | dict[str, Dataset] | None = None,
368
+ # less commonly used
369
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
370
+ callbacks: list[TrainerCallback] | None = None,
371
+ peft_config: "PeftConfig | None" = None,
372
+ ) -> None:
373
+ if train_dataset is None:
374
+ raise ValueError("`train_dataset` is required")
375
+
376
+ if ref_model is model:
377
+ raise ValueError(
378
+ "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the "
379
+ "same as `model`, you must make a copy of it, or `None` if you use peft."
380
+ )
381
+
382
+ self.args = args
383
+ self.processing_class = processing_class
384
+ self.policy_model = model
385
+
386
+ # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
387
+ # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
388
+ # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
389
+ # default to the recommended non-reentrant behavior here, while preserving any user-provided value.
390
+ if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
391
+ args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
392
+ args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
393
+
394
+ # Define the collator if not provided
395
+ if data_collator is None:
396
+ data_collator = DataCollatorWithPadding(self.processing_class)
397
+
398
+ # Handle stop token settings: update policy model's generation_config to use provided stop token
399
+ if args.stop_token and args.stop_token_id:
400
+ raise ValueError("You cannot set both `stop_token` and `stop_token_id`.")
401
+ elif args.stop_token:
402
+ if args.stop_token == "eos":
403
+ self.policy_model.generation_config.eos_token_id = self.stop_token_id = processing_class.eos_token_id
404
+ else:
405
+ raise ValueError(
406
+ f"Unknown `stop_token` {args.stop_token}. Allowed values are: `'eos'` and `None` (no stop token)."
407
+ )
408
+ else:
409
+ self.policy_model.generation_config.eos_token_id = self.stop_token_id = args.stop_token_id # None or int
410
+
411
+ # Check that the kl estimator is valid
412
+ if self.args.kl_estimator not in {"k1", "k3"}:
413
+ raise ValueError(
414
+ "kl_estimator must be either 'k1' (straightforward, unbiased) or 'k3' (lower variance, unbiased, "
415
+ "appears to be a strictly better estimator). See "
416
+ "[Approximating KL Divergence](http://joschu.net/blog/kl-approx.html) for details."
417
+ )
418
+
419
+ # peft support
420
+ if not is_peft_available() and peft_config is not None:
421
+ raise ImportError(
422
+ "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models"
423
+ )
424
+ elif is_peft_available() and peft_config is not None:
425
+ if isinstance(self.policy_model, PeftModel):
426
+ raise ValueError(
427
+ "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first "
428
+ "merge and unload the existing adapter, save the resulting base model, and then pass that base "
429
+ "model along with the new `peft_config` to the trainer."
430
+ )
431
+
432
+ # get peft model with the given config
433
+ self.policy_model = get_peft_model(self.policy_model, peft_config)
434
+ if args.bf16 and getattr(self.policy_model, "is_loaded_in_4bit", False):
435
+ peft_module_casting_to_bf16(self.policy_model)
436
+
437
+ self.is_peft_model = is_peft_available() and isinstance(self.policy_model, PeftModel)
438
+ self.model_adapter_name = args.model_adapter_name
439
+ self.ref_adapter_name = args.ref_adapter_name
440
+
441
+ if ref_model:
442
+ self.ref_model = ref_model
443
+ elif self.is_peft_model:
444
+ self.ref_model = None
445
+ else:
446
+ self.ref_model = create_reference_model(self.policy_model)
447
+
448
+ self.reward_model = reward_model
449
+ self.train_dataset = train_dataset
450
+ self.train_dataset_len = len(train_dataset)
451
+ self.value_model = value_model
452
+ self.data_collator = data_collator
453
+ self.eval_dataset = eval_dataset
454
+ self.optimizer, self.lr_scheduler = optimizers
455
+ self.optimizer_cls_and_kwargs = None # needed for transformers >= 4.47
456
+
457
+ #########
458
+ # calculate various batch sizes
459
+ #########
460
+ if args.total_episodes is None: # allow the users to define episodes in terms of epochs.
461
+ args.total_episodes = int(args.num_train_epochs * self.train_dataset_len)
462
+ accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps)
463
+ self.accelerator = accelerator
464
+ args.world_size = accelerator.num_processes
465
+ args.local_batch_size = args.per_device_train_batch_size * args.gradient_accumulation_steps
466
+ args.micro_batch_size = int(args.per_device_train_batch_size * args.world_size)
467
+ args.batch_size = int(args.local_batch_size * args.world_size)
468
+ args.mini_batch_size = exact_div(
469
+ args.batch_size, args.num_mini_batches, "`batch_size` must be a multiple of `num_mini_batches`"
470
+ )
471
+ args.local_mini_batch_size = exact_div(
472
+ args.local_batch_size, args.num_mini_batches, "`local_batch_size` must be a multiple of `num_mini_batches`"
473
+ )
474
+ if args.whiten_rewards:
475
+ assert args.local_mini_batch_size >= 8, (
476
+ f"Per-rank minibatch size {args.local_mini_batch_size} is insufficient for whitening"
477
+ )
478
+ # `per_rank_rollout_batch_size` is our `args.local_batch_size`
479
+ # `per_rank_minibatch_size` is our `args.local_mini_batch_size`
480
+ args.num_total_batches = math.ceil(
481
+ args.total_episodes / args.batch_size
482
+ ) # we may train for more than `total_episodes`
483
+ self.local_seed = args.seed + accelerator.process_index * 100003 # Prime
484
+ if args.num_sample_generations > 0:
485
+ self.sample_generations_freq = max(1, args.num_total_batches // args.num_sample_generations)
486
+ self.local_dataloader_batch_size = args.local_batch_size
487
+
488
+ #########
489
+ # setup model, optimizer, and others
490
+ #########
491
+ for module in [self.policy_model, self.ref_model, self.value_model, self.reward_model]:
492
+ if module is not None:
493
+ disable_dropout_in_model(module)
494
+ self.model = PolicyAndValueWrapper(self.policy_model, self.value_model)
495
+ self.model.config = self.policy_model.config # needed for pushing to hub
496
+ self.create_optimizer_and_scheduler(
497
+ num_training_steps=args.num_total_batches
498
+ ) # note that we are calling `self.lr_scheduler.step()` manually only at the batch level
499
+
500
+ #########
501
+ # trainer specifics
502
+ #########
503
+ default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to)
504
+ self.callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks
505
+ self.callback_handler = CallbackHandler(
506
+ self.callbacks, self.model, self.processing_class, self.optimizer, self.lr_scheduler
507
+ )
508
+ self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK)
509
+ self.control = TrainerControl()
510
+ self.state = OnlineTrainerState(
511
+ is_local_process_zero=self.is_local_process_zero(),
512
+ is_world_process_zero=self.is_world_process_zero(),
513
+ stateful_callbacks=[
514
+ cb for cb in self.callback_handler.callbacks + [self.control] if isinstance(cb, ExportableState)
515
+ ],
516
+ )
517
+ self.current_flos = 0
518
+ self.hp_search_backend = None
519
+ self.is_deepspeed_enabled = getattr(self.accelerator.state, "deepspeed_plugin", None) is not None
520
+ self.is_fsdp_enabled = getattr(self.accelerator.state, "fsdp_plugin", None) is not None
521
+ # Create distant repo and output directory if needed
522
+ self.hub_model_id = None
523
+ if self.args.push_to_hub:
524
+ self.init_hf_repo()
525
+ if self.args.should_save:
526
+ os.makedirs(self.args.output_dir, exist_ok=True)
527
+
528
+ # Add tags for models that have been loaded with the correct transformers version
529
+ if hasattr(self.model, "add_model_tags"):
530
+ self.model.add_model_tags(self._tag_names)
531
+
532
+ #########
533
+ # setup dataloader
534
+ #########
535
+ self.dataloader = DataLoader(
536
+ self.train_dataset,
537
+ batch_size=self.local_dataloader_batch_size,
538
+ shuffle=True,
539
+ collate_fn=self.data_collator,
540
+ drop_last=True, # needed; otherwise the last batch will be of ragged shape
541
+ )
542
+ # sync random states for DataLoader(shuffle=True) before `accelerator.prepare`
543
+ # see https://gist.github.com/vwxyzjn/2581bff1e48e185e0b85b6dfe1def79c
544
+ torch.manual_seed(args.seed)
545
+ self.model, self.optimizer, self.dataloader = accelerator.prepare(self.model, self.optimizer, self.dataloader)
546
+ torch.manual_seed(self.local_seed) # reset the local seed again
547
+
548
+ self.eval_dataloader = DataLoader(
549
+ self.eval_dataset,
550
+ batch_size=args.per_device_eval_batch_size,
551
+ collate_fn=self.data_collator,
552
+ drop_last=True,
553
+ ) # no need to shuffle eval dataset
554
+ self.eval_dataloader = accelerator.prepare(self.eval_dataloader)
555
+
556
+ if self.is_deepspeed_enabled:
557
+ self.reward_model = prepare_deepspeed(self.reward_model, accelerator)
558
+
559
+ if self.ref_model is None:
560
+ if not self.is_peft_model:
561
+ raise ValueError("No reference model and model is not a Peft model.")
562
+ else:
563
+ self.ref_model = prepare_deepspeed(self.ref_model, accelerator)
564
+ else:
565
+ if self.ref_model is None:
566
+ if not self.is_peft_model:
567
+ raise ValueError("No reference model and model is not a Peft model.")
568
+ else:
569
+ self.ref_model = self.ref_model.to(self.accelerator.device)
570
+ self.reward_model = self.reward_model.to(self.accelerator.device)
571
+
572
+ def get_train_dataloader(self) -> DataLoader:
573
+ return self.dataloader
574
+
575
+ def get_eval_dataloader(self) -> DataLoader:
576
+ return self.eval_dataloader
577
+
578
+ @contextmanager
579
+ def null_ref_context(self):
580
+ """Context manager for handling null reference model (that is, peft adapter manipulation)."""
581
+ with (
582
+ self.accelerator.unwrap_model(self.model.policy).disable_adapter()
583
+ if self.is_peft_model and not self.ref_adapter_name
584
+ else nullcontext()
585
+ ):
586
+ if self.ref_adapter_name:
587
+ self.model.policy.set_adapter(self.ref_adapter_name)
588
+ yield
589
+ if self.ref_adapter_name:
590
+ self.model.policy.set_adapter(self.model_adapter_name or "default")
591
+
592
+ def save_model(self, output_dir: str | None = None, _internal_call: bool = False):
593
+ backup_model = self.model
594
+ if hasattr(self.model, "policy"):
595
+ self.model = self.model.policy # save only the policy for inference
596
+ if self.is_deepspeed_enabled:
597
+ backup_deepspeed = self.deepspeed
598
+ self.deepspeed = self.model
599
+
600
+ super().save_model(output_dir, _internal_call)
601
+
602
+ self.model = backup_model
603
+ if self.is_deepspeed_enabled:
604
+ self.deepspeed = backup_deepspeed
605
+
606
+ def train(self):
607
+ args = self.args
608
+ accelerator = self.accelerator
609
+ optimizer = self.optimizer
610
+ model = self.model
611
+ ref_policy = self.ref_model
612
+ reward_model = self.reward_model
613
+ processing_class = self.processing_class
614
+ dataloader = self.dataloader
615
+ device = accelerator.device
616
+
617
+ def repeat_generator():
618
+ while True:
619
+ yield from dataloader
620
+
621
+ iter_dataloader = iter(repeat_generator())
622
+ generation_kwargs = {
623
+ "max_new_tokens": args.response_length,
624
+ "temperature": (args.temperature + 1e-7),
625
+ "top_k": 0.0,
626
+ "top_p": 1.0,
627
+ "do_sample": True,
628
+ }
629
+ generation_config = GenerationConfig(**generation_kwargs)
630
+
631
+ accelerator.print("===training policy===")
632
+ start_time = time.time()
633
+ stats_shape = (args.num_ppo_epochs, args.num_mini_batches, args.gradient_accumulation_steps)
634
+ approxkl_stats = torch.zeros(stats_shape, device=device)
635
+ pg_clipfrac_stats = torch.zeros(stats_shape, device=device)
636
+ pg_loss_stats = torch.zeros(stats_shape, device=device)
637
+ vf_loss_stats = torch.zeros(stats_shape, device=device)
638
+ vf_clipfrac_stats = torch.zeros(stats_shape, device=device)
639
+ entropy_stats = torch.zeros(stats_shape, device=device)
640
+ ratio_stats = torch.zeros(stats_shape, device=device)
641
+ model.train()
642
+
643
+ # trainer state initialization
644
+ self.state.global_step = 0
645
+ self.state.episode = 0
646
+ self.state.max_steps = args.num_total_batches
647
+ self.state.num_train_epochs = args.total_episodes / self.train_dataset_len
648
+ # Compute absolute values for logging, eval, and save if given as ratio
649
+ if args.logging_steps is not None:
650
+ if args.logging_steps < 1:
651
+ self.state.logging_steps = math.ceil(self.state.max_steps * args.logging_steps)
652
+ else:
653
+ self.state.logging_steps = args.logging_steps
654
+ if args.eval_steps is not None:
655
+ if args.eval_steps < 1:
656
+ self.state.eval_steps = math.ceil(self.state.max_steps * args.eval_steps)
657
+ else:
658
+ self.state.eval_steps = args.eval_steps
659
+ if args.save_steps is not None:
660
+ if args.save_steps < 1:
661
+ self.state.save_steps = math.ceil(self.state.max_steps * args.save_steps)
662
+ else:
663
+ self.state.save_steps = args.save_steps
664
+ self.control = self.callback_handler.on_train_begin(args, self.state, self.control)
665
+
666
+ # backward compatibility
667
+ if self.is_deepspeed_enabled:
668
+ self.deepspeed = self.model
669
+ self.model_wrapped = self.model
670
+
671
+ for update in range(1, args.num_total_batches + 1):
672
+ self.state.episode += 1 * args.batch_size
673
+ data = next(iter_dataloader)
674
+ with torch.no_grad():
675
+ queries = data["input_ids"].to(device)
676
+ context_length = queries.shape[1]
677
+ responses = []
678
+ postprocessed_responses = []
679
+ logprobs = []
680
+ ref_logprobs = []
681
+ scores = []
682
+ sequence_lengths = []
683
+ values = []
684
+ with (
685
+ unwrap_model_for_generation(
686
+ self.model,
687
+ self.accelerator,
688
+ gather_deepspeed3_params=self.args.ds3_gather_for_generation,
689
+ generation_kwargs=generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
690
+ ) as unwrapped_model
691
+ ):
692
+ query_responses, logitss = batch_generation(
693
+ unwrapped_model.policy,
694
+ queries,
695
+ args.local_rollout_forward_batch_size,
696
+ processing_class.pad_token_id,
697
+ generation_config,
698
+ )
699
+
700
+ for i in range(0, queries.shape[0], args.local_rollout_forward_batch_size):
701
+ query = queries[i : i + args.local_rollout_forward_batch_size]
702
+ query_response = query_responses[i : i + args.local_rollout_forward_batch_size]
703
+ response = query_response[:, context_length:]
704
+ logits = logitss[i : i + args.local_rollout_forward_batch_size]
705
+ logprob = selective_log_softmax(logits, response)
706
+ del logits
707
+ empty_cache()
708
+
709
+ if ref_policy is None:
710
+ with self.null_ref_context():
711
+ ref_output = forward(model.policy, query_response, processing_class.pad_token_id)
712
+ else:
713
+ ref_output = forward(ref_policy, query_response, processing_class.pad_token_id)
714
+ ref_logits = ref_output.logits[:, context_length - 1 : -1]
715
+ ref_logits /= args.temperature + 1e-7
716
+ ref_logprob = selective_log_softmax(ref_logits, response)
717
+ del ref_output, ref_logits
718
+ empty_cache()
719
+
720
+ # Response Processing 1. truncate response after the first occurrence of `stop_token_id`
721
+ postprocessed_response = response
722
+ if self.stop_token_id is not None: # handle the edge case when stop_token_id exists but is 0
723
+ postprocessed_response = truncate_response(
724
+ self.stop_token_id, processing_class.pad_token_id, response
725
+ )
726
+
727
+ # Response Processing 2. run reward model on the truncated responses
728
+ postprocessed_query_response = torch.cat((query, postprocessed_response), 1)
729
+ sequence_length = first_true_indices(postprocessed_response == processing_class.pad_token_id) - 1
730
+ unwrapped_value_model = accelerator.unwrap_model(model).value_model
731
+ full_value, _, _ = get_reward(
732
+ unwrapped_value_model, query_response, processing_class.pad_token_id, context_length
733
+ )
734
+ value = full_value[:, context_length - 1 : -1].squeeze(-1)
735
+ _, score, _ = get_reward(
736
+ reward_model, postprocessed_query_response, processing_class.pad_token_id, context_length
737
+ )
738
+
739
+ responses.append(response)
740
+ postprocessed_responses.append(postprocessed_response)
741
+ logprobs.append(logprob)
742
+ ref_logprobs.append(ref_logprob)
743
+ sequence_lengths.append(sequence_length)
744
+ scores.append(score)
745
+ values.append(value)
746
+ responses = torch.cat(responses, 0)
747
+ postprocessed_responses = torch.cat(postprocessed_responses, 0)
748
+ logprobs = torch.cat(logprobs, 0)
749
+ ref_logprobs = torch.cat(ref_logprobs, 0)
750
+ sequence_lengths = torch.cat(sequence_lengths, 0)
751
+ scores = torch.cat(scores, 0)
752
+ values = torch.cat(values, 0)
753
+ del (logprob, ref_logprob, full_value, value, score, unwrapped_model)
754
+ empty_cache()
755
+ gc.collect()
756
+
757
+ # Response Processing 3. Filter completion. Ensure that the sample contains stop_token_id
758
+ # Completions not passing that filter will receive a lower score.
759
+ contain_eos_token = torch.any(postprocessed_responses == self.processing_class.eos_token_id, dim=-1)
760
+ if self.args.missing_eos_penalty is not None:
761
+ scores[~contain_eos_token] -= self.args.missing_eos_penalty
762
+ # accelerator.print(f"{scores=}, {(contain_eos_token.sum() / len(contain_eos_token))=}")
763
+
764
+ # be very careful with `padding_mask_p1`; see https://excalidraw.com/#json=LWnzG4w2k5DjF_EOL_xPt,e2w3a-hFJ_gX5vOfeyXGTw
765
+ response_idxs = torch.arange(responses.shape[1], device=responses.device).repeat(responses.shape[0], 1)
766
+ padding_mask = response_idxs > sequence_lengths.unsqueeze(1)
767
+ logprobs = torch.masked_fill(logprobs, padding_mask, INVALID_LOGPROB)
768
+ ref_logprobs = torch.masked_fill(ref_logprobs, padding_mask, INVALID_LOGPROB)
769
+ sequence_lengths_p1 = sequence_lengths + 1
770
+ padding_mask_p1 = response_idxs > (sequence_lengths_p1.unsqueeze(1))
771
+ values = torch.masked_fill(values, padding_mask_p1, 0)
772
+
773
+ # 4. compute rewards
774
+ # Formula used by http://joschu.net/blog/kl-approx.html for the k1 and k3 estimators
775
+ logr = ref_logprobs - logprobs
776
+ kl = -logr if args.kl_estimator == "k1" else (logr.exp() - 1) - logr # Else statement is k3
777
+ non_score_reward = -args.kl_coef * kl
778
+ rewards = non_score_reward.clone()
779
+ actual_start = torch.arange(rewards.size(0), device=rewards.device)
780
+ actual_end = torch.where(sequence_lengths_p1 < rewards.size(1), sequence_lengths_p1, sequence_lengths)
781
+ rewards[actual_start, actual_end] += scores
782
+
783
+ # 5. whiten rewards
784
+ if args.whiten_rewards:
785
+ rewards = masked_whiten(rewards, mask=~padding_mask_p1, shift_mean=False)
786
+ rewards = torch.masked_fill(rewards, padding_mask_p1, 0)
787
+
788
+ # 6. compute advantages and returns
789
+ lastgaelam = 0
790
+ advantages_reversed = []
791
+ gen_length = responses.shape[1]
792
+ for t in reversed(range(gen_length)):
793
+ nextvalues = values[:, t + 1] if t < gen_length - 1 else 0.0
794
+ delta = rewards[:, t] + args.gamma * nextvalues - values[:, t]
795
+ lastgaelam = delta + args.gamma * args.lam * lastgaelam
796
+ advantages_reversed.append(lastgaelam)
797
+ advantages = torch.stack(advantages_reversed[::-1], axis=1)
798
+ returns = advantages + values
799
+ advantages = masked_whiten(advantages, ~padding_mask)
800
+ advantages = torch.masked_fill(advantages, padding_mask, 0)
801
+ empty_cache()
802
+
803
+ # Do multiple epochs of PPO training, with a fresh random shuffle in each epoch
804
+ for ppo_epoch_idx in range(args.num_ppo_epochs):
805
+ b_inds = np.random.permutation(args.local_batch_size)
806
+ minibatch_idx = 0
807
+ for mini_batch_start in range(0, args.local_batch_size, args.local_mini_batch_size):
808
+ mini_batch_end = mini_batch_start + args.local_mini_batch_size
809
+ mini_batch_inds = b_inds[mini_batch_start:mini_batch_end]
810
+ gradient_accumulation_idx = 0
811
+ for micro_batch_start in range(0, args.local_mini_batch_size, args.per_device_train_batch_size):
812
+ with accelerator.accumulate(model):
813
+ micro_batch_end = micro_batch_start + args.per_device_train_batch_size
814
+ micro_batch_inds = mini_batch_inds[micro_batch_start:micro_batch_end]
815
+ mb_advantage = advantages[micro_batch_inds]
816
+ mb_responses = responses[micro_batch_inds]
817
+ mb_query_responses = query_responses[micro_batch_inds]
818
+ mb_logprobs = logprobs[micro_batch_inds]
819
+ mb_return = returns[micro_batch_inds]
820
+ mb_values = values[micro_batch_inds]
821
+
822
+ output, vpred_temp = forward(model, mb_query_responses, processing_class.pad_token_id)
823
+ logits = output.logits[:, context_length - 1 : -1]
824
+ logits /= args.temperature + 1e-7
825
+ new_logprobs = selective_log_softmax(logits, mb_responses)
826
+ new_logprobs = torch.masked_fill(
827
+ new_logprobs, padding_mask[micro_batch_inds], INVALID_LOGPROB
828
+ )
829
+ vpred = vpred_temp[:, context_length - 1 : -1].squeeze(-1)
830
+ vpred = torch.masked_fill(vpred, padding_mask_p1[micro_batch_inds], 0)
831
+ vpredclipped = torch.clamp(
832
+ vpred,
833
+ mb_values - args.cliprange_value,
834
+ mb_values + args.cliprange_value,
835
+ )
836
+ vf_losses1 = torch.square(vpred - mb_return)
837
+ vf_losses2 = torch.square(vpredclipped - mb_return)
838
+ vf_loss_max = torch.max(vf_losses1, vf_losses2)
839
+ vf_loss = 0.5 * masked_mean(vf_loss_max, ~padding_mask_p1[micro_batch_inds])
840
+ vf_clipfrac = masked_mean(
841
+ (vf_losses2 > vf_losses1).float(), ~padding_mask_p1[micro_batch_inds]
842
+ )
843
+ logprobs_diff = new_logprobs - mb_logprobs
844
+ ratio = torch.exp(logprobs_diff)
845
+ pg_losses = -mb_advantage * ratio
846
+ pg_losses2 = -mb_advantage * torch.clamp(ratio, 1.0 - args.cliprange, 1.0 + args.cliprange)
847
+ pg_loss_max = torch.max(pg_losses, pg_losses2)
848
+ pg_loss = masked_mean(pg_loss_max, ~padding_mask[micro_batch_inds])
849
+ loss = pg_loss + args.vf_coef * vf_loss
850
+ accelerator.backward(loss)
851
+ optimizer.step()
852
+ optimizer.zero_grad()
853
+ with torch.no_grad():
854
+ pg_clipfrac = masked_mean(
855
+ (pg_losses2 > pg_losses).float(), ~padding_mask[micro_batch_inds]
856
+ )
857
+ prob_dist = torch.nn.functional.softmax(logits, dim=-1)
858
+ entropy = torch.logsumexp(logits, dim=-1) - torch.sum(prob_dist * logits, dim=-1)
859
+ approxkl = 0.5 * (logprobs_diff**2).mean()
860
+ approxkl_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = approxkl
861
+ pg_clipfrac_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = (
862
+ pg_clipfrac
863
+ )
864
+ pg_loss_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = pg_loss
865
+ vf_loss_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = vf_loss
866
+ vf_clipfrac_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = (
867
+ vf_clipfrac
868
+ )
869
+ entropy_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = entropy.mean()
870
+ ratio_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = ratio.mean()
871
+ gradient_accumulation_idx += 1
872
+ minibatch_idx += 1
873
+ # del everything and empty cache
874
+ # fmt: off
875
+ del (
876
+ output, vpred_temp, logits, new_logprobs, vpred, vpredclipped,
877
+ vf_losses1, vf_losses2, vf_loss, vf_clipfrac, logprobs_diff, ratio, pg_losses, pg_losses2, pg_loss_max,
878
+ pg_loss, loss, pg_clipfrac, prob_dist, entropy, approxkl, mb_return,
879
+ mb_advantage, mb_values, mb_responses, mb_query_responses, mb_logprobs,
880
+ )
881
+ # fmt: on
882
+ empty_cache()
883
+ with torch.no_grad():
884
+ mean_kl = kl.sum(1).mean()
885
+ mean_entropy = (-logprobs).sum(1).mean()
886
+ mean_non_score_reward = non_score_reward.sum(1).mean()
887
+ rlhf_reward = mean_non_score_reward + scores.mean()
888
+ eps = int(self.state.episode / (time.time() - start_time))
889
+ metrics = {}
890
+ metrics["eps"] = eps
891
+ metrics["objective/kl"] = self.accelerator.gather_for_metrics(mean_kl).mean().item()
892
+ metrics["objective/entropy"] = self.accelerator.gather_for_metrics(mean_entropy).mean().item()
893
+ metrics["objective/non_score_reward"] = (
894
+ self.accelerator.gather_for_metrics(mean_non_score_reward).mean().item()
895
+ )
896
+ metrics["objective/rlhf_reward"] = self.accelerator.gather_for_metrics(rlhf_reward).mean().item()
897
+ metrics["objective/scores"] = self.accelerator.gather_for_metrics(scores.mean()).mean().item()
898
+ metrics["policy/approxkl_avg"] = self.accelerator.gather_for_metrics(approxkl_stats).mean().item()
899
+ metrics["policy/clipfrac_avg"] = self.accelerator.gather_for_metrics(pg_clipfrac_stats).mean().item()
900
+ metrics["loss/policy_avg"] = self.accelerator.gather_for_metrics(pg_loss_stats).mean().item()
901
+ metrics["loss/value_avg"] = self.accelerator.gather_for_metrics(vf_loss_stats).mean().item()
902
+ metrics["val/clipfrac_avg"] = self.accelerator.gather_for_metrics(vf_clipfrac_stats).mean().item()
903
+ metrics["policy/entropy_avg"] = self.accelerator.gather_for_metrics(entropy_stats).mean().item()
904
+ metrics["val/ratio"] = self.accelerator.gather_for_metrics(ratio_stats).mean().item()
905
+ metrics["val/ratio_var"] = self.accelerator.gather_for_metrics(ratio_stats).var().item()
906
+ metrics["val/num_eos_tokens"] = (responses == processing_class.eos_token_id).sum().item()
907
+ metrics["lr"] = self.lr_scheduler.get_last_lr()[0]
908
+ metrics["episode"] = self.state.episode
909
+ self.state.epoch = self.state.episode / self.train_dataset_len # used by self.log
910
+ self.state.global_step += 1
911
+ self.log(metrics)
912
+
913
+ self.lr_scheduler.step()
914
+ self.control = self.callback_handler.on_step_end(args, self.state, self.control)
915
+ if self.control.should_save:
916
+ self._save_checkpoint(model, trial=None)
917
+ self.control = self.callback_handler.on_save(self.args, self.state, self.control)
918
+ del kl, mean_kl, mean_entropy, mean_non_score_reward, scores, metrics, non_score_reward
919
+ empty_cache()
920
+ gc.collect()
921
+
922
+ if args.num_sample_generations > 0 and (update - 1) % self.sample_generations_freq == 0:
923
+ self.generate_completions(sampling=True)
924
+ empty_cache()
925
+ del (
926
+ query_responses,
927
+ responses,
928
+ postprocessed_responses,
929
+ logprobs,
930
+ ref_logprobs,
931
+ values,
932
+ sequence_lengths,
933
+ contain_eos_token,
934
+ sequence_lengths_p1,
935
+ response_idxs,
936
+ padding_mask,
937
+ padding_mask_p1,
938
+ rewards,
939
+ actual_start,
940
+ actual_end,
941
+ advantages,
942
+ returns,
943
+ )
944
+ empty_cache()
945
+
946
+ # HF trainer specifics
947
+ self.control = self.callback_handler.on_train_end(args, self.state, self.control)
948
+ if self.control.should_save:
949
+ self._save_checkpoint(model, trial=None)
950
+ self.control = self.callback_handler.on_save(self.args, self.state, self.control)
951
+
952
+ def generate_completions(self, sampling: bool = False):
953
+ if self.eval_dataset is None:
954
+ return # no eval set to sample from (pass eval_dataset and eval_strategy != "no" for sample generations)
955
+ args = self.args
956
+ processing_class = self.processing_class
957
+ generation_kwargs = {
958
+ "max_new_tokens": args.response_length,
959
+ "temperature": (0.01 + 1e-7),
960
+ "top_k": 0.0,
961
+ "top_p": 1.0,
962
+ "do_sample": True,
963
+ }
964
+ generation_config = GenerationConfig(**generation_kwargs)
965
+
966
+ table = defaultdict(list)
967
+ with (
968
+ unwrap_model_for_generation(
969
+ self.model,
970
+ self.accelerator,
971
+ gather_deepspeed3_params=self.args.ds3_gather_for_generation,
972
+ generation_kwargs=generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
973
+ ) as unwrapped_model
974
+ ):
975
+ for batch in self.eval_dataloader:
976
+ query = batch["input_ids"]
977
+ with torch.no_grad():
978
+ context_length = query.shape[1]
979
+ query_response, _ = batch_generation(
980
+ unwrapped_model.policy,
981
+ query,
982
+ query.shape[0],
983
+ processing_class.pad_token_id,
984
+ generation_config,
985
+ )
986
+ response = query_response[:, context_length:]
987
+ postprocessed_response = response
988
+ if self.stop_token_id is not None: # handle the edge case when stop_token_id exists but is 0
989
+ postprocessed_response = truncate_response(
990
+ self.stop_token_id, processing_class.pad_token_id, response
991
+ )
992
+ table["query"].extend(
993
+ gather_object(processing_class.batch_decode(query, skip_special_tokens=True))
994
+ )
995
+ table["model response"].extend(
996
+ gather_object(processing_class.batch_decode(postprocessed_response))
997
+ )
998
+
999
+ postprocessed_query_response = torch.cat((query, postprocessed_response), 1)
1000
+ _, score, _ = get_reward(
1001
+ self.reward_model, postprocessed_query_response, processing_class.pad_token_id, context_length
1002
+ )
1003
+ table["score"].extend(self.accelerator.gather_for_metrics(score).float().cpu().numpy())
1004
+
1005
+ if sampling:
1006
+ break
1007
+ df = pd.DataFrame(table)
1008
+
1009
+ if self.accelerator.is_main_process:
1010
+ if is_rich_available():
1011
+ print_rich_table(df.iloc[0 : 0 + 5])
1012
+ if "wandb" in args.report_to:
1013
+ import wandb
1014
+
1015
+ if wandb.run is not None:
1016
+ wandb.log({"completions": wandb.Table(dataframe=df)})
1017
+
1018
+ if "comet_ml" in args.report_to:
1019
+ log_table_to_comet_experiment(
1020
+ name="completions.csv",
1021
+ table=df,
1022
+ )
1023
+
1024
+ # Ensure the model card is saved along with the checkpoint
1025
+ def _save_checkpoint(self, model, trial):
1026
+ if self.args.hub_model_id is None:
1027
+ model_name = Path(self.args.output_dir).name
1028
+ else:
1029
+ model_name = self.args.hub_model_id.split("/")[-1]
1030
+ self.create_model_card(model_name=model_name)
1031
+ super()._save_checkpoint(model, trial)
tasks/tasksmith-0ea2241cceeb/tests/source/trl/experimental/prm/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 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 .prm_config import PRMConfig
16
+ from .prm_trainer import PRMTrainer
17
+
18
+
19
+ __all__ = ["PRMConfig", "PRMTrainer"]