AdithyaSK HF Staff commited on
Commit
88131d4
·
verified ·
1 Parent(s): 9362b47

Stage Harbor release files 34001-34500

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-5b4f21a2a450/tests/source/tests/experimental/test_utils.py +160 -0
  2. tasks/tasksmith-5b4f21a2a450/tests/source/tests/experimental/test_xpo_trainer.py +143 -0
  3. tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/README.md +57 -0
  4. tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/__init__.py +14 -0
  5. tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/dpo.json +280 -0
  6. tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/sft.json +280 -0
  7. tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/sft_fa2.json +281 -0
  8. tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/test_invariant.py +296 -0
  9. tasks/tasksmith-5b4f21a2a450/tests/source/tests/tasksmith_behavior.py +201 -0
  10. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_activation_offloading.py +237 -0
  11. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_callbacks.py +238 -0
  12. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_chat_template_utils.py +1255 -0
  13. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_cli.py +140 -0
  14. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_cli_utils.py +426 -0
  15. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_data_utils.py +1335 -0
  16. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_dpo_trainer.py +1286 -0
  17. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_grpo_trainer.py +0 -0
  18. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_model_utils.py +34 -0
  19. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_reward_trainer.py +837 -0
  20. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rewards.py +215 -0
  21. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rich_progress_callback.py +64 -0
  22. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rloo_trainer.py +1767 -0
  23. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_sft_trainer.py +0 -0
  24. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_skills.py +578 -0
  25. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_skills_cli.py +288 -0
  26. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_utils.py +1380 -0
  27. tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_vllm_client_server.py +1036 -0
  28. tasks/tasksmith-5b4f21a2a450/tests/source/tests/testing_constants.py +18 -0
  29. tasks/tasksmith-5b4f21a2a450/tests/source/tests/testing_utils.py +148 -0
  30. tasks/tasksmith-5b4f21a2a450/tests/source/trl/__init__.py +132 -0
  31. tasks/tasksmith-5b4f21a2a450/tests/source/trl/_compat.py +164 -0
  32. tasks/tasksmith-5b4f21a2a450/tests/source/trl/_lazy_module.py +79 -0
  33. tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/fsdp1.yaml +28 -0
  34. tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/fsdp2.yaml +25 -0
  35. tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/multi_gpu.yaml +16 -0
  36. tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/single_gpu.yaml +16 -0
  37. tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero1.yaml +20 -0
  38. tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero2.yaml +21 -0
  39. tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero3.yaml +22 -0
  40. tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_template_utils.py +939 -0
  41. tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/README.md +254 -0
  42. tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere.jinja +1 -0
  43. tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere2.jinja +20 -0
  44. tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere2_training.jinja +25 -0
  45. tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere_training.jinja +6 -0
  46. tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/deepseekv3.jinja +1 -0
  47. tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/deepseekv3_training.jinja +8 -0
  48. tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma.jinja +4 -0
  49. tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma3.jinja +47 -0
  50. tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma3_training.jinja +72 -0
tasks/tasksmith-5b4f21a2a450/tests/source/tests/experimental/test_utils.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 datasets import Dataset, load_dataset
17
+ from transformers import AutoTokenizer
18
+
19
+ from trl.experimental.utils import DataCollatorForChatML, truncate_dataset
20
+
21
+ from ..testing_utils import TrlTestCase
22
+
23
+
24
+ class TestDataCollatorForChatML(TrlTestCase):
25
+ def setup_method(self):
26
+ # Initialize the tokenizer
27
+ self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
28
+ if self.tokenizer.pad_token is None:
29
+ self.tokenizer.pad_token = self.tokenizer.eos_token
30
+
31
+ # Define token IDs
32
+ self.bos_token_id = self.tokenizer.bos_token_id if self.tokenizer.bos_token_id is not None else 1
33
+ self.eos_token_id = self.tokenizer.eos_token_id if self.tokenizer.eos_token_id is not None else 2
34
+ # Token ID for "true", the last assistant's response in the example:
35
+ self.ignore_index = -100
36
+ self.max_length = 1024
37
+ self.messages_key = "messages"
38
+
39
+ # Example input
40
+ dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train")
41
+ self.examples = dataset.to_list()
42
+
43
+ # Initialize the data collator
44
+ self.collator = DataCollatorForChatML(
45
+ tokenizer=self.tokenizer,
46
+ max_length=self.max_length,
47
+ ignore_index=self.ignore_index,
48
+ )
49
+
50
+ def test_data_collator_for_chatml(self):
51
+ # Process the data
52
+ data = self.collator(self.examples)
53
+
54
+ # Verify basic shapes and types
55
+ assert "input_ids" in data
56
+ assert "attention_mask" in data
57
+ assert "labels" in data
58
+ assert "prompts" in data
59
+ assert "prompt_attention_mask" in data
60
+
61
+ # Decode input_ids and labels for verification
62
+ input_ids = data["input_ids"][0].tolist()
63
+ labels = data["labels"][0].tolist()
64
+ prompt_only = data["prompts"][0].tolist()
65
+
66
+ # Get the last assistant's response for comparison
67
+ last_message = self.examples[0][self.messages_key][-1]
68
+ assert last_message["role"] == "assistant", "Last message should be from assistant"
69
+ last_assistant_response = last_message["content"]
70
+
71
+ # Verify that input_ids contain both prompt and response
72
+ decoded_input = self.tokenizer.decode(input_ids)
73
+ assert last_assistant_response in decoded_input, "Input should contain assistant's response"
74
+
75
+ # Verify that prompts only contain the conversation up to the last response
76
+ decoded_prompt = self.tokenizer.decode(prompt_only)
77
+ assert last_assistant_response not in decoded_prompt, "Prompt should not contain assistant's response"
78
+
79
+ # Verify labels are -100 for non-assistant parts
80
+ prompt_length = len(prompt_only)
81
+ assert all(label == self.ignore_index for label in labels[:prompt_length]), (
82
+ "Labels should be ignore_index for prompt tokens"
83
+ )
84
+
85
+ # Verify labels match assistant response after prompt
86
+ # Add a filter to remove any trailing tokens after the first <|im_end|>
87
+ last_assistant_response_with_end = last_assistant_response + self.tokenizer.eos_token
88
+ last_assistant_response_tokens = self.tokenizer.encode(
89
+ last_assistant_response_with_end, add_special_tokens=False
90
+ )
91
+
92
+ response_labels = []
93
+ for label in labels[prompt_length:]:
94
+ if label == self.ignore_index:
95
+ continue
96
+ response_labels.append(label)
97
+ if label == self.tokenizer.convert_tokens_to_ids("<|im_end|>"):
98
+ break
99
+ assert response_labels == last_assistant_response_tokens, "Labels should match assistant response tokens"
100
+
101
+ # Verify there isn't a generation prompt at the end
102
+ generation_prompt = "<|im_start|>assistant"
103
+ assert not decoded_input.strip().endswith(generation_prompt), (
104
+ f"Input should not end with generation prompt '{generation_prompt}'"
105
+ )
106
+
107
+ assert response_labels == last_assistant_response_tokens, "Labels should match assistant response tokens"
108
+
109
+
110
+ class TestTruncateExamples(TrlTestCase):
111
+ def test_with_dataset(self):
112
+ examples = {
113
+ "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]],
114
+ "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]],
115
+ }
116
+ dataset = Dataset.from_dict(examples)
117
+ dataset = dataset.with_format("numpy", dtype="float32")
118
+ format = dataset.format
119
+ max_length = 2
120
+ expected_output = {
121
+ "input_ids": [[1, 2], [4, 5], [8]],
122
+ "attention_mask": [[0, 1], [0, 0], [1]],
123
+ }
124
+ dataset = truncate_dataset(dataset, max_length)
125
+ assert dataset.to_dict() == expected_output
126
+ assert format == dataset.format
127
+
128
+ def test_with_iterable_dataset(self):
129
+ examples = {
130
+ "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]],
131
+ "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]],
132
+ }
133
+ dataset = Dataset.from_dict(examples).to_iterable_dataset()
134
+ dataset = dataset.with_format("numpy")
135
+ formatting = dataset._formatting
136
+ max_length = 2
137
+ expected_output = {
138
+ "input_ids": [[1, 2], [4, 5], [8]],
139
+ "attention_mask": [[0, 1], [0, 0], [1]],
140
+ }
141
+ dataset = truncate_dataset(dataset, max_length)
142
+ num_examples = len(examples[next(iter(examples))])
143
+ assert next(iter(dataset.with_format(None).batch(batch_size=num_examples))) == expected_output
144
+ assert formatting == dataset._formatting
145
+
146
+ def test_with_extra_column(self):
147
+ examples = {
148
+ "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]],
149
+ "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]],
150
+ "my_column": ["a", "b", "c"],
151
+ }
152
+ dataset = Dataset.from_dict(examples)
153
+ max_length = 2
154
+ expected_output = {
155
+ "input_ids": [[1, 2], [4, 5], [8]],
156
+ "attention_mask": [[0, 1], [0, 0], [1]],
157
+ "my_column": ["a", "b", "c"],
158
+ }
159
+ dataset = truncate_dataset(dataset, max_length)
160
+ assert dataset.to_dict() == expected_output
tasks/tasksmith-5b4f21a2a450/tests/source/tests/experimental/test_xpo_trainer.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 pytest
16
+ from datasets import load_dataset
17
+ from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer
18
+ from transformers.utils import is_peft_available
19
+
20
+ from trl.experimental.xpo import XPOConfig, XPOTrainer
21
+
22
+ from ..testing_utils import TrlTestCase, require_peft
23
+
24
+
25
+ if is_peft_available():
26
+ from peft import LoraConfig, get_peft_model
27
+
28
+
29
+ @pytest.mark.low_priority
30
+ class TestXPOTrainer(TrlTestCase):
31
+ def setup_method(self):
32
+ self.model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
33
+ self.model = AutoModelForCausalLM.from_pretrained(self.model_id, dtype="float32")
34
+ self.ref_model = AutoModelForCausalLM.from_pretrained(self.model_id)
35
+ self.reward_model = AutoModelForSequenceClassification.from_pretrained(self.model_id, num_labels=1)
36
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
37
+ self.tokenizer.pad_token = self.tokenizer.eos_token
38
+
39
+ @pytest.mark.parametrize("config_name", ["standard_prompt_only", "conversational_prompt_only"])
40
+ def test_xpo_trainer_training(self, config_name):
41
+ training_args = XPOConfig(
42
+ output_dir=self.tmp_dir,
43
+ per_device_train_batch_size=2,
44
+ max_steps=3,
45
+ remove_unused_columns=False,
46
+ gradient_accumulation_steps=1,
47
+ learning_rate=9e-1,
48
+ report_to="none",
49
+ )
50
+ dataset = load_dataset("trl-internal-testing/zen", config_name, split="train")
51
+
52
+ trainer = XPOTrainer(
53
+ model=self.model,
54
+ ref_model=self.ref_model,
55
+ reward_funcs=self.reward_model,
56
+ args=training_args,
57
+ processing_class=self.tokenizer,
58
+ train_dataset=dataset,
59
+ )
60
+
61
+ trainer.train()
62
+
63
+ assert "train_loss" in trainer.state.log_history[-1]
64
+
65
+ @require_peft
66
+ def test_train_with_peft(self):
67
+ lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM")
68
+ training_args = XPOConfig(
69
+ output_dir=self.tmp_dir,
70
+ per_device_train_batch_size=2,
71
+ max_steps=3,
72
+ learning_rate=5.0e-7,
73
+ report_to="none",
74
+ )
75
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
76
+
77
+ trainer = XPOTrainer(
78
+ model=self.model,
79
+ reward_funcs=self.reward_model,
80
+ args=training_args,
81
+ processing_class=self.tokenizer,
82
+ train_dataset=dataset,
83
+ peft_config=lora_config,
84
+ )
85
+
86
+ trainer.train()
87
+
88
+ assert "train_loss" in trainer.state.log_history[-1]
89
+
90
+ @require_peft
91
+ def test_train_with_peft_and_ref_model(self):
92
+ lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM")
93
+ training_args = XPOConfig(
94
+ output_dir=self.tmp_dir,
95
+ per_device_train_batch_size=2,
96
+ max_steps=3,
97
+ learning_rate=5.0e-7,
98
+ report_to="none",
99
+ )
100
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
101
+
102
+ trainer = XPOTrainer(
103
+ model=self.model,
104
+ ref_model=self.ref_model,
105
+ reward_funcs=self.reward_model,
106
+ args=training_args,
107
+ processing_class=self.tokenizer,
108
+ train_dataset=dataset,
109
+ peft_config=lora_config,
110
+ )
111
+
112
+ trainer.train()
113
+
114
+ assert "train_loss" in trainer.state.log_history[-1]
115
+
116
+ @require_peft
117
+ def test_train_pre_pefted_model_implicit_ref(self):
118
+ lora_config = LoraConfig(r=8, lora_alpha=16, lora_dropout=0.1, bias="none", task_type="CAUSAL_LM")
119
+ peft_model_instance = get_peft_model(self.model, lora_config)
120
+
121
+ training_args = XPOConfig(
122
+ output_dir=self.tmp_dir,
123
+ per_device_train_batch_size=1,
124
+ max_steps=2,
125
+ learning_rate=5.0e-7,
126
+ eval_strategy="no",
127
+ report_to="none",
128
+ remove_unused_columns=False,
129
+ )
130
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
131
+
132
+ trainer = XPOTrainer(
133
+ model=peft_model_instance,
134
+ ref_model=None,
135
+ reward_funcs=self.reward_model, # Using reward_model to ensure _generate_completions is used as expected
136
+ args=training_args,
137
+ processing_class=self.tokenizer,
138
+ train_dataset=dataset,
139
+ )
140
+
141
+ trainer.train()
142
+
143
+ assert "train_loss" in trainer.state.log_history[-1]
tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/README.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Training invariant tests
2
+
3
+ Catches silent training bugs that don't fail unit tests but shift the training trajectory. Runs on real models, opt-in only.
4
+
5
+ ## How it works
6
+
7
+ Configs are grouped into **equivalence classes**: configs in the same class must produce the same trajectory (e.g. PDB=1×GAS=8 must equal PDB=8×GAS=1, FA2 must equal eager). Each class has one **canonical** config (the first one) that owns the class's reference snapshot. Every config in the class — canonical included — is asserted to match the saved reference. This catches both invariant breakage (a non-canonical config drifting away from the canonical's pinned trajectory) and numerical regressions (the canonical itself drifting from its committed snapshot across versions).
8
+
9
+ Recording the references is a separate concern from testing them, so it's a separate entry point (`python tests/invariant/test_invariant.py`).
10
+
11
+ Each config is a `trl <method>` CLI invocation with a fixed set of args. The harness shells out (`subprocess.run(["trl", method, ...])`), the CLI runs end to end, writes `trainer_state.json` to its `--output_dir`, and the harness parses the `log_history` into a `Trajectory`.
12
+
13
+ This means the suite tests the actual user-facing entry point, not the Python API. Catches CLI-only bugs (arg parsing, defaults, dispatch) for free. Distributed runs are an additive change: prepend `accelerate launch --config_file <strategy>.yaml` to the same command.
14
+
15
+ ## Scope (initial)
16
+
17
+ - Trainers: `trl sft`, `trl dpo`
18
+ - Model: `Qwen/Qwen2.5-0.5B-Instruct` (pinned revision)
19
+ - Equivalence classes:
20
+ - `sft`: `sft_default` (canonical), `sft_pdb1_gas8` (gradient accumulation), `sft_attn_fa2_kernels` (FA2 via kernels)
21
+ - `dpo`: `dpo_default` (canonical), `dpo_pdb1_gas8` (gradient accumulation)
22
+ - Single GPU, fp32, fixed seed, ~50 optimizer steps.
23
+
24
+ Other axes (sharding, DDP, more trainers) are deferred and will be additive.
25
+
26
+ ## Trajectory
27
+
28
+ Per optimizer step: `loss`, `grad_norm`. One JSON per equivalence class in `references/` (`sft.json`, `dpo.json`):
29
+
30
+ ```json
31
+ {
32
+ "config": {"name": "sft_default", "method": "sft", "args": {...}},
33
+ "env": {"accelerate": "...", "torch": "...", "transformers": "...", "trl": "...", "gpu": "H100-80GB"},
34
+ "steps": [{"step": 1, "loss": 1.234, "grad_norm": 0.567}, ...]
35
+ }
36
+ ```
37
+
38
+ ## Comparison
39
+
40
+ Scalar series with absolute tolerance + zero-mean-residual. The residual check is what flags bugs like GAS-dropping — they show up as a one-sided systematic shift in the loss curve, not as point-wise outliers.
41
+
42
+ ## Hardware
43
+
44
+ Reference snapshots are recorded on **H100 80GB** (pinned in `references/env.lock`).
45
+
46
+ ## Running
47
+
48
+ ```bash
49
+ # test
50
+ pytest tests/invariant/ -m invariant
51
+
52
+ # record references
53
+ python tests/invariant/test_invariant.py # all classes
54
+ python tests/invariant/test_invariant.py sft # one class
55
+ ```
56
+
57
+ Snapshot updates must be justified in the PR description.
tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/dpo.json ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "config": {
3
+ "name": "dpo_default",
4
+ "method": "dpo",
5
+ "args": {
6
+ "model_name_or_path": "Qwen/Qwen2.5-0.5B-Instruct",
7
+ "model_revision": "7ae557604adf67be50417f59c2c2f167def9a775",
8
+ "attn_implementation": "eager",
9
+ "dataset_name": "trl-lib/ultrafeedback_binarized",
10
+ "max_steps": "50",
11
+ "max_length": "512",
12
+ "logging_steps": "1",
13
+ "report_to": "none",
14
+ "seed": "42",
15
+ "data_seed": "42",
16
+ "full_determinism": "True",
17
+ "bf16": "False"
18
+ }
19
+ },
20
+ "env": {
21
+ "accelerate": "1.13.0",
22
+ "torch": "2.10.0+cu128",
23
+ "transformers": "5.10.0.dev0",
24
+ "trl": "f4e94c0c10654ab57b94e7cd8096ed4f12246e03",
25
+ "python": "3.13.13",
26
+ "gpu": "NVIDIA H100 80GB HBM3"
27
+ },
28
+ "steps": [
29
+ {
30
+ "step": 1,
31
+ "loss": 0.6931471824645996,
32
+ "grad_norm": 157.25071716308594
33
+ },
34
+ {
35
+ "step": 2,
36
+ "loss": 0.6901174783706665,
37
+ "grad_norm": 108.38384246826172
38
+ },
39
+ {
40
+ "step": 3,
41
+ "loss": 0.6326549053192139,
42
+ "grad_norm": 140.2856903076172
43
+ },
44
+ {
45
+ "step": 4,
46
+ "loss": 0.7054474353790283,
47
+ "grad_norm": 151.10508728027344
48
+ },
49
+ {
50
+ "step": 5,
51
+ "loss": 0.7342866063117981,
52
+ "grad_norm": 157.84791564941406
53
+ },
54
+ {
55
+ "step": 6,
56
+ "loss": 0.6869831085205078,
57
+ "grad_norm": 137.7687530517578
58
+ },
59
+ {
60
+ "step": 7,
61
+ "loss": 0.7037957906723022,
62
+ "grad_norm": 130.58058166503906
63
+ },
64
+ {
65
+ "step": 8,
66
+ "loss": 0.671793520450592,
67
+ "grad_norm": 164.77792358398438
68
+ },
69
+ {
70
+ "step": 9,
71
+ "loss": 0.6760100722312927,
72
+ "grad_norm": 102.67815399169922
73
+ },
74
+ {
75
+ "step": 10,
76
+ "loss": 0.6628016233444214,
77
+ "grad_norm": 123.41923522949219
78
+ },
79
+ {
80
+ "step": 11,
81
+ "loss": 0.6634430885314941,
82
+ "grad_norm": 83.91616821289062
83
+ },
84
+ {
85
+ "step": 12,
86
+ "loss": 0.7321300506591797,
87
+ "grad_norm": 161.53366088867188
88
+ },
89
+ {
90
+ "step": 13,
91
+ "loss": 0.7024844884872437,
92
+ "grad_norm": 150.16744995117188
93
+ },
94
+ {
95
+ "step": 14,
96
+ "loss": 0.6837225556373596,
97
+ "grad_norm": 123.26526641845703
98
+ },
99
+ {
100
+ "step": 15,
101
+ "loss": 0.7167133092880249,
102
+ "grad_norm": 133.57534790039062
103
+ },
104
+ {
105
+ "step": 16,
106
+ "loss": 0.6835181713104248,
107
+ "grad_norm": 124.6922378540039
108
+ },
109
+ {
110
+ "step": 17,
111
+ "loss": 0.6272522211074829,
112
+ "grad_norm": 100.10560607910156
113
+ },
114
+ {
115
+ "step": 18,
116
+ "loss": 0.8025375604629517,
117
+ "grad_norm": 198.8187713623047
118
+ },
119
+ {
120
+ "step": 19,
121
+ "loss": 0.7497490048408508,
122
+ "grad_norm": 136.41639709472656
123
+ },
124
+ {
125
+ "step": 20,
126
+ "loss": 0.7327032089233398,
127
+ "grad_norm": 135.1873016357422
128
+ },
129
+ {
130
+ "step": 21,
131
+ "loss": 0.8468657732009888,
132
+ "grad_norm": 183.79238891601562
133
+ },
134
+ {
135
+ "step": 22,
136
+ "loss": 0.6504813432693481,
137
+ "grad_norm": 119.43262481689453
138
+ },
139
+ {
140
+ "step": 23,
141
+ "loss": 0.8200190663337708,
142
+ "grad_norm": 221.7334747314453
143
+ },
144
+ {
145
+ "step": 24,
146
+ "loss": 0.6116989850997925,
147
+ "grad_norm": 134.1520233154297
148
+ },
149
+ {
150
+ "step": 25,
151
+ "loss": 0.715190052986145,
152
+ "grad_norm": 160.9645538330078
153
+ },
154
+ {
155
+ "step": 26,
156
+ "loss": 0.78664231300354,
157
+ "grad_norm": 173.35397338867188
158
+ },
159
+ {
160
+ "step": 27,
161
+ "loss": 0.627922534942627,
162
+ "grad_norm": 118.79180145263672
163
+ },
164
+ {
165
+ "step": 28,
166
+ "loss": 0.6171221733093262,
167
+ "grad_norm": 143.510986328125
168
+ },
169
+ {
170
+ "step": 29,
171
+ "loss": 0.7258801460266113,
172
+ "grad_norm": 166.77137756347656
173
+ },
174
+ {
175
+ "step": 30,
176
+ "loss": 0.6643164157867432,
177
+ "grad_norm": 109.94638061523438
178
+ },
179
+ {
180
+ "step": 31,
181
+ "loss": 0.8424814343452454,
182
+ "grad_norm": 155.43392944335938
183
+ },
184
+ {
185
+ "step": 32,
186
+ "loss": 0.6372821927070618,
187
+ "grad_norm": 165.25477600097656
188
+ },
189
+ {
190
+ "step": 33,
191
+ "loss": 0.6878336668014526,
192
+ "grad_norm": 132.20591735839844
193
+ },
194
+ {
195
+ "step": 34,
196
+ "loss": 0.7095304131507874,
197
+ "grad_norm": 168.26194763183594
198
+ },
199
+ {
200
+ "step": 35,
201
+ "loss": 0.6994724273681641,
202
+ "grad_norm": 126.31066131591797
203
+ },
204
+ {
205
+ "step": 36,
206
+ "loss": 0.6479494571685791,
207
+ "grad_norm": 162.87469482421875
208
+ },
209
+ {
210
+ "step": 37,
211
+ "loss": 0.7106008529663086,
212
+ "grad_norm": 142.19422912597656
213
+ },
214
+ {
215
+ "step": 38,
216
+ "loss": 0.6147706508636475,
217
+ "grad_norm": 124.1236343383789
218
+ },
219
+ {
220
+ "step": 39,
221
+ "loss": 0.6274570226669312,
222
+ "grad_norm": 97.5869369506836
223
+ },
224
+ {
225
+ "step": 40,
226
+ "loss": 0.5677652359008789,
227
+ "grad_norm": 99.20594787597656
228
+ },
229
+ {
230
+ "step": 41,
231
+ "loss": 0.5417441129684448,
232
+ "grad_norm": 136.53424072265625
233
+ },
234
+ {
235
+ "step": 42,
236
+ "loss": 0.6146669983863831,
237
+ "grad_norm": 117.05335998535156
238
+ },
239
+ {
240
+ "step": 43,
241
+ "loss": 0.5652309656143188,
242
+ "grad_norm": 141.68212890625
243
+ },
244
+ {
245
+ "step": 44,
246
+ "loss": 0.6843374967575073,
247
+ "grad_norm": 123.86646270751953
248
+ },
249
+ {
250
+ "step": 45,
251
+ "loss": 0.700664758682251,
252
+ "grad_norm": 176.58290100097656
253
+ },
254
+ {
255
+ "step": 46,
256
+ "loss": 0.627228856086731,
257
+ "grad_norm": 93.38623046875
258
+ },
259
+ {
260
+ "step": 47,
261
+ "loss": 0.6068558096885681,
262
+ "grad_norm": 144.66879272460938
263
+ },
264
+ {
265
+ "step": 48,
266
+ "loss": 0.7041699886322021,
267
+ "grad_norm": 147.3819122314453
268
+ },
269
+ {
270
+ "step": 49,
271
+ "loss": 0.6936260461807251,
272
+ "grad_norm": 114.99978637695312
273
+ },
274
+ {
275
+ "step": 50,
276
+ "loss": 0.8024596571922302,
277
+ "grad_norm": 156.8375244140625
278
+ }
279
+ ]
280
+ }
tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/sft.json ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "config": {
3
+ "name": "sft_default",
4
+ "method": "sft",
5
+ "args": {
6
+ "model_name_or_path": "Qwen/Qwen2.5-0.5B-Instruct",
7
+ "model_revision": "7ae557604adf67be50417f59c2c2f167def9a775",
8
+ "attn_implementation": "eager",
9
+ "dataset_name": "trl-lib/Capybara",
10
+ "max_steps": "50",
11
+ "max_length": "512",
12
+ "logging_steps": "1",
13
+ "report_to": "none",
14
+ "seed": "42",
15
+ "data_seed": "42",
16
+ "full_determinism": "True",
17
+ "bf16": "False"
18
+ }
19
+ },
20
+ "env": {
21
+ "accelerate": "1.13.0",
22
+ "torch": "2.10.0+cu128",
23
+ "transformers": "5.10.0.dev0",
24
+ "trl": "f4e94c0c10654ab57b94e7cd8096ed4f12246e03",
25
+ "python": "3.13.13",
26
+ "gpu": "NVIDIA H100 80GB HBM3"
27
+ },
28
+ "steps": [
29
+ {
30
+ "step": 1,
31
+ "loss": 2.3842217922210693,
32
+ "grad_norm": 28.170888900756836
33
+ },
34
+ {
35
+ "step": 2,
36
+ "loss": 1.4120551347732544,
37
+ "grad_norm": 16.11708641052246
38
+ },
39
+ {
40
+ "step": 3,
41
+ "loss": 1.6543627977371216,
42
+ "grad_norm": 9.521869659423828
43
+ },
44
+ {
45
+ "step": 4,
46
+ "loss": 1.548227071762085,
47
+ "grad_norm": 9.530509948730469
48
+ },
49
+ {
50
+ "step": 5,
51
+ "loss": 1.3084965944290161,
52
+ "grad_norm": 13.43132209777832
53
+ },
54
+ {
55
+ "step": 6,
56
+ "loss": 1.4568636417388916,
57
+ "grad_norm": 11.567093849182129
58
+ },
59
+ {
60
+ "step": 7,
61
+ "loss": 1.6642777919769287,
62
+ "grad_norm": 8.233135223388672
63
+ },
64
+ {
65
+ "step": 8,
66
+ "loss": 1.6268576383590698,
67
+ "grad_norm": 6.363206386566162
68
+ },
69
+ {
70
+ "step": 9,
71
+ "loss": 1.5339726209640503,
72
+ "grad_norm": 6.955142974853516
73
+ },
74
+ {
75
+ "step": 10,
76
+ "loss": 1.547467827796936,
77
+ "grad_norm": 5.978666305541992
78
+ },
79
+ {
80
+ "step": 11,
81
+ "loss": 1.7950178384780884,
82
+ "grad_norm": 7.241233825683594
83
+ },
84
+ {
85
+ "step": 12,
86
+ "loss": 1.8137775659561157,
87
+ "grad_norm": 8.63271713256836
88
+ },
89
+ {
90
+ "step": 13,
91
+ "loss": 1.3856267929077148,
92
+ "grad_norm": 6.400929927825928
93
+ },
94
+ {
95
+ "step": 14,
96
+ "loss": 1.3795125484466553,
97
+ "grad_norm": 6.382791996002197
98
+ },
99
+ {
100
+ "step": 15,
101
+ "loss": 1.3708516359329224,
102
+ "grad_norm": 6.692564010620117
103
+ },
104
+ {
105
+ "step": 16,
106
+ "loss": 1.8075040578842163,
107
+ "grad_norm": 7.801014423370361
108
+ },
109
+ {
110
+ "step": 17,
111
+ "loss": 1.254800796508789,
112
+ "grad_norm": 5.860067367553711
113
+ },
114
+ {
115
+ "step": 18,
116
+ "loss": 1.6014561653137207,
117
+ "grad_norm": 7.397754669189453
118
+ },
119
+ {
120
+ "step": 19,
121
+ "loss": 1.5693073272705078,
122
+ "grad_norm": 6.078225612640381
123
+ },
124
+ {
125
+ "step": 20,
126
+ "loss": 1.2925223112106323,
127
+ "grad_norm": 6.285624027252197
128
+ },
129
+ {
130
+ "step": 21,
131
+ "loss": 1.261284589767456,
132
+ "grad_norm": 5.98115348815918
133
+ },
134
+ {
135
+ "step": 22,
136
+ "loss": 1.016650676727295,
137
+ "grad_norm": 6.040045261383057
138
+ },
139
+ {
140
+ "step": 23,
141
+ "loss": 1.222269058227539,
142
+ "grad_norm": 6.034141540527344
143
+ },
144
+ {
145
+ "step": 24,
146
+ "loss": 1.45418381690979,
147
+ "grad_norm": 6.263362407684326
148
+ },
149
+ {
150
+ "step": 25,
151
+ "loss": 1.23504638671875,
152
+ "grad_norm": 5.99455451965332
153
+ },
154
+ {
155
+ "step": 26,
156
+ "loss": 1.2722694873809814,
157
+ "grad_norm": 5.834524631500244
158
+ },
159
+ {
160
+ "step": 27,
161
+ "loss": 2.2606589794158936,
162
+ "grad_norm": 7.2228522300720215
163
+ },
164
+ {
165
+ "step": 28,
166
+ "loss": 1.4542038440704346,
167
+ "grad_norm": 6.190547466278076
168
+ },
169
+ {
170
+ "step": 29,
171
+ "loss": 1.3753437995910645,
172
+ "grad_norm": 5.7064290046691895
173
+ },
174
+ {
175
+ "step": 30,
176
+ "loss": 1.0842117071151733,
177
+ "grad_norm": 6.300862789154053
178
+ },
179
+ {
180
+ "step": 31,
181
+ "loss": 1.6317358016967773,
182
+ "grad_norm": 6.022386074066162
183
+ },
184
+ {
185
+ "step": 32,
186
+ "loss": 1.4107545614242554,
187
+ "grad_norm": 6.697302341461182
188
+ },
189
+ {
190
+ "step": 33,
191
+ "loss": 1.5427740812301636,
192
+ "grad_norm": 6.703666687011719
193
+ },
194
+ {
195
+ "step": 34,
196
+ "loss": 1.0882741212844849,
197
+ "grad_norm": 6.260556697845459
198
+ },
199
+ {
200
+ "step": 35,
201
+ "loss": 2.1459619998931885,
202
+ "grad_norm": 6.938933849334717
203
+ },
204
+ {
205
+ "step": 36,
206
+ "loss": 1.7524574995040894,
207
+ "grad_norm": 6.392754554748535
208
+ },
209
+ {
210
+ "step": 37,
211
+ "loss": 1.558825135231018,
212
+ "grad_norm": 7.106125831604004
213
+ },
214
+ {
215
+ "step": 38,
216
+ "loss": 1.5750346183776855,
217
+ "grad_norm": 6.705704689025879
218
+ },
219
+ {
220
+ "step": 39,
221
+ "loss": 1.0681045055389404,
222
+ "grad_norm": 5.93332576751709
223
+ },
224
+ {
225
+ "step": 40,
226
+ "loss": 1.4508510828018188,
227
+ "grad_norm": 6.193344593048096
228
+ },
229
+ {
230
+ "step": 41,
231
+ "loss": 1.5779269933700562,
232
+ "grad_norm": 6.469877243041992
233
+ },
234
+ {
235
+ "step": 42,
236
+ "loss": 1.2731173038482666,
237
+ "grad_norm": 6.590377330780029
238
+ },
239
+ {
240
+ "step": 43,
241
+ "loss": 1.34458327293396,
242
+ "grad_norm": 5.618240833282471
243
+ },
244
+ {
245
+ "step": 44,
246
+ "loss": 1.5110447406768799,
247
+ "grad_norm": 5.829492092132568
248
+ },
249
+ {
250
+ "step": 45,
251
+ "loss": 1.9833546876907349,
252
+ "grad_norm": 6.42317533493042
253
+ },
254
+ {
255
+ "step": 46,
256
+ "loss": 2.0645744800567627,
257
+ "grad_norm": 7.079426288604736
258
+ },
259
+ {
260
+ "step": 47,
261
+ "loss": 1.0404279232025146,
262
+ "grad_norm": 5.035366535186768
263
+ },
264
+ {
265
+ "step": 48,
266
+ "loss": 1.3794283866882324,
267
+ "grad_norm": 5.685641288757324
268
+ },
269
+ {
270
+ "step": 49,
271
+ "loss": 1.4115599393844604,
272
+ "grad_norm": 6.172175407409668
273
+ },
274
+ {
275
+ "step": 50,
276
+ "loss": 1.3042362928390503,
277
+ "grad_norm": 5.568996906280518
278
+ }
279
+ ]
280
+ }
tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/references/sft_fa2.json ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "config": {
3
+ "name": "sft_fa2",
4
+ "method": "sft",
5
+ "args": {
6
+ "model_name_or_path": "Qwen/Qwen2.5-0.5B-Instruct",
7
+ "model_revision": "7ae557604adf67be50417f59c2c2f167def9a775",
8
+ "attn_implementation": "kernels-community/flash-attn2",
9
+ "dataset_name": "trl-lib/Capybara",
10
+ "max_steps": "50",
11
+ "max_length": "None",
12
+ "logging_steps": "1",
13
+ "report_to": "none",
14
+ "seed": "42",
15
+ "data_seed": "42",
16
+ "full_determinism": "True",
17
+ "bf16": "True",
18
+ "per_device_train_batch_size": "2"
19
+ }
20
+ },
21
+ "env": {
22
+ "accelerate": "1.13.0",
23
+ "torch": "2.10.0+cu128",
24
+ "transformers": "5.10.0.dev0",
25
+ "trl": "f4e94c0c10654ab57b94e7cd8096ed4f12246e03",
26
+ "python": "3.13.13",
27
+ "gpu": "NVIDIA H100 80GB HBM3"
28
+ },
29
+ "steps": [
30
+ {
31
+ "step": 1,
32
+ "loss": 2.0777087211608887,
33
+ "grad_norm": 23.311853408813477
34
+ },
35
+ {
36
+ "step": 2,
37
+ "loss": 1.5351684093475342,
38
+ "grad_norm": 18.663341522216797
39
+ },
40
+ {
41
+ "step": 3,
42
+ "loss": 1.3684718608856201,
43
+ "grad_norm": 15.328994750976562
44
+ },
45
+ {
46
+ "step": 4,
47
+ "loss": 2.432941198348999,
48
+ "grad_norm": 10.522828102111816
49
+ },
50
+ {
51
+ "step": 5,
52
+ "loss": 1.482237458229065,
53
+ "grad_norm": 14.26174259185791
54
+ },
55
+ {
56
+ "step": 6,
57
+ "loss": 1.205272912979126,
58
+ "grad_norm": 9.654252052307129
59
+ },
60
+ {
61
+ "step": 7,
62
+ "loss": 1.4993977546691895,
63
+ "grad_norm": 9.16186237335205
64
+ },
65
+ {
66
+ "step": 8,
67
+ "loss": 1.3386749029159546,
68
+ "grad_norm": 9.539480209350586
69
+ },
70
+ {
71
+ "step": 9,
72
+ "loss": 1.7551285028457642,
73
+ "grad_norm": 8.458740234375
74
+ },
75
+ {
76
+ "step": 10,
77
+ "loss": 1.6139777898788452,
78
+ "grad_norm": 47.66611099243164
79
+ },
80
+ {
81
+ "step": 11,
82
+ "loss": 1.3058594465255737,
83
+ "grad_norm": 7.0746378898620605
84
+ },
85
+ {
86
+ "step": 12,
87
+ "loss": 1.4825245141983032,
88
+ "grad_norm": 7.372246265411377
89
+ },
90
+ {
91
+ "step": 13,
92
+ "loss": 1.0571527481079102,
93
+ "grad_norm": 9.301342010498047
94
+ },
95
+ {
96
+ "step": 14,
97
+ "loss": 1.2916768789291382,
98
+ "grad_norm": 6.207754135131836
99
+ },
100
+ {
101
+ "step": 15,
102
+ "loss": 1.3111194372177124,
103
+ "grad_norm": 9.410601615905762
104
+ },
105
+ {
106
+ "step": 16,
107
+ "loss": 1.5206763744354248,
108
+ "grad_norm": 9.227742195129395
109
+ },
110
+ {
111
+ "step": 17,
112
+ "loss": 1.580748438835144,
113
+ "grad_norm": 14.178001403808594
114
+ },
115
+ {
116
+ "step": 18,
117
+ "loss": 0.7333115935325623,
118
+ "grad_norm": 12.217166900634766
119
+ },
120
+ {
121
+ "step": 19,
122
+ "loss": 1.6668834686279297,
123
+ "grad_norm": 6.052151679992676
124
+ },
125
+ {
126
+ "step": 20,
127
+ "loss": 1.0880261659622192,
128
+ "grad_norm": 9.590500831604004
129
+ },
130
+ {
131
+ "step": 21,
132
+ "loss": 1.147664189338684,
133
+ "grad_norm": 8.589299201965332
134
+ },
135
+ {
136
+ "step": 22,
137
+ "loss": 1.0658481121063232,
138
+ "grad_norm": 6.9600419998168945
139
+ },
140
+ {
141
+ "step": 23,
142
+ "loss": 1.3873035907745361,
143
+ "grad_norm": 9.590429306030273
144
+ },
145
+ {
146
+ "step": 24,
147
+ "loss": 1.890312671661377,
148
+ "grad_norm": 19.884483337402344
149
+ },
150
+ {
151
+ "step": 25,
152
+ "loss": 1.9729206562042236,
153
+ "grad_norm": 7.790271759033203
154
+ },
155
+ {
156
+ "step": 26,
157
+ "loss": 2.0644829273223877,
158
+ "grad_norm": 6.620902061462402
159
+ },
160
+ {
161
+ "step": 27,
162
+ "loss": 0.6783545613288879,
163
+ "grad_norm": 5.400845527648926
164
+ },
165
+ {
166
+ "step": 28,
167
+ "loss": 1.4178911447525024,
168
+ "grad_norm": 11.719703674316406
169
+ },
170
+ {
171
+ "step": 29,
172
+ "loss": 2.0086207389831543,
173
+ "grad_norm": 8.36505126953125
174
+ },
175
+ {
176
+ "step": 30,
177
+ "loss": 1.5915957689285278,
178
+ "grad_norm": 7.866483688354492
179
+ },
180
+ {
181
+ "step": 31,
182
+ "loss": 1.4387072324752808,
183
+ "grad_norm": 6.462050914764404
184
+ },
185
+ {
186
+ "step": 32,
187
+ "loss": 1.1696559190750122,
188
+ "grad_norm": 7.273270606994629
189
+ },
190
+ {
191
+ "step": 33,
192
+ "loss": 1.8873889446258545,
193
+ "grad_norm": 16.88315773010254
194
+ },
195
+ {
196
+ "step": 34,
197
+ "loss": 1.742367148399353,
198
+ "grad_norm": 10.79595947265625
199
+ },
200
+ {
201
+ "step": 35,
202
+ "loss": 1.484022617340088,
203
+ "grad_norm": 7.354922294616699
204
+ },
205
+ {
206
+ "step": 36,
207
+ "loss": 1.209019422531128,
208
+ "grad_norm": 9.22113037109375
209
+ },
210
+ {
211
+ "step": 37,
212
+ "loss": 1.4977227449417114,
213
+ "grad_norm": 6.676819801330566
214
+ },
215
+ {
216
+ "step": 38,
217
+ "loss": 1.186678409576416,
218
+ "grad_norm": 6.483543395996094
219
+ },
220
+ {
221
+ "step": 39,
222
+ "loss": 1.463419795036316,
223
+ "grad_norm": 8.406513214111328
224
+ },
225
+ {
226
+ "step": 40,
227
+ "loss": 1.892924427986145,
228
+ "grad_norm": 6.2646484375
229
+ },
230
+ {
231
+ "step": 41,
232
+ "loss": 1.6282488107681274,
233
+ "grad_norm": 8.783570289611816
234
+ },
235
+ {
236
+ "step": 42,
237
+ "loss": 1.6034563779830933,
238
+ "grad_norm": 8.478983879089355
239
+ },
240
+ {
241
+ "step": 43,
242
+ "loss": 1.4728147983551025,
243
+ "grad_norm": 8.578154563903809
244
+ },
245
+ {
246
+ "step": 44,
247
+ "loss": 2.4027509689331055,
248
+ "grad_norm": 8.874027252197266
249
+ },
250
+ {
251
+ "step": 45,
252
+ "loss": 2.154872179031372,
253
+ "grad_norm": 8.062206268310547
254
+ },
255
+ {
256
+ "step": 46,
257
+ "loss": 1.3577312231063843,
258
+ "grad_norm": 8.476325035095215
259
+ },
260
+ {
261
+ "step": 47,
262
+ "loss": 1.2283380031585693,
263
+ "grad_norm": 24.45260238647461
264
+ },
265
+ {
266
+ "step": 48,
267
+ "loss": 1.87751305103302,
268
+ "grad_norm": 6.911473274230957
269
+ },
270
+ {
271
+ "step": 49,
272
+ "loss": 0.6943105459213257,
273
+ "grad_norm": 7.364080905914307
274
+ },
275
+ {
276
+ "step": 50,
277
+ "loss": 0.9754929542541504,
278
+ "grad_norm": 12.101676940917969
279
+ }
280
+ ]
281
+ }
tasks/tasksmith-5b4f21a2a450/tests/source/tests/invariant/test_invariant.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os
17
+ import platform
18
+ import subprocess
19
+ import sys
20
+ import tempfile
21
+ from dataclasses import asdict, dataclass
22
+ from pathlib import Path
23
+
24
+ import accelerate
25
+ import pytest
26
+ import torch
27
+ import transformers
28
+
29
+
30
+ MODEL = "Qwen/Qwen2.5-0.5B-Instruct"
31
+ MODEL_REVISION = "7ae557604adf67be50417f59c2c2f167def9a775"
32
+
33
+ SFT_DATASET = "trl-lib/Capybara"
34
+ DPO_DATASET = "trl-lib/ultrafeedback_binarized"
35
+
36
+ REFERENCES_DIR = Path(__file__).parent / "references"
37
+
38
+ NUM_STEPS = 50
39
+ SEED = 42
40
+ MAX_LENGTH = 512
41
+
42
+
43
+ def _trl_commit() -> str:
44
+ """Return the current trl commit SHA (with `-dirty` suffix if the working tree has uncommitted changes).
45
+
46
+ Assumes the suite is run from a `pip install -e .` checkout — the only intended setup.
47
+ """
48
+ cwd = Path(__file__).parent
49
+ sha = subprocess.run(
50
+ ["git", "-C", str(cwd), "rev-parse", "HEAD"], capture_output=True, text=True, check=True
51
+ ).stdout.strip()
52
+ dirty = subprocess.run(
53
+ ["git", "-C", str(cwd), "status", "--porcelain"], capture_output=True, text=True, check=True
54
+ ).stdout.strip()
55
+ return f"{sha}-dirty" if dirty else sha
56
+
57
+
58
+ def env_snapshot() -> dict:
59
+ return {
60
+ "accelerate": accelerate.__version__,
61
+ "torch": torch.__version__,
62
+ "transformers": transformers.__version__,
63
+ "trl": _trl_commit(),
64
+ "python": platform.python_version(),
65
+ "gpu": torch.cuda.get_device_name(0) if torch.cuda.is_available() else "cpu",
66
+ }
67
+
68
+
69
+ @dataclass
70
+ class StepRecord:
71
+ step: int
72
+ loss: float
73
+ grad_norm: float
74
+
75
+
76
+ @dataclass
77
+ class Trajectory:
78
+ config: dict
79
+ env: dict
80
+ steps: list[StepRecord]
81
+
82
+
83
+ @dataclass
84
+ class CorrectnessConfig:
85
+ name: str
86
+ method: str # "sft" | "dpo"
87
+ args: dict[str, str]
88
+ num_processes: int = 1
89
+
90
+ def cli_args(self) -> list[str]:
91
+ out: list[str] = []
92
+ for k, v in self.args.items():
93
+ out.extend([f"--{k}", v])
94
+ return out
95
+
96
+
97
+ def run(config: CorrectnessConfig) -> Trajectory:
98
+ """Invoke the trl CLI as a subprocess; parse its trainer_state.json into a Trajectory."""
99
+ with tempfile.TemporaryDirectory() as tmpdir:
100
+ cmd = ["trl", config.method]
101
+ cmd += ["--num_processes", str(config.num_processes)]
102
+ cmd += ["--output_dir", tmpdir, *config.cli_args()]
103
+ env = {**os.environ, "CUDA_VISIBLE_DEVICES": ",".join(str(i) for i in range(config.num_processes))}
104
+ subprocess.run(cmd, check=True, env=env)
105
+
106
+ state_paths = list(Path(tmpdir).glob("**/trainer_state.json"))
107
+ if not state_paths:
108
+ raise RuntimeError(f"trainer_state.json not produced in {tmpdir}")
109
+ state = json.loads(state_paths[0].read_text())
110
+
111
+ steps = [
112
+ StepRecord(
113
+ step=int(log["step"]),
114
+ loss=float(log["loss"]),
115
+ grad_norm=float(log["grad_norm"]),
116
+ )
117
+ for log in state["log_history"]
118
+ if "loss" in log # skip eval and final-summary entries
119
+ ]
120
+
121
+ return Trajectory(
122
+ config={"name": config.name, "method": config.method, "args": config.args},
123
+ env=env_snapshot(),
124
+ steps=steps,
125
+ )
126
+
127
+
128
+ def save(trajectory: Trajectory, path: Path) -> None:
129
+ path.parent.mkdir(parents=True, exist_ok=True)
130
+ path.write_text(json.dumps(asdict(trajectory), indent=2))
131
+
132
+
133
+ def load(path: Path) -> Trajectory:
134
+ data = json.loads(path.read_text())
135
+ return Trajectory(
136
+ config=data["config"],
137
+ env=data["env"],
138
+ steps=[StepRecord(**s) for s in data["steps"]],
139
+ )
140
+
141
+
142
+ def compare_scalars(a: Trajectory, b: Trajectory, tol: dict[str, float], residual_tol: dict[str, float]) -> list[str]:
143
+ """Compare scalar series (loss, grad_norm). `tol` and `residual_tol` are per-field dicts keyed by `'loss'` and
144
+ `'grad_norm'`."""
145
+ errors: list[str] = []
146
+ if len(a.steps) != len(b.steps):
147
+ return [f"length mismatch: {len(a.steps)} vs {len(b.steps)}"]
148
+
149
+ for field in ("loss", "grad_norm"):
150
+ sa = [getattr(s, field) for s in a.steps]
151
+ sb = [getattr(s, field) for s in b.steps]
152
+ diffs = [x - y for x, y in zip(sa, sb, strict=False)]
153
+ max_abs = max(abs(d) for d in diffs)
154
+ if max_abs > tol[field]:
155
+ i = max(range(len(diffs)), key=lambda k: abs(diffs[k]))
156
+ step = a.steps[i].step
157
+ errors.append(
158
+ f"{field}: max |Δ|={max_abs:.3e} at step {step} (a={sa[i]:.6e}, b={sb[i]:.6e}, tol={tol[field]:.1e})"
159
+ )
160
+
161
+ mean = sum(diffs) / len(diffs)
162
+ if abs(mean) > residual_tol[field]:
163
+ errors.append(f"{field}: systematic drift, mean Δ={mean:.3e} (tol={residual_tol[field]:.1e})")
164
+
165
+ return errors
166
+
167
+
168
+ def _build(
169
+ name: str, method: str, dataset: str, attn: str = "eager", num_processes: int = 1, **overrides
170
+ ) -> CorrectnessConfig:
171
+ args: dict[str, str] = {
172
+ "model_name_or_path": MODEL,
173
+ "model_revision": MODEL_REVISION,
174
+ "attn_implementation": attn,
175
+ "dataset_name": dataset,
176
+ "max_steps": str(NUM_STEPS),
177
+ "max_length": str(MAX_LENGTH),
178
+ "logging_steps": "1",
179
+ "report_to": "none",
180
+ "seed": str(SEED),
181
+ "data_seed": str(SEED),
182
+ "full_determinism": "True",
183
+ # Force pure fp32 training for maximal determinism and to avoid bfloat16-induced divergences.
184
+ "bf16": "False",
185
+ }
186
+ args.update({k: str(v) for k, v in overrides.items()})
187
+ return CorrectnessConfig(name=name, method=method, args=args, num_processes=num_processes)
188
+
189
+
190
+ # Equivalence classes: each maps to a `members` list plus per-field `tol` (max |Δ|) and `residual_tol` (mean Δ)
191
+ # dicts. The first member is the canonical config — it owns the class's reference snapshot and is the only one
192
+ # re-recorded under `--update-references`. Every other member is asserted to match that snapshot.
193
+ # Tuning tip: run `python tests/invariant/test_invariant.py <klass> --report` to see actual Δs and set tolerances
194
+ # to ~1.5–2× the observed noise.
195
+ EQUIVALENCE_CLASSES: dict[str, dict] = {
196
+ "sft": {
197
+ "tol": {"loss": 1e-3, "grad_norm": 1e-1},
198
+ "residual_tol": {"loss": 1e-5, "grad_norm": 1e-3},
199
+ "members": [
200
+ _build("sft_default", "sft", SFT_DATASET),
201
+ _build("sft_pdb1_gas8", "sft", SFT_DATASET, per_device_train_batch_size=1, gradient_accumulation_steps=8),
202
+ _build("sft_no_grad_ckpt", "sft", SFT_DATASET, gradient_checkpointing=False),
203
+ _build("sft_ddp2", "sft", SFT_DATASET, per_device_train_batch_size=4, num_processes=2),
204
+ ],
205
+ },
206
+ "sft_fa2": {
207
+ # Loss is much tighter than grad_norm under FA2+bf16 (grad_norm absorbs bf16 + FA varlen kernel noise).
208
+ # See https://github.com/huggingface/trl/pull/5842#issuecomment-4539190615
209
+ "tol": {"loss": 1.5e-2, "grad_norm": 1.0},
210
+ "residual_tol": {"loss": 1e-4, "grad_norm": 5e-2},
211
+ "members": [
212
+ _build(
213
+ "sft_fa2",
214
+ "sft",
215
+ SFT_DATASET,
216
+ attn="kernels-community/flash-attn2", # to avoid cross-contamination between samples when padding_free=True
217
+ bf16=True, # required for FA2 kernels, which are bfloat16-only
218
+ max_length=None, # Required when padding_free=True
219
+ per_device_train_batch_size=2,
220
+ ),
221
+ _build(
222
+ "sft_fa2_padfree",
223
+ "sft",
224
+ SFT_DATASET,
225
+ attn="kernels-community/flash-attn2", # to avoid cross-contamination between samples when padding_free=True
226
+ bf16=True, # required for FA2 kernels, which are bfloat16-only
227
+ max_length=None, # Required when padding_free=True
228
+ per_device_train_batch_size=2,
229
+ padding_free=True,
230
+ ),
231
+ ],
232
+ },
233
+ "dpo": {
234
+ "tol": {"loss": 1e-4, "grad_norm": 1e-2},
235
+ "residual_tol": {"loss": 1e-5, "grad_norm": 1e-3},
236
+ "members": [
237
+ _build("dpo_default", "dpo", DPO_DATASET),
238
+ _build("dpo_pdb1_gas8", "dpo", DPO_DATASET, per_device_train_batch_size=1, gradient_accumulation_steps=8),
239
+ _build("dpo_no_grad_ckpt", "dpo", DPO_DATASET, gradient_checkpointing=False),
240
+ _build("dpo_ddp2", "dpo", DPO_DATASET, per_device_train_batch_size=4, num_processes=2),
241
+ ],
242
+ },
243
+ }
244
+
245
+
246
+ _ALL = [(klass, c) for klass, ec in EQUIVALENCE_CLASSES.items() for c in ec["members"]]
247
+
248
+
249
+ @pytest.mark.invariant
250
+ @pytest.mark.parametrize("klass,config", _ALL, ids=[c.name for _, c in _ALL])
251
+ def test_invariant(klass, config):
252
+ ref_path = REFERENCES_DIR / f"{klass}.json"
253
+ if not ref_path.exists():
254
+ pytest.fail(f"no reference at {ref_path}; record it with `python {Path(__file__).name}`")
255
+
256
+ if config.num_processes > 1 and torch.cuda.device_count() < config.num_processes:
257
+ pytest.skip(f"requires {config.num_processes} GPUs, got {torch.cuda.device_count()}")
258
+
259
+ trajectory = run(config)
260
+ reference = load(ref_path)
261
+ ec = EQUIVALENCE_CLASSES[klass]
262
+ errors = compare_scalars(trajectory, reference, tol=ec["tol"], residual_tol=ec["residual_tol"])
263
+ assert not errors, f"'{config.name}' diverges from class '{klass}' reference:\n " + "\n ".join(errors)
264
+
265
+
266
+ if __name__ == "__main__":
267
+ import argparse
268
+
269
+ parser = argparse.ArgumentParser(description="Record canonical reference trajectories for the invariant tests.")
270
+ parser.add_argument(
271
+ "klass",
272
+ nargs="*",
273
+ choices=list(EQUIVALENCE_CLASSES),
274
+ help="Equivalence class(es) to record. Default: all.",
275
+ )
276
+ parser.add_argument(
277
+ "--allow-dirty",
278
+ action="store_true",
279
+ help="Allow recording from a dirty working tree (snapshot will pin an irreproducible state).",
280
+ )
281
+ cli_args = parser.parse_args()
282
+
283
+ if _trl_commit().endswith("-dirty") and not cli_args.allow_dirty:
284
+ sys.exit(
285
+ "Refusing to record from a dirty working tree: the snapshot would pin a state that can't be "
286
+ "reproduced from a commit SHA. Commit your changes first, or pass --allow-dirty to override."
287
+ )
288
+
289
+ classes = cli_args.klass or list(EQUIVALENCE_CLASSES)
290
+ for klass in classes:
291
+ canonical = EQUIVALENCE_CLASSES[klass]["members"][0]
292
+ print(f"recording '{klass}' from canonical config '{canonical.name}'") # noqa: T201
293
+ trajectory = run(canonical)
294
+ ref_path = REFERENCES_DIR / f"{klass}.json"
295
+ save(trajectory, ref_path)
296
+ print(f" → {ref_path}") # noqa: T201
tasks/tasksmith-5b4f21a2a450/tests/source/tests/tasksmith_behavior.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline numerical contracts and real tiny-trainer integration for GMPO."""
2
+ from collections import defaultdict
3
+ from types import SimpleNamespace
4
+
5
+ import pytest
6
+ import torch
7
+
8
+
9
+ class LogitTable(torch.nn.Module):
10
+ def __init__(self):
11
+ super().__init__()
12
+ values = torch.tensor([
13
+ [[0.0, 0.3, -0.1, 0.4, 0.2, -0.4, 0.1], [0.0, 0.2, 0.7, -0.2, 0.5, 0.1, -0.1],
14
+ [0.4, -0.5, 0.1, 0.6, 0.9, 0.2, -0.1], [0.3, 0.2, 0.1, 0.4, 0.5, -0.2, 0.0],
15
+ [0.1, 0.3, -0.2, 0.8, 0.0, 0.1, -0.3]],
16
+ [[0.5, 0.2, -0.5, 0.4, 0.1, -0.3, 0.7], [1.3, -0.3, 0.7, -0.2, 0.4, 0.2, 0.0],
17
+ [2.1, -0.3, 0.0, 0.2, -0.5, 0.1, -0.1], [0.0, 0.1, 0.2, 0.4, 0.3, 0.5, -0.2],
18
+ [0.4, 0.2, 0.1, 0.3, -0.4, 0.0, -0.2]],
19
+ ], dtype=torch.float64)
20
+ self.logits = torch.nn.Parameter(values)
21
+
22
+ def forward(self, input_ids, attention_mask, use_cache=False):
23
+ assert input_ids.shape == attention_mask.shape == (2, 5)
24
+ return SimpleNamespace(logits=self.logits + 0.0)
25
+
26
+
27
+ def _logps(logits, completion_ids):
28
+ log_probs = logits[:, -4:-1].log_softmax(-1)
29
+ return log_probs.gather(-1, completion_ids.unsqueeze(-1)).squeeze(-1)
30
+
31
+
32
+ def _fixture(beta=0.0, entropy_quantile=1.0, train=True, accumulation=1):
33
+ from trl.experimental.gmpo import GMPOTrainer
34
+ model = LogitTable()
35
+ model.train(train)
36
+ trainer = object.__new__(GMPOTrainer)
37
+ trainer.model = model
38
+ trainer.temperature = 1.0
39
+ trainer.model_kwarg_keys = {"input_ids", "attention_mask", "use_cache"}
40
+ trainer.epsilon_low, trainer.epsilon_high = 0.4, 0.25
41
+ trainer.beta, trainer.top_entropy_quantile = beta, entropy_quantile
42
+ trainer.current_gradient_accumulation_steps = accumulation
43
+ trainer.accelerator = SimpleNamespace(gather=lambda value: value, pad_across_processes=lambda value, **kwargs: value,
44
+ num_processes=1, is_main_process=True)
45
+ trainer._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
46
+ inputs = {
47
+ "prompt_ids": torch.tensor([[1, 2], [2, 1]]), "prompt_mask": torch.ones(2, 2, dtype=torch.long),
48
+ "completion_ids": torch.tensor([[3, 4, 5], [4, 3, 2]]),
49
+ "completion_mask": torch.tensor([[1, 1, 0], [1, 1, 1]]),
50
+ "advantages": torch.tensor([1.5, -0.8], dtype=torch.float64),
51
+ }
52
+ current = _logps(model.logits.detach(), inputs["completion_ids"])
53
+ # Positive/negative advantages encounter both clipped and unclipped directions.
54
+ inputs["old_per_token_logps"] = current - torch.tensor([[0.8, -0.7, 5.0], [-0.8, 0.7, 0.1]])
55
+ inputs["ref_per_token_logps"] = current + torch.tensor([[0.2, -0.3, 2.0], [0.4, -0.2, 0.15]])
56
+ return trainer, model, inputs
57
+
58
+
59
+ def _expected(logits, inputs, *, beta=0.0, keep=None, accumulation=1):
60
+ """Sequence-wise ratio-space calculation independent of the vectorized implementation."""
61
+ current = _logps(logits, inputs["completion_ids"])
62
+ previous = inputs.get("old_per_token_logps", current.detach())
63
+ full_mask = inputs["completion_mask"].bool()
64
+ if "tool_mask" in inputs:
65
+ full_mask &= inputs["tool_mask"].bool()
66
+ selected = full_mask if keep is None else full_mask & keep
67
+ losses = []
68
+ for row in range(2):
69
+ advantage = inputs["advantages"][row]
70
+ ratios = []
71
+ for col in range(3):
72
+ if selected[row, col]:
73
+ ratio = (current[row, col] - previous[row, col]).exp()
74
+ limit = torch.exp(current.new_tensor(0.25 if advantage > 0 else -0.4))
75
+ ratios.append(torch.minimum(ratio, limit) if advantage > 0 else torch.maximum(ratio, limit))
76
+ weight = torch.stack(ratios).prod().pow(1.0 / len(ratios)) if ratios else current.new_tensor(1.0)
77
+ loss = -advantage * weight
78
+ if beta:
79
+ terms = [torch.exp(inputs["ref_per_token_logps"][row, col] - current[row, col])
80
+ - (inputs["ref_per_token_logps"][row, col] - current[row, col]) - 1
81
+ for col in range(3) if full_mask[row, col]]
82
+ loss = loss + beta * (torch.stack(terms).mean() if terms else current.new_tensor(0.0))
83
+ losses.append(loss)
84
+ return torch.stack(losses).mean() / accumulation
85
+
86
+
87
+ def _compare(trainer, model, inputs, *, beta=0.0, keep=None, accumulation=1):
88
+ expected_logits = model.logits.detach().clone().requires_grad_()
89
+ expected = _expected(expected_logits, inputs, beta=beta, keep=keep, accumulation=accumulation)
90
+ actual = trainer._compute_loss(model, inputs)
91
+ torch.testing.assert_close(actual, expected, rtol=1e-8, atol=1e-8)
92
+ actual.backward()
93
+ expected.backward()
94
+ assert model.logits.grad is not None and model.logits.grad.abs().sum() > 0
95
+ torch.testing.assert_close(model.logits.grad, expected_logits.grad, rtol=1e-7, atol=1e-8)
96
+
97
+
98
+ def test_log_space_defaults_on_cpu(tmp_path):
99
+ from trl.experimental.gmpo import GMPOConfig
100
+ args = GMPOConfig(str(tmp_path), use_cpu=True, bf16=False, fp16=False, report_to="none")
101
+ assert args.epsilon == 0.4 and args.epsilon_high is None
102
+
103
+
104
+ def test_geometric_mean_sign_aware_clipping_values_and_gradients():
105
+ trainer, model, inputs = _fixture()
106
+ _compare(trainer, model, inputs)
107
+
108
+
109
+ def test_tool_and_completion_masks_exclude_tokens_from_values_and_gradients():
110
+ trainer, model, inputs = _fixture()
111
+ inputs["tool_mask"] = torch.tensor([[1, 0, 1], [1, 1, 0]])
112
+ _compare(trainer, model, inputs)
113
+ assert model.logits.grad[0, 2:4].count_nonzero() == 0
114
+ assert model.logits.grad[1, 3].count_nonzero() == 0
115
+
116
+
117
+ def test_sequence_averaged_kl_and_train_accumulation():
118
+ trainer, model, inputs = _fixture(beta=0.3, accumulation=3)
119
+ _compare(trainer, model, inputs, beta=0.3, accumulation=3)
120
+ assert trainer._metrics["train"]["kl"]
121
+
122
+
123
+ def test_eval_does_not_divide_by_training_accumulation():
124
+ trainer, model, inputs = _fixture(train=False, accumulation=3)
125
+ _compare(trainer, model, inputs)
126
+
127
+
128
+ def test_old_logps_default_detaches_without_losing_policy_gradient():
129
+ trainer, model, inputs = _fixture()
130
+ del inputs["old_per_token_logps"]
131
+ _compare(trainer, model, inputs)
132
+
133
+
134
+ def test_high_entropy_selection_changes_geometric_mean_not_kl_mask():
135
+ trainer, model, inputs = _fixture(beta=0.2, entropy_quantile=0.4)
136
+ probabilities = model.logits.detach()[:, -4:-1].softmax(-1)
137
+ entropy = -(probabilities * probabilities.log()).sum(-1)
138
+ active = inputs["completion_mask"].bool()
139
+ threshold = entropy[active].quantile(0.6)
140
+ keep = entropy >= threshold
141
+ assert 0 < (active & keep).sum() < active.sum()
142
+ _compare(trainer, model, inputs, beta=0.2, keep=keep)
143
+
144
+
145
+ def test_empty_completion_masks_are_finite_with_zero_policy_gradient():
146
+ trainer, model, inputs = _fixture(beta=0.3)
147
+ inputs["completion_mask"].zero_()
148
+ actual = trainer._compute_loss(model, inputs)
149
+ torch.testing.assert_close(actual, -inputs["advantages"].mean())
150
+ actual.backward()
151
+ assert torch.isfinite(actual) and model.logits.grad.count_nonzero() == 0
152
+
153
+
154
+ @pytest.mark.parametrize("conversational", [False, True])
155
+ def test_local_tiny_trainer_updates_policy(conversational, tmp_path):
156
+ from datasets import Dataset
157
+ from tokenizers import Tokenizer
158
+ from tokenizers.models import WordLevel
159
+ from tokenizers.pre_tokenizers import Whitespace
160
+ from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
161
+ from trl.experimental.gmpo import GMPOConfig, GMPOTrainer
162
+
163
+ torch.manual_seed(31)
164
+ torch.set_num_threads(1)
165
+ vocab = {"[PAD]": 0, "[UNK]": 1, "[EOS]": 2, "hello": 3, "red": 4, "blue": 5, "green": 6, "answer": 7}
166
+ backend = Tokenizer(WordLevel(vocab, unk_token="[UNK]"))
167
+ backend.pre_tokenizer = Whitespace()
168
+ tokenizer = PreTrainedTokenizerFast(tokenizer_object=backend, pad_token="[PAD]", unk_token="[UNK]", eos_token="[EOS]")
169
+ tokenizer.chat_template = "{% for message in messages %}{{ message['content'] }} {% endfor %}"
170
+ model = LlamaForCausalLM(LlamaConfig(vocab_size=8, hidden_size=16, intermediate_size=32,
171
+ num_hidden_layers=1, num_attention_heads=2, num_key_value_heads=2, max_position_embeddings=32,
172
+ bos_token_id=1, eos_token_id=2, pad_token_id=0, attention_dropout=0.0))
173
+ # The inherited beta>0 path reloads its reference from the policy's model ID.
174
+ # Give it a local checkpoint instead of an empty or remote model identifier.
175
+ checkpoint = tmp_path / "initial-model"
176
+ model.save_pretrained(checkpoint)
177
+ model = LlamaForCausalLM.from_pretrained(checkpoint)
178
+ prompt = [{"role": "user", "content": "hello"}] if conversational else "hello"
179
+ dataset = Dataset.from_list([{"prompt": prompt} for _ in range(4)])
180
+
181
+ def rewards(completions, **kwargs):
182
+ return [float(index % 2) for index in range(len(completions))]
183
+
184
+ def rollout(prompts, trainer):
185
+ # Deterministic rollout input; the real trainer still computes loss/backprop/optimizer updates.
186
+ count = len(prompts)
187
+ return {"prompt_ids": [[3] for _ in range(count)],
188
+ "completion_ids": [[4, 5, 2] if i % 2 == 0 else [6, 7, 2] for i in range(count)],
189
+ "logprobs": [[-2.0] * 3 for _ in range(count)]}
190
+
191
+ args = GMPOConfig(str(tmp_path), use_cpu=True, bf16=False, fp16=False,
192
+ gradient_checkpointing=False, per_device_train_batch_size=2, num_generations=2,
193
+ max_steps=2, max_completion_length=3, num_iterations=2, learning_rate=0.01,
194
+ report_to="none", save_strategy="no", logging_steps=1, disable_tqdm=True,
195
+ beta=0.1 if conversational else 0.0)
196
+ trainer = GMPOTrainer(model, rewards, args=args, train_dataset=dataset,
197
+ processing_class=tokenizer, rollout_func=rollout)
198
+ before = {name: value.detach().clone() for name, value in model.named_parameters()}
199
+ outcome = trainer.train()
200
+ assert trainer.state.global_step == 2 and torch.isfinite(torch.tensor(outcome.training_loss))
201
+ assert any(not torch.equal(before[name], value.detach()) for name, value in model.named_parameters())
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_activation_offloading.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from torch import nn
17
+ from transformers import AutoModelForCausalLM
18
+ from transformers.testing_utils import torch_device
19
+ from transformers.utils import is_peft_available
20
+
21
+ from trl.models.activation_offloading import NoOpManager, OffloadActivations
22
+
23
+ from .testing_utils import TrlTestCase, require_peft, require_torch_accelerator
24
+
25
+
26
+ if is_peft_available():
27
+ from peft import LoraConfig, get_peft_model
28
+
29
+
30
+ class TestActivationOffloading(TrlTestCase):
31
+ @require_torch_accelerator
32
+ @require_peft
33
+ def test_offloading_with_peft_models(self) -> None:
34
+ """Test that activation offloading works with PEFT models."""
35
+ model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
36
+ model = AutoModelForCausalLM.from_pretrained(model_id).to(torch_device)
37
+ peft_config = LoraConfig(
38
+ lora_alpha=16,
39
+ lora_dropout=0.1,
40
+ r=8,
41
+ bias="none",
42
+ task_type="CAUSAL_LM",
43
+ )
44
+
45
+ model = get_peft_model(model, peft_config)
46
+ inp = torch.randint(0, 100, (2, 10), device=torch_device)
47
+
48
+ # First forward-backward pass without offloading
49
+ torch.manual_seed(42)
50
+ loss = model(inp, labels=inp).loss
51
+ loss.backward()
52
+
53
+ # Store gradients - only from trainable parameters
54
+ grads_original = []
55
+ for name, param in model.named_parameters():
56
+ if param.requires_grad and param.grad is not None:
57
+ grads_original.append((name, param.grad.clone()))
58
+
59
+ # Reset gradients
60
+ for p in model.parameters():
61
+ if p.grad is not None:
62
+ p.grad = None
63
+
64
+ # Second forward-backward pass with offloading
65
+ torch.manual_seed(42)
66
+ with OffloadActivations():
67
+ loss_c = model(inp, labels=inp).loss
68
+ loss_c.backward()
69
+
70
+ # Compare gradients - only trainable parameters
71
+ for name_orig, grad_orig in grads_original:
72
+ for name_param, param in model.named_parameters():
73
+ if name_param == name_orig and param.requires_grad and param.grad is not None:
74
+ (
75
+ torch.testing.assert_close(grad_orig, param.grad, rtol=1e-4, atol=1e-5),
76
+ (f"Gradient mismatch for {name_orig}"),
77
+ )
78
+
79
+ @require_torch_accelerator
80
+ def test_noop_manager_with_offloading(self):
81
+ model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
82
+ model = AutoModelForCausalLM.from_pretrained(model_id).to(torch_device)
83
+ inp = torch.randint(0, 100, (2, 10), device=torch_device)
84
+
85
+ # Run with offloading but disable for specific section
86
+ with OffloadActivations():
87
+ # First forward-backward with normal offloading
88
+ torch.manual_seed(42)
89
+ out1 = model(inp, labels=inp)
90
+ out1.loss.backward()
91
+ grads1 = [p.grad.clone() for p in model.parameters()]
92
+
93
+ # Reset grads
94
+ for p in model.parameters():
95
+ p.grad = None
96
+
97
+ # Second forward-backward with NoOpManager
98
+ with NoOpManager():
99
+ torch.manual_seed(42)
100
+ out2 = model(inp, labels=inp)
101
+ out2.loss.backward()
102
+
103
+ grads2 = [p.grad.clone() for p in model.parameters()]
104
+
105
+ # Gradients should match as NoOpManager should have prevented offloading
106
+ for g1, g2 in zip(grads1, grads2, strict=True):
107
+ torch.testing.assert_close(g1, g2, rtol=1e-4, atol=1e-5)
108
+
109
+ @require_torch_accelerator
110
+ def test_min_offload_size(self):
111
+ """Test that tensors smaller than min_offload_size aren't offloaded"""
112
+ model = nn.Sequential(
113
+ nn.Linear(5, 5), # Small layer that shouldn't be offloaded
114
+ nn.Linear(5, 1000), # Large layer that should be offloaded
115
+ ).to(torch_device)
116
+
117
+ inp = torch.randn(2, 5, device=torch_device)
118
+
119
+ with OffloadActivations(min_offload_size=1000):
120
+ out = model(inp)
121
+ out.sum().backward()
122
+
123
+ # The test passes if no errors occur, as we're mainly testing
124
+ # that the logic handles both offloaded and non-offloaded tensors
125
+
126
+ @require_torch_accelerator
127
+ def test_real_hf_model(self):
128
+ """Test with an actual HuggingFace model"""
129
+ model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
130
+ model = AutoModelForCausalLM.from_pretrained(model_id).to(torch_device)
131
+
132
+ # Create small input
133
+ inp = torch.randint(0, 100, (2, 10), device=torch_device)
134
+
135
+ # Baseline without offloading
136
+ torch.manual_seed(42)
137
+ out1 = model(inp, labels=inp).loss
138
+ out1.backward()
139
+ grads1 = [p.grad.clone() for p in model.parameters()]
140
+
141
+ # Reset grads
142
+ for p in model.parameters():
143
+ p.grad = None
144
+
145
+ # With offloading
146
+ with OffloadActivations():
147
+ torch.manual_seed(42)
148
+ out2 = model(inp, labels=inp).loss
149
+ out2.backward()
150
+
151
+ grads2 = [p.grad.clone() for p in model.parameters()]
152
+
153
+ # Check outputs and gradients match
154
+ torch.testing.assert_close(out1, out2)
155
+ for g1, g2 in zip(grads1, grads2, strict=True):
156
+ torch.testing.assert_close(g1, g2)
157
+
158
+ @require_torch_accelerator
159
+ def test_tensor_deduplication(self):
160
+ """Test that deduplication works correctly for tensors sharing storage"""
161
+
162
+ class ModelWithViews(nn.Module):
163
+ def __init__(self):
164
+ super().__init__()
165
+ self.linear = nn.Linear(100, 100)
166
+
167
+ def forward(self, x):
168
+ out = self.linear(x)
169
+ view1 = out.view(-1)
170
+ view2 = out.transpose(0, 1)
171
+ return view1.sum() + view2.sum()
172
+
173
+ model = ModelWithViews().to(torch_device)
174
+ offload_ctx = OffloadActivations(min_offload_size=1)
175
+ offload_ctx.update_model_params(model)
176
+
177
+ x = torch.randn(10, 100, device=torch_device, requires_grad=True)
178
+ with offload_ctx:
179
+ loss = model(x)
180
+
181
+ total_tensor_ids = offload_ctx.tensor_id
182
+ assert total_tensor_ids > 0, "Should have created tensor IDs"
183
+
184
+ # modified=True means offloaded to CPU, modified=False means kept on GPU (deduplicated)
185
+ deduplicated_count = sum(1 for _, modified, _, _, _ in offload_ctx.tracker.values() if not modified)
186
+ offloaded_count = sum(1 for _, modified, _, _, _ in offload_ctx.tracker.values() if modified)
187
+
188
+ assert offloaded_count > 0, "Should have offloaded at least one tensor"
189
+ assert deduplicated_count > 0, "Should have deduplicated at least one tensor (view)"
190
+
191
+ unique_storages_offloaded = len(offload_ctx.storage_to_tensor_id)
192
+ assert unique_storages_offloaded < total_tensor_ids, (
193
+ f"Deduplication should result in fewer storages ({unique_storages_offloaded}) "
194
+ f"than total tensors ({total_tensor_ids})"
195
+ )
196
+
197
+ loss.backward()
198
+
199
+ @require_torch_accelerator
200
+ def test_stale_tracker_state_is_cleared_between_forwards(self):
201
+ """Test that tensors from unused graph branches don't accumulate across steps."""
202
+
203
+ class ModelWithUnusedBranch(nn.Module):
204
+ def __init__(self):
205
+ super().__init__()
206
+ self.used = nn.Linear(8, 8)
207
+ self.unused = nn.Linear(8, 8)
208
+
209
+ def forward(self, x):
210
+ return self.used(x).sum(), self.unused(x).sum()
211
+
212
+ model = ModelWithUnusedBranch().to(torch_device)
213
+ offload_ctx = OffloadActivations(use_pin_memory=False, use_streams=False, min_offload_size=1)
214
+ offload_ctx.update_model_params(model)
215
+ inp = torch.randn(4, 8, device=torch_device)
216
+
217
+ tracker_counts = []
218
+ for _ in range(3):
219
+ model.zero_grad(set_to_none=True)
220
+ with offload_ctx:
221
+ loss, _ = model(inp)
222
+ loss.backward()
223
+ tracker_counts.append(len(offload_ctx.tracker))
224
+
225
+ assert tracker_counts == [tracker_counts[0]] * len(tracker_counts)
226
+
227
+ @require_torch_accelerator
228
+ def test_parameter_filtering(self):
229
+ """Test that model parameters are filtered during offloading"""
230
+ model = nn.Sequential(nn.Linear(10, 20), nn.Linear(20, 10)).to(torch_device)
231
+ offload_ctx = OffloadActivations()
232
+ offload_ctx.update_model_params(model)
233
+
234
+ assert len(offload_ctx.param_storages) > 0, "Should have tracked parameter storages"
235
+
236
+ param_ptrs = {p.data.untyped_storage().data_ptr() for p in model.parameters()}
237
+ assert offload_ctx.param_storages == param_ptrs, "Tracked storages should match parameter storages"
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_callbacks.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os
17
+ from unittest.mock import call, patch
18
+
19
+ from datasets import load_dataset
20
+ from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, Trainer, TrainingArguments
21
+
22
+ from trl import BEMACallback, LogCompletionsCallback
23
+
24
+ from .testing_utils import TrlTestCase, require_comet, require_wandb
25
+
26
+
27
+ class TestLogCompletionsCallback(TrlTestCase):
28
+ def setup_method(self):
29
+ self.model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
30
+ self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
31
+ self.tokenizer.pad_token = self.tokenizer.eos_token
32
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only")
33
+ dataset["train"] = dataset["train"].select(range(8))
34
+
35
+ def tokenize_function(examples):
36
+ out = self.tokenizer(examples["prompt"], padding="max_length", max_length=16, truncation=True)
37
+ out["labels"] = out["input_ids"].copy()
38
+ return out
39
+
40
+ self.dataset = dataset.map(tokenize_function, batched=True)
41
+
42
+ self.generation_config = GenerationConfig(max_length=32)
43
+
44
+ @require_wandb
45
+ def test_basic_wandb(self):
46
+ import wandb
47
+
48
+ training_args = TrainingArguments(
49
+ output_dir=self.tmp_dir,
50
+ eval_strategy="steps",
51
+ eval_steps=2, # evaluate every 2 steps
52
+ per_device_train_batch_size=2, # 8 samples in total so 4 batches of 2 per epoch
53
+ per_device_eval_batch_size=2,
54
+ report_to="wandb",
55
+ )
56
+ trainer = Trainer(
57
+ model=self.model,
58
+ args=training_args,
59
+ train_dataset=self.dataset["train"],
60
+ eval_dataset=self.dataset["test"],
61
+ processing_class=self.tokenizer,
62
+ )
63
+ completions_callback = LogCompletionsCallback(trainer, self.generation_config, num_prompts=2)
64
+ trainer.add_callback(completions_callback)
65
+ trainer.train()
66
+
67
+ # Get the current run
68
+ completions_path = wandb.run.summary.completions["path"]
69
+ json_path = os.path.join(wandb.run.dir, completions_path)
70
+ with open(json_path) as f:
71
+ completions = json.load(f)
72
+
73
+ # Check that the columns are correct
74
+ assert "step" in completions["columns"]
75
+ assert "prompt" in completions["columns"]
76
+ assert "completion" in completions["columns"]
77
+
78
+ # Check that the prompt is in the log
79
+ assert self.dataset["test"][0]["prompt"] in completions["data"][0]
80
+
81
+ @require_comet
82
+ def test_basic_comet(self):
83
+ import comet_ml
84
+
85
+ training_args = TrainingArguments(
86
+ output_dir=self.tmp_dir,
87
+ eval_strategy="steps",
88
+ eval_steps=2, # evaluate every 2 steps
89
+ per_device_train_batch_size=2, # 8 samples in total so 4 batches of 2 per epoch
90
+ per_device_eval_batch_size=2,
91
+ report_to="comet_ml",
92
+ )
93
+ trainer = Trainer(
94
+ model=self.model,
95
+ args=training_args,
96
+ train_dataset=self.dataset["train"],
97
+ eval_dataset=self.dataset["test"],
98
+ processing_class=self.tokenizer,
99
+ )
100
+ completions_callback = LogCompletionsCallback(trainer, self.generation_config, num_prompts=2)
101
+ trainer.add_callback(completions_callback)
102
+ trainer.train()
103
+
104
+ # close experiment to make sure all pending data are flushed
105
+ experiment = comet_ml.get_running_experiment()
106
+ assert experiment is not None
107
+ experiment.end()
108
+
109
+ # get experiment assets and check that all required tables was logged
110
+ steps = len(self.dataset["train"]) + len(self.dataset["test"])
111
+ tables_logged = int(steps / 2) + 1 # +1 to include zero step
112
+
113
+ api_experiment = comet_ml.APIExperiment(previous_experiment=experiment.id)
114
+ tables = api_experiment.get_asset_list("dataframe")
115
+ assert tables is not None
116
+ assert len(tables) == tables_logged
117
+ assert all(table["fileName"] == "completions.csv" for table in tables)
118
+
119
+
120
+ class TestBEMACallback(TrlTestCase):
121
+ def setup_method(self):
122
+ self.model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
123
+ self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
124
+ self.tokenizer.pad_token = self.tokenizer.eos_token
125
+ dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling")
126
+
127
+ def tokenize_function(examples, tokenizer):
128
+ out = tokenizer(examples["text"], padding="max_length", max_length=17)
129
+ out["labels"] = out["input_ids"].copy()
130
+ return out
131
+
132
+ self.dataset = dataset.map(
133
+ tokenize_function, fn_kwargs={"tokenizer": self.tokenizer}, remove_columns=["text"], batched=True
134
+ )
135
+
136
+ def test_model_saved(self):
137
+ """Test that BEMACallback saves the BEMA model."""
138
+ training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none")
139
+ bema_callback = BEMACallback(update_freq=2)
140
+ trainer = Trainer(
141
+ model=self.model,
142
+ args=training_args,
143
+ train_dataset=self.dataset["train"],
144
+ processing_class=self.tokenizer,
145
+ callbacks=[bema_callback],
146
+ )
147
+ trainer.train()
148
+
149
+ # Check that the BEMA model was saved and can be loaded
150
+ bema_path = os.path.join(self.tmp_dir, "bema")
151
+ assert os.path.isdir(bema_path), "BEMA directory was not created"
152
+ AutoModelForCausalLM.from_pretrained(bema_path)
153
+
154
+ def test_update_frequency_0(self):
155
+ """Test that BEMA callback respects the update frequency."""
156
+ training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none")
157
+ bema_callback = BEMACallback(update_freq=2)
158
+
159
+ with patch.object(bema_callback, "_update_bema_weights") as mock_update:
160
+ trainer = Trainer(
161
+ model=self.model,
162
+ args=training_args,
163
+ train_dataset=self.dataset["train"],
164
+ processing_class=self.tokenizer,
165
+ callbacks=[bema_callback],
166
+ )
167
+
168
+ trainer.train()
169
+
170
+ # Total 9 steps (17 samples, batch size 8, 3 epochs).
171
+ # BEMA starts after step 0 and updates every 2 steps → updates at 2, 4, 5, 8
172
+ assert mock_update.call_args_list == [call(2), call(4), call(6), call(8)]
173
+
174
+ def test_update_frequency_1(self):
175
+ """Test that BEMA callback respects the update frequency."""
176
+ training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none")
177
+ bema_callback = BEMACallback(update_freq=3)
178
+
179
+ with patch.object(bema_callback, "_update_bema_weights") as mock_update:
180
+ trainer = Trainer(
181
+ model=self.model,
182
+ args=training_args,
183
+ train_dataset=self.dataset["train"],
184
+ processing_class=self.tokenizer,
185
+ callbacks=[bema_callback],
186
+ )
187
+
188
+ trainer.train()
189
+
190
+ # Total 9 steps (17 samples, batch size 8, 3 epochs).
191
+ # BEMA starts after step 0 and updates every 3 steps → updates at 3, 6, 9
192
+ assert mock_update.call_args_list == [call(3), call(6), call(9)]
193
+
194
+ def test_update_frequency_2(self):
195
+ """Test that BEMA callback respects the update frequency."""
196
+ training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none")
197
+ bema_callback = BEMACallback(update_freq=2, update_after=3)
198
+
199
+ with patch.object(bema_callback, "_update_bema_weights") as mock_update:
200
+ trainer = Trainer(
201
+ model=self.model,
202
+ args=training_args,
203
+ train_dataset=self.dataset["train"],
204
+ processing_class=self.tokenizer,
205
+ callbacks=[bema_callback],
206
+ )
207
+
208
+ trainer.train()
209
+
210
+ # Total 9 steps (17 samples, batch size 8, 3 epochs).
211
+ # BEMA starts after step 3 and updates every 2 steps → updates at 5, 7, 9
212
+ assert mock_update.call_args_list == [call(5), call(7), call(9)]
213
+
214
+ def test_no_bema(self):
215
+ """Test that BEMACallback works without BEMA updates."""
216
+ training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none")
217
+ bema_callback = BEMACallback(update_freq=2, bias_power=0.0)
218
+ trainer = Trainer(
219
+ model=self.model,
220
+ args=training_args,
221
+ train_dataset=self.dataset["train"],
222
+ processing_class=self.tokenizer,
223
+ callbacks=[bema_callback],
224
+ )
225
+ trainer.train()
226
+
227
+ def test_no_ema(self):
228
+ """Test that BEMACallback works without EMA updates."""
229
+ training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none")
230
+ bema_callback = BEMACallback(update_freq=2, ema_power=0.0)
231
+ trainer = Trainer(
232
+ model=self.model,
233
+ args=training_args,
234
+ train_dataset=self.dataset["train"],
235
+ processing_class=self.tokenizer,
236
+ callbacks=[bema_callback],
237
+ )
238
+ trainer.train()
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_chat_template_utils.py ADDED
@@ -0,0 +1,1255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 copy
16
+ import textwrap
17
+
18
+ import pytest
19
+ import transformers
20
+ from packaging.version import Version
21
+ from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoProcessor, AutoTokenizer
22
+
23
+ from trl import clone_chat_template
24
+ from trl.chat_template_utils import (
25
+ add_response_schema,
26
+ get_training_chat_template,
27
+ is_chat_template_prefix_preserving,
28
+ is_chat_template_stop_token_trained,
29
+ parse_response,
30
+ supports_tool_calling,
31
+ )
32
+ from trl.data_utils import prepare_multimodal_messages
33
+
34
+ from .testing_utils import TrlTestCase, require_jmespath, require_vision
35
+
36
+
37
+ class TestCloneChatTemplate(TrlTestCase):
38
+ def test_clone(self):
39
+ # This tokenizer doesn't have a chat_template by default
40
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM")
41
+ model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM")
42
+ # This one has a chat_template by default
43
+ source = "trl-internal-testing/tiny-Qwen3ForCausalLM"
44
+ _, modified_tokenizer, _ = clone_chat_template(model, tokenizer, source)
45
+
46
+ # Check if special tokens are correctly set
47
+ assert modified_tokenizer.eos_token == "<|im_end|>"
48
+
49
+ def test_clone_with_resize(self):
50
+ # This tokenizer doesn't have a chat_template by default
51
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM")
52
+ model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM")
53
+ # This one has a chat_template by default
54
+ source = "trl-internal-testing/tiny-Qwen3ForCausalLM"
55
+ modified_model, modified_tokenizer, _ = clone_chat_template(
56
+ model, tokenizer, source, resize_to_multiple_of=123
57
+ )
58
+
59
+ # Check that the input embeddings have been resized to a multiple of 123
60
+ assert (modified_model.vocab_size % 123) == 0
61
+ # Check that the input embeddings size matches the tokenizer vocabulary size
62
+ assert model.vocab_size == len(modified_tokenizer.vocab)
63
+
64
+ def test_clone_with_resize_and_extra_tokens_already_in_vocab(self):
65
+ # This tokenizer doesn't have a chat_template by default
66
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM")
67
+ model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM")
68
+ # This one has a chat_template by default
69
+ source = "trl-internal-testing/tiny-Qwen3ForCausalLM"
70
+ # This will add <extra_id_0>, <extra_id_1>, ... to the tokenizer
71
+ modified_model, modified_tokenizer, _ = clone_chat_template(
72
+ model, tokenizer, source, resize_to_multiple_of=123
73
+ )
74
+ # Try if we can resize a tokenizer that already has extra these extra tokens
75
+ modified_model, modified_tokenizer, _ = clone_chat_template(
76
+ modified_model, modified_tokenizer, source, resize_to_multiple_of=124
77
+ )
78
+
79
+ # Check that the input embeddings have been resized to a multiple of 123
80
+ assert (modified_model.vocab_size % 124) == 0
81
+ # Check that the input embeddings size matches the tokenizer vocabulary size
82
+ assert model.vocab_size == len(modified_tokenizer.vocab)
83
+
84
+ def test_apply_new_chat_template(self):
85
+ # This tokenizer doesn't have a chat_template by default
86
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM")
87
+ model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-BloomForCausalLM")
88
+ # This one has a chat_template by default
89
+ source = "trl-internal-testing/tiny-Qwen3ForCausalLM"
90
+ _, modified_tokenizer, _ = clone_chat_template(model, tokenizer, source)
91
+ messages = [
92
+ {"role": "system", "content": "You are helpful"},
93
+ {"role": "user", "content": "Hello"},
94
+ {"role": "assistant", "content": "Hi, how can I help you?"},
95
+ ]
96
+ prompt = modified_tokenizer.apply_chat_template(messages, tokenize=False)
97
+
98
+ assert (
99
+ prompt
100
+ == "<|im_start|>system\nYou are helpful<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\nHi, how can I help you?<|im_end|>\n"
101
+ )
102
+
103
+ def test_clone_with_sequence_classification_model(self):
104
+ # This tokenizer doesn't have a chat_template by default
105
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptNeoXForSequenceClassification")
106
+ model = AutoModelForSequenceClassification.from_pretrained(
107
+ "trl-internal-testing/tiny-GptNeoXForSequenceClassification"
108
+ )
109
+ # This one has a chat_template by default
110
+ source = "trl-internal-testing/tiny-Qwen3ForCausalLM"
111
+ _, modified_tokenizer, _ = clone_chat_template(model, tokenizer, source)
112
+
113
+ # Check if special tokens are correctly set
114
+ assert modified_tokenizer.eos_token == "<|im_end|>"
115
+
116
+
117
+ @pytest.mark.xfail(
118
+ condition=Version(transformers.__version__) < Version("5.0.0"),
119
+ reason="Response parsing is not supported in transformers versions below 5.0.0",
120
+ strict=True,
121
+ )
122
+ @require_jmespath
123
+ class TestAddResponseSchema:
124
+ @pytest.mark.parametrize(
125
+ "tokenizer_name",
126
+ [
127
+ pytest.param("trl-internal-testing/tiny-Glm4MoeForCausalLM", id="glm4moe"),
128
+ pytest.param(
129
+ "trl-internal-testing/tiny-GptOssForCausalLM",
130
+ id="gptoss",
131
+ marks=pytest.mark.xfail(
132
+ Version(transformers.__version__) < Version("5.5.0"),
133
+ reason="Upstream bug in response parsing (see #5753; fixed in transformers#45166)",
134
+ strict=True,
135
+ ),
136
+ ),
137
+ pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.1", id="llama3.1"),
138
+ pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.2", id="llama3.2"),
139
+ pytest.param(
140
+ "trl-internal-testing/tiny-NemotronHForCausalLM-nano",
141
+ id="nemotron_3_nano",
142
+ marks=pytest.mark.skipif(
143
+ Version(transformers.__version__) < Version("5.3.0"),
144
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
145
+ ),
146
+ ),
147
+ pytest.param(
148
+ "trl-internal-testing/tiny-NemotronHForCausalLM-super",
149
+ id="nemotron_3_super",
150
+ marks=pytest.mark.skipif(
151
+ Version(transformers.__version__) < Version("5.3.0"),
152
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
153
+ ),
154
+ ),
155
+ pytest.param(
156
+ "trl-internal-testing/tiny-NemotronHForCausalLM-ultra",
157
+ id="nemotron_3_ultra",
158
+ marks=pytest.mark.skipif(
159
+ Version(transformers.__version__) < Version("5.3.0"),
160
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
161
+ ),
162
+ ),
163
+ pytest.param("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", id="qwen2.5"),
164
+ pytest.param("trl-internal-testing/tiny-Qwen3MoeForCausalLM", id="qwen3"),
165
+ pytest.param("trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", id="qwen3_instruct_2507"),
166
+ ],
167
+ )
168
+ def test_add_response_schema(self, tokenizer_name):
169
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
170
+ tokenizer = add_response_schema(tokenizer)
171
+ messages = [
172
+ {"role": "user", "content": "What is 3*4?"},
173
+ {
174
+ "role": "assistant",
175
+ "tool_calls": [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}],
176
+ },
177
+ ]
178
+ prefix = tokenizer.apply_chat_template(messages[:1], tokenize=False, add_generation_prompt=True)
179
+ text = tokenizer.apply_chat_template(messages, tokenize=False)
180
+ response = text[len(prefix) :]
181
+ # Here, we just test that the parsing doesn't raise an error.
182
+ # The correctness of the parsing is tested in TestParseResponse
183
+ tokenizer.parse_response(response)
184
+
185
+ @pytest.mark.parametrize(
186
+ "processor_name",
187
+ [
188
+ pytest.param("trl-internal-testing/tiny-Qwen3VLForConditionalGeneration", id="qwen3_vl"),
189
+ pytest.param("trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", id="qwen35-nothink"),
190
+ pytest.param("trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-Think", id="qwen35-think"),
191
+ pytest.param("trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", id="qwen36"),
192
+ ],
193
+ )
194
+ def test_add_response_schema_vlm(self, processor_name):
195
+ # For VLM processors, `add_response_schema` must set the schema on the inner tokenizer, since
196
+ # `parse_response` is a tokenizer method that reads `self.response_schema` from the tokenizer instance.
197
+ processor = AutoProcessor.from_pretrained(processor_name)
198
+ processor = add_response_schema(processor)
199
+ assert processor.tokenizer.response_schema is not None
200
+ messages = [
201
+ {"role": "user", "content": [{"type": "text", "text": "What is 3*4?"}]},
202
+ {
203
+ "role": "assistant",
204
+ # "content" is required here because VLM processors crash on tokenize=True without it
205
+ # (KeyError in processing_utils.py). See huggingface/transformers#45290.
206
+ "content": [{"type": "text", "text": ""}],
207
+ "tool_calls": [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}],
208
+ },
209
+ ]
210
+ prefix = processor.apply_chat_template(messages[:1], tokenize=False, add_generation_prompt=True)
211
+ text = processor.apply_chat_template(messages, tokenize=False)
212
+ response = text[len(prefix) :]
213
+ # Here, we just test that the parsing doesn't raise an error.
214
+ # The correctness of the parsing is tested in TestParseResponse
215
+ processor.tokenizer.parse_response(response)
216
+
217
+
218
+ class TestSupportsToolCalling:
219
+ @pytest.mark.parametrize(
220
+ "model_id",
221
+ [
222
+ pytest.param("trl-internal-testing/tiny-DeepseekV3ForCausalLM", id="deepseekv3"),
223
+ pytest.param("trl-internal-testing/tiny-DeepseekV3ForCausalLM-0528", id="deepseekv3-0528"),
224
+ pytest.param(
225
+ "trl-internal-testing/tiny-Gemma4ForConditionalGeneration",
226
+ id="gemma4",
227
+ marks=pytest.mark.skipif(
228
+ Version(transformers.__version__) < Version("5.5.0"),
229
+ reason="Gemma4 models were introduced in transformers-5.5.0",
230
+ ),
231
+ ),
232
+ pytest.param(
233
+ "trl-internal-testing/tiny-Glm4MoeForCausalLM",
234
+ id="glm4moe",
235
+ marks=pytest.mark.skipif(
236
+ Version(transformers.__version__) < Version("5.0.0"),
237
+ reason="GLM4 tokenizer requires transformers>=5.0.0",
238
+ ),
239
+ ),
240
+ pytest.param("trl-internal-testing/tiny-GptOssForCausalLM", id="gptoss"),
241
+ pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.1", id="llama3.1"),
242
+ pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.2", id="llama3.2"),
243
+ pytest.param(
244
+ "trl-internal-testing/tiny-NemotronHForCausalLM-nano",
245
+ id="nemotron_3_nano",
246
+ marks=pytest.mark.skipif(
247
+ Version(transformers.__version__) < Version("5.3.0"),
248
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
249
+ ),
250
+ ),
251
+ pytest.param(
252
+ "trl-internal-testing/tiny-NemotronHForCausalLM-super",
253
+ id="nemotron_3_super",
254
+ marks=pytest.mark.skipif(
255
+ Version(transformers.__version__) < Version("5.3.0"),
256
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
257
+ ),
258
+ ),
259
+ pytest.param(
260
+ "trl-internal-testing/tiny-NemotronHForCausalLM-ultra",
261
+ id="nemotron_3_ultra",
262
+ marks=pytest.mark.skipif(
263
+ Version(transformers.__version__) < Version("5.3.0"),
264
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
265
+ ),
266
+ ),
267
+ pytest.param("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", id="qwen2.5"),
268
+ pytest.param("trl-internal-testing/tiny-Qwen3ForCausalLM", id="qwen3"),
269
+ pytest.param("trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", id="qwen3_instruct_2507"),
270
+ pytest.param("trl-internal-testing/tiny-Qwen3MoeForCausalLM", id="qwen3moe"),
271
+ pytest.param(
272
+ "trl-internal-testing/tiny-Qwen3VLForConditionalGeneration",
273
+ id="qwen3_vl",
274
+ marks=pytest.mark.skipif(
275
+ Version(transformers.__version__) < Version("4.57.0"),
276
+ reason="Qwen3-VL was introduced in transformers-4.57.0",
277
+ ),
278
+ ),
279
+ pytest.param(
280
+ "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink",
281
+ id="qwen35-nothink",
282
+ marks=pytest.mark.skipif(
283
+ Version(transformers.__version__) < Version("5.0.0"),
284
+ reason="Qwen3.5 tokenizer requires transformers>=5.0.0",
285
+ ),
286
+ ),
287
+ pytest.param(
288
+ "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-Think",
289
+ id="qwen35-think",
290
+ marks=pytest.mark.skipif(
291
+ Version(transformers.__version__) < Version("5.0.0"),
292
+ reason="Qwen3.5 tokenizer requires transformers>=5.0.0",
293
+ ),
294
+ ),
295
+ pytest.param(
296
+ "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6",
297
+ id="qwen36",
298
+ marks=pytest.mark.skipif(
299
+ Version(transformers.__version__) < Version("5.0.0"),
300
+ reason="Qwen3.5 tokenizer requires transformers>=5.0.0",
301
+ ),
302
+ ),
303
+ ],
304
+ )
305
+ def test_supports_tool_calling(self, model_id):
306
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
307
+ assert supports_tool_calling(tokenizer) is True
308
+
309
+ @pytest.mark.parametrize(
310
+ "model_id",
311
+ [
312
+ # No chat template
313
+ pytest.param("trl-internal-testing/tiny-BartModel", id="bart"),
314
+ pytest.param("trl-internal-testing/tiny-BloomForCausalLM", id="bloom"),
315
+ pytest.param("trl-internal-testing/tiny-GPT2LMHeadModel", id="gpt2"),
316
+ pytest.param("trl-internal-testing/tiny-GPTNeoXForCausalLM", id="gptneox"),
317
+ pytest.param("trl-internal-testing/tiny-GptNeoXForSequenceClassification", id="gptneox-seq"),
318
+ pytest.param("trl-internal-testing/tiny-OPTForCausalLM", id="opt"),
319
+ pytest.param("trl-internal-testing/tiny-T5ForConditionalGeneration", id="t5"),
320
+ # TemplateError: rejects tool role sequence
321
+ pytest.param("trl-internal-testing/tiny-CohereForCausalLM", id="cohere"),
322
+ pytest.param("trl-internal-testing/tiny-FalconMambaForCausalLM", id="falconmamba"),
323
+ pytest.param("trl-internal-testing/tiny-GemmaForCausalLM", id="gemma"),
324
+ pytest.param("trl-internal-testing/tiny-Gemma2ForCausalLM", id="gemma2"),
325
+ pytest.param("trl-internal-testing/tiny-Gemma3ForConditionalGeneration", id="gemma3"),
326
+ pytest.param("trl-internal-testing/tiny-Idefics2ForConditionalGeneration", id="idefics2"),
327
+ pytest.param("trl-internal-testing/tiny-Idefics3ForConditionalGeneration", id="idefics3"),
328
+ pytest.param("trl-internal-testing/tiny-LlavaNextForConditionalGeneration", id="llava_next"),
329
+ pytest.param("trl-internal-testing/tiny-MistralForCausalLM-0.1", id="mistral0.1"),
330
+ pytest.param("trl-internal-testing/tiny-MistralForCausalLM-0.2", id="mistral0.2"),
331
+ pytest.param("trl-internal-testing/tiny-SmolVLMForConditionalGeneration", id="smolvlm"),
332
+ # Silently drops both tool_calls and tool messages
333
+ pytest.param("trl-internal-testing/tiny-Cohere2ForCausalLM", id="cohere2"),
334
+ pytest.param("trl-internal-testing/tiny-LlavaForConditionalGeneration", id="llava"),
335
+ # Olmo3 uses a bespoke function-calling schema (a `functions`/`function_calls` string on the
336
+ # message plus an `environment` role) instead of the standard `tools`/`tool_calls`/`tool`
337
+ # interface, so a standard tool-calling conversation is silently dropped.
338
+ pytest.param(
339
+ "trl-internal-testing/tiny-Olmo3ForCausalLM",
340
+ id="olmo3",
341
+ marks=pytest.mark.skipif(
342
+ Version(transformers.__version__) < Version("4.57.0"),
343
+ reason="Olmo 3 was introduced in transformers>=4.57.0",
344
+ ),
345
+ ),
346
+ pytest.param("trl-internal-testing/tiny-Phi3ForCausalLM-3", id="phi3"),
347
+ pytest.param("trl-internal-testing/tiny-Phi3ForCausalLM-3.5", id="phi3.5"),
348
+ # Renders tool message content as plain text but drops assistant tool_calls
349
+ pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3", id="llama3"),
350
+ pytest.param("trl-internal-testing/tiny-Qwen2VLForConditionalGeneration", id="qwen2_vl"),
351
+ pytest.param("trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", id="qwen2.5_vl"),
352
+ ],
353
+ )
354
+ def test_does_not_support_tool_calling(self, model_id):
355
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
356
+ assert supports_tool_calling(tokenizer) is False
357
+
358
+
359
+ class TestIsChatTemplatePrefixPreserving:
360
+ def test_prefix_preserving_template(self):
361
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3MoeForCausalLM")
362
+ # docstyle-ignore
363
+ tokenizer.chat_template = textwrap.dedent(r"""
364
+ {%- for message in messages %}
365
+
366
+ {%- if message.role == 'user' %}
367
+ {{- '<|im_start|>user\n' + message.content + '<|im_end|>\n' }}
368
+ {%- elif message.role == 'assistant' %}
369
+ {{- '<|im_start|>assistant\n' + message.content }}
370
+ {%- if message.tool_calls %}
371
+ {%- for tool_call in message.tool_calls %}
372
+ {%- if tool_call.function %}
373
+ {%- set tool_call = tool_call.function %}
374
+ {%- endif %}
375
+ {{- '<tool_call>' + tool_call.name + '</tool_call>' }}
376
+ {%- endfor %}
377
+ {%- endif %}
378
+ {{- '<|im_end|>\n' }}
379
+ {%- elif message.role == 'tool' %}
380
+ {{- '<|im_start|>tool\n' + message.content + '<|im_end|>\n' }}
381
+ {%- endif %}
382
+
383
+ {%- endfor %}
384
+
385
+ {%- if add_generation_prompt %}
386
+ {{- '<|im_start|>assistant\n' }}
387
+ {%- endif %}""")
388
+ assert is_chat_template_prefix_preserving(tokenizer) is True
389
+
390
+ def test_non_prefix_preserving_template(self):
391
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3MoeForCausalLM")
392
+ # The following template is quite typical of models like Qwen3 and GPT-OSS, where the thinking part (even
393
+ # empty) is only present for last assistant message, which makes it non-prefix-preserving: appending a tool
394
+ # message changes the earlier output.
395
+ # docstyle-ignore
396
+ tokenizer.chat_template = textwrap.dedent(r"""
397
+ {%- if messages[0].role == 'system' %}
398
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
399
+ {%- endif %}
400
+ {%- set ns = namespace(last_query_index=messages|length - 1) %}
401
+ {%- for message in messages[::-1] %}
402
+ {%- set index = (messages|length - 1) - loop.index0 %}
403
+ {%- if message.role == "user" and message.content is string %}
404
+ {%- set ns.last_query_index = index %}
405
+ {%- break %}
406
+ {%- endif %}
407
+ {%- endfor %}
408
+ {%- for message in messages %}
409
+ {%- set content = message.content if message.content is string else '' %}
410
+ {%- if message.role == "user" or (message.role == "system" and not loop.first) %}
411
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>\n' }}
412
+ {%- elif message.role == "assistant" %}
413
+ {%- set reasoning_content = '' %}
414
+ {%- if message.reasoning_content is string %}
415
+ {%- set reasoning_content = message.reasoning_content %}
416
+ {%- else %}
417
+ {%- if '</think>' in content %}
418
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
419
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
420
+ {%- endif %}
421
+ {%- endif %}
422
+ {%- if loop.index0 > ns.last_query_index %}
423
+ {%- if loop.last or (not loop.last and reasoning_content) %}
424
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
425
+ {%- else %}
426
+ {{- '<|im_start|>' + message.role + '\n' + content }}
427
+ {%- endif %}
428
+ {%- else %}
429
+ {{- '<|im_start|>' + message.role + '\n' + content }}
430
+ {%- endif %}
431
+ {%- if message.tool_calls %}
432
+ {%- for tool_call in message.tool_calls %}
433
+ {%- if tool_call.function %}
434
+ {%- set tool_call = tool_call.function %}
435
+ {%- endif %}
436
+ {{- '<tool_call>' + tool_call.name + '</tool_call>' }}
437
+ {%- endfor %}
438
+ {%- endif %}
439
+ {{- '<|im_end|>\n' }}
440
+ {%- elif message.role == "tool" %}
441
+ {{- '<|im_start|>tool\n' + content + '<|im_end|>\n' }}
442
+ {%- endif %}
443
+ {%- endfor %}
444
+ {%- if add_generation_prompt %}
445
+ {{- '<|im_start|>assistant\n' }}
446
+ {%- if enable_thinking is defined and enable_thinking is false %}
447
+ {{- '<think>\n\n</think>\n\n' }}
448
+ {%- endif %}
449
+ {%- endif %}""")
450
+ assert is_chat_template_prefix_preserving(tokenizer) is False
451
+
452
+ @require_vision
453
+ def test_prefix_preserving_template_processor(self):
454
+ processor = AutoProcessor.from_pretrained("trl-internal-testing/tiny-Qwen3VLForConditionalGeneration")
455
+ # Simple prefix-preserving template that mirrors how Qwen-VL templates emit image tokens: a list-of-blocks
456
+ # content is iterated, and `{"type": "image"}` blocks are rendered as `<|vision_start|><|image_pad|><|vision_end|>`.
457
+ # docstyle-ignore
458
+ processor.chat_template = textwrap.dedent(r"""
459
+ {%- for message in messages %}
460
+
461
+ {%- if message.role == 'user' %}
462
+ {{- '<|im_start|>user\n' }}
463
+ {%- if message.content is string %}
464
+ {{- message.content }}
465
+ {%- else %}
466
+ {%- for content in message.content %}
467
+ {%- if content.type == 'image' or 'image' in content %}
468
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
469
+ {%- elif 'text' in content %}
470
+ {{- content.text }}
471
+ {%- endif %}
472
+ {%- endfor %}
473
+ {%- endif %}
474
+ {{- '<|im_end|>\n' }}
475
+ {%- elif message.role == 'assistant' %}
476
+ {{- '<|im_start|>assistant\n' }}
477
+ {%- if message.content is string %}
478
+ {{- message.content }}
479
+ {%- else %}
480
+ {%- for content in message.content %}
481
+ {%- if 'text' in content %}
482
+ {{- content.text }}
483
+ {%- endif %}
484
+ {%- endfor %}
485
+ {%- endif %}
486
+ {%- if message.tool_calls %}
487
+ {%- for tool_call in message.tool_calls %}
488
+ {%- if tool_call.function %}
489
+ {%- set tool_call = tool_call.function %}
490
+ {%- endif %}
491
+ {{- '<tool_call>' + tool_call.name + '</tool_call>' }}
492
+ {%- endfor %}
493
+ {%- endif %}
494
+ {{- '<|im_end|>\n' }}
495
+ {%- elif message.role == 'tool' %}
496
+ {{- '<|im_start|>tool\n' }}
497
+ {%- if message.content is string %}
498
+ {{- message.content }}
499
+ {%- else %}
500
+ {%- for content in message.content %}
501
+ {%- if 'text' in content %}
502
+ {{- content.text }}
503
+ {%- endif %}
504
+ {%- endfor %}
505
+ {%- endif %}
506
+ {{- '<|im_end|>\n' }}
507
+ {%- endif %}
508
+
509
+ {%- endfor %}
510
+
511
+ {%- if add_generation_prompt %}
512
+ {{- '<|im_start|>assistant\n' }}
513
+ {%- endif %}""")
514
+ assert is_chat_template_prefix_preserving(processor) is True
515
+
516
+
517
+ class TestIsChatTemplateStopTokenTrained:
518
+ def test_stop_token_trained(self):
519
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3MoeForCausalLM")
520
+ # The assistant turn is closed by <|im_end|> inside the generation span, so the end-of-turn token is masked
521
+ # in and the model is trained to stop.
522
+ # docstyle-ignore
523
+ tokenizer.chat_template = textwrap.dedent(r"""
524
+ {%- for message in messages %}
525
+ {%- if message.role == 'user' %}
526
+ {{- '<|im_start|>user\n' + message.content + '<|im_end|>\n' }}
527
+ {%- elif message.role == 'assistant' %}
528
+ {{- '<|im_start|>assistant\n' }}
529
+ {%- generation %}{{- message.content + '<|im_end|>' }}{%- endgeneration %}
530
+ {{- '\n' }}
531
+ {%- endif %}
532
+ {%- endfor %}
533
+ {%- if add_generation_prompt %}
534
+ {{- '<|im_start|>assistant\n' }}
535
+ {%- endif %}""")
536
+ assert is_chat_template_stop_token_trained(tokenizer) is True
537
+
538
+ def test_stop_token_not_trained(self):
539
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3MoeForCausalLM")
540
+ # GLM-style: the assistant's end-of-turn token is emitted as the prefix of the following message, so the
541
+ # generation span covers content only and the model is never trained to stop.
542
+ # docstyle-ignore
543
+ tokenizer.chat_template = textwrap.dedent(r"""
544
+ {%- for message in messages %}
545
+ {%- if message.role == 'user' %}
546
+ {{- '<|im_start|>user\n' + message.content + '<|im_end|>\n' }}
547
+ {%- elif message.role == 'assistant' %}
548
+ {{- '<|im_start|>assistant\n' }}
549
+ {%- generation %}{{- message.content }}{%- endgeneration %}
550
+ {{- '<|im_end|>\n' }}
551
+ {%- endif %}
552
+ {%- endfor %}
553
+ {%- if add_generation_prompt %}
554
+ {{- '<|im_start|>assistant\n' }}
555
+ {%- endif %}""")
556
+ assert is_chat_template_stop_token_trained(tokenizer) is False
557
+
558
+ def test_template_error_returns_false(self):
559
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3MoeForCausalLM")
560
+ tokenizer.chat_template = "{{ raise_exception('probe rejected') }}"
561
+ assert is_chat_template_stop_token_trained(tokenizer) is False
562
+
563
+
564
+ @pytest.mark.parametrize(
565
+ "tokenizer_name",
566
+ [
567
+ pytest.param("trl-internal-testing/tiny-CohereForCausalLM", id="cohere"),
568
+ pytest.param("trl-internal-testing/tiny-Cohere2ForCausalLM", id="cohere2"),
569
+ pytest.param("trl-internal-testing/tiny-DeepseekV3ForCausalLM", id="deepseekv3"),
570
+ pytest.param("trl-internal-testing/tiny-GemmaForCausalLM", id="gemma"),
571
+ pytest.param("trl-internal-testing/tiny-Gemma2ForCausalLM", id="gemma2"),
572
+ pytest.param("trl-internal-testing/tiny-Gemma3ForConditionalGeneration", id="gemma3", marks=require_vision),
573
+ pytest.param(
574
+ "trl-internal-testing/tiny-Glm4MoeForCausalLM",
575
+ id="glm4moe",
576
+ marks=pytest.mark.skipif(
577
+ Version(transformers.__version__) < Version("5.0.0"),
578
+ reason="GLM4 tokenizer requires transformers>=5.0.0",
579
+ ),
580
+ ),
581
+ pytest.param("trl-internal-testing/tiny-GptOssForCausalLM", id="gptoss"),
582
+ pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3", id="llama3"),
583
+ pytest.param("trl-internal-testing/tiny-LlavaForConditionalGeneration", id="llava", marks=require_vision),
584
+ pytest.param(
585
+ "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", id="llava_next", marks=require_vision
586
+ ),
587
+ pytest.param(
588
+ "trl-internal-testing/tiny-NemotronHForCausalLM-nano",
589
+ id="nemotron_3_nano",
590
+ marks=pytest.mark.skipif(
591
+ Version(transformers.__version__) < Version("5.3.0"),
592
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
593
+ ),
594
+ ),
595
+ pytest.param(
596
+ "trl-internal-testing/tiny-NemotronHForCausalLM-super",
597
+ id="nemotron_3_super",
598
+ marks=pytest.mark.skipif(
599
+ Version(transformers.__version__) < Version("5.3.0"),
600
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
601
+ ),
602
+ ),
603
+ pytest.param(
604
+ "trl-internal-testing/tiny-NemotronHForCausalLM-ultra",
605
+ id="nemotron_3_ultra",
606
+ marks=pytest.mark.skipif(
607
+ Version(transformers.__version__) < Version("5.3.0"),
608
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
609
+ ),
610
+ ),
611
+ pytest.param("trl-internal-testing/tiny-Phi3ForCausalLM-3", id="phi3"),
612
+ pytest.param("trl-internal-testing/tiny-Phi3ForCausalLM-3.5", id="phi3.5"),
613
+ pytest.param("trl-internal-testing/tiny-Qwen2VLForConditionalGeneration", id="qwen2_vl", marks=require_vision),
614
+ pytest.param("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", id="qwen2.5"),
615
+ pytest.param(
616
+ "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", id="qwen2.5_vl", marks=require_vision
617
+ ),
618
+ pytest.param("trl-internal-testing/tiny-Qwen3MoeForCausalLM", id="qwen3"),
619
+ pytest.param("trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", id="qwen3_instruct_2507"),
620
+ pytest.param(
621
+ "trl-internal-testing/tiny-Qwen3VLForConditionalGeneration",
622
+ id="qwen3_vl",
623
+ marks=[
624
+ require_vision,
625
+ pytest.mark.skipif(
626
+ Version(transformers.__version__) < Version("4.57.0"),
627
+ reason="Qwen3-VL was introduced in transformers-4.57.0",
628
+ ),
629
+ ],
630
+ ),
631
+ pytest.param(
632
+ "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink",
633
+ id="qwen35-nothink",
634
+ marks=[
635
+ require_vision,
636
+ pytest.mark.skipif(
637
+ Version(transformers.__version__) < Version("5.0.0"),
638
+ reason="Qwen3.5 tokenizer requires transformers>=5.0.0",
639
+ ),
640
+ ],
641
+ ),
642
+ pytest.param(
643
+ "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-Think",
644
+ id="qwen35-think",
645
+ marks=[
646
+ require_vision,
647
+ pytest.mark.skipif(
648
+ Version(transformers.__version__) < Version("5.0.0"),
649
+ reason="Qwen3.5 tokenizer requires transformers>=5.0.0",
650
+ ),
651
+ ],
652
+ ),
653
+ pytest.param(
654
+ "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6",
655
+ id="qwen36",
656
+ marks=[
657
+ require_vision,
658
+ pytest.mark.skipif(
659
+ Version(transformers.__version__) < Version("5.0.0"),
660
+ reason="Qwen3.5 tokenizer requires transformers>=5.0.0",
661
+ ),
662
+ ],
663
+ ),
664
+ ],
665
+ )
666
+ class TestGetTrainingChatTemplate:
667
+ def _load(self, model_name):
668
+ if "ForCausalLM" in model_name:
669
+ self.is_vlm = False
670
+ processing_class = AutoTokenizer.from_pretrained(model_name)
671
+ elif "ForConditionalGeneration" in model_name:
672
+ self.is_vlm = True
673
+ processing_class = AutoProcessor.from_pretrained(model_name)
674
+
675
+ return processing_class
676
+
677
+ def test_new_chat_template_is_prefix_preserving(self, tokenizer_name):
678
+ tokenizer = self._load(tokenizer_name)
679
+ new_chat_template = get_training_chat_template(tokenizer)
680
+ if new_chat_template is not None:
681
+ tokenizer.chat_template = new_chat_template
682
+ # Prefix-preservation is only meaningful for templates that actually support tool messages — the check
683
+ # itself renders one. Skip the assertion for tool-less templates (e.g. Gemma).
684
+ if not supports_tool_calling(tokenizer):
685
+ pytest.skip("Template does not support tool calling; prefix-preservation check is not applicable.")
686
+ assert is_chat_template_prefix_preserving(tokenizer) is True
687
+
688
+ def test_new_chat_template_trains_stop_token(self, tokenizer_name, request):
689
+ if tokenizer_name in (
690
+ "trl-internal-testing/tiny-LlavaForConditionalGeneration",
691
+ "trl-internal-testing/tiny-LlavaNextForConditionalGeneration",
692
+ ):
693
+ reason = f"{tokenizer_name}: the processor returns an all-zero assistant tokens mask"
694
+ request.node.add_marker(pytest.mark.xfail(strict=False, reason=reason))
695
+ tokenizer = self._load(tokenizer_name)
696
+ new_chat_template = get_training_chat_template(tokenizer)
697
+ assert is_chat_template_stop_token_trained(tokenizer, chat_template=new_chat_template) is True
698
+
699
+ def test_behavior_unchanged_single_user_no_generation_prompt(self, tokenizer_name):
700
+ tokenizer = self._load(tokenizer_name)
701
+ messages = [{"role": "user", "content": "What color is the sky?"}]
702
+ if self.is_vlm:
703
+ messages = prepare_multimodal_messages(messages)
704
+
705
+ before = tokenizer.apply_chat_template(messages, tokenize=False)
706
+ new_chat_template = get_training_chat_template(tokenizer)
707
+ after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template)
708
+ assert before == after
709
+
710
+ def test_behavior_unchanged_single_user_with_generation_prompt(self, tokenizer_name):
711
+ tokenizer = self._load(tokenizer_name)
712
+ messages = [{"role": "user", "content": "What color is the sky?"}]
713
+ if self.is_vlm:
714
+ messages = prepare_multimodal_messages(messages)
715
+
716
+ before = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
717
+ new_chat_template = get_training_chat_template(tokenizer)
718
+ after = tokenizer.apply_chat_template(
719
+ messages,
720
+ tokenize=False,
721
+ add_generation_prompt=True,
722
+ chat_template=new_chat_template,
723
+ )
724
+ assert before == after
725
+
726
+ def test_behavior_unchanged_single_user_and_final_assistant_plain_content(self, tokenizer_name):
727
+ tokenizer = self._load(tokenizer_name)
728
+ messages = [
729
+ {"role": "user", "content": "What color is the sky?"},
730
+ {"role": "assistant", "content": "It is blue."},
731
+ ]
732
+ if self.is_vlm:
733
+ messages = prepare_multimodal_messages(messages)
734
+
735
+ before = tokenizer.apply_chat_template(messages, tokenize=False)
736
+ new_chat_template = get_training_chat_template(tokenizer)
737
+ after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template)
738
+ if tokenizer_name == "trl-internal-testing/tiny-Glm4MoeForCausalLM":
739
+ # GLM's native template doesn't terminate an assistant turn with an end-of-turn token; the turn is ended
740
+ # by the following message's role marker. The training template appends that terminator to the final
741
+ # assistant turn so the stop token is trained — here the `<|user|>` that would open the next turn.
742
+ assert after == before + "<|user|>"
743
+ else:
744
+ assert before == after
745
+
746
+ def test_behavior_unchanged_final_assistant_with_reasoning_content(self, tokenizer_name):
747
+ tokenizer = self._load(tokenizer_name)
748
+ messages = [
749
+ {"role": "user", "content": "What color is the sky?"},
750
+ {
751
+ "role": "assistant",
752
+ "content": "It is blue.",
753
+ "reasoning_content": "The sky appears blue due to Rayleigh scattering.",
754
+ },
755
+ ]
756
+ if self.is_vlm:
757
+ messages = prepare_multimodal_messages(messages)
758
+
759
+ before = tokenizer.apply_chat_template(messages, tokenize=False)
760
+ new_chat_template = get_training_chat_template(tokenizer)
761
+ after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template)
762
+ if tokenizer_name == "trl-internal-testing/tiny-Glm4MoeForCausalLM":
763
+ # GLM's native template doesn't terminate an assistant turn with an end-of-turn token; the turn is ended
764
+ # by the following message's role marker. The training template appends that terminator to the final
765
+ # assistant turn so the stop token is trained — here the `<|user|>` that would open the next turn.
766
+ assert after == before + "<|user|>"
767
+ else:
768
+ assert before == after
769
+
770
+ def test_behavior_unchanged_final_assistant_with_existing_think_tags(self, tokenizer_name):
771
+ tokenizer = self._load(tokenizer_name)
772
+ messages = [
773
+ {"role": "user", "content": "What color is the sky?"},
774
+ {
775
+ "role": "assistant",
776
+ "content": "<think>\nThe sky scatters shorter wavelengths.\n</think>\n\nIt is blue.",
777
+ },
778
+ ]
779
+ if self.is_vlm:
780
+ messages = prepare_multimodal_messages(messages)
781
+
782
+ before = tokenizer.apply_chat_template(messages, tokenize=False)
783
+ new_chat_template = get_training_chat_template(tokenizer)
784
+ after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template)
785
+ if tokenizer_name == "trl-internal-testing/tiny-Glm4MoeForCausalLM":
786
+ # GLM's native template doesn't terminate an assistant turn with an end-of-turn token; the turn is ended
787
+ # by the following message's role marker. The training template appends that terminator to the final
788
+ # assistant turn so the stop token is trained — here the `<|user|>` that would open the next turn.
789
+ assert after == before + "<|user|>"
790
+ else:
791
+ assert before == after
792
+
793
+ def test_behavior_unchanged_assistant_with_tool_calls(self, tokenizer_name):
794
+ tokenizer = self._load(tokenizer_name)
795
+ tool_calls = [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}]
796
+ messages = [
797
+ {"role": "user", "content": "Multiply 3 by 4."},
798
+ {"role": "assistant", "content": "I will call a tool.", "tool_calls": tool_calls},
799
+ ]
800
+ if self.is_vlm:
801
+ messages = prepare_multimodal_messages(messages)
802
+
803
+ messages_before = copy.deepcopy(messages)
804
+ if tokenizer_name == "trl-internal-testing/tiny-DeepseekV3ForCausalLM":
805
+ # Best-effort fallback for templates that reject dict args (e.g. DeepSeek-V3). This is a chat template
806
+ # bug (see transformers#45419), and the training chat template fixes it to avoid blocking users.
807
+ messages_before[1]["tool_calls"][0]["function"]["arguments"] = '{"a": 3, "b": 4}'
808
+
809
+ before = tokenizer.apply_chat_template(messages_before, tokenize=False)
810
+ new_chat_template = get_training_chat_template(tokenizer)
811
+ after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template)
812
+ if tokenizer_name == "trl-internal-testing/tiny-Glm4MoeForCausalLM":
813
+ # GLM's native template doesn't terminate an assistant turn with an end-of-turn token; the turn is ended
814
+ # by the following message's role marker. The training template appends that terminator to the final
815
+ # assistant turn so the stop token is trained — here `<|observation|>`, which closes a tool call.
816
+ assert after == before + "<|observation|>"
817
+ else:
818
+ assert before == after
819
+
820
+ def test_behavior_unchanged_with_tools_with_and_without_system_message(self, tokenizer_name):
821
+ tokenizer = self._load(tokenizer_name)
822
+ tools = [
823
+ {
824
+ "type": "function",
825
+ "function": {
826
+ "name": "multiply",
827
+ "description": "Multiply two numbers.",
828
+ "parameters": {
829
+ "type": "object",
830
+ "properties": {
831
+ "a": {"type": "number"},
832
+ "b": {"type": "number"},
833
+ },
834
+ "required": ["a", "b"],
835
+ },
836
+ },
837
+ }
838
+ ]
839
+ messages = [{"role": "user", "content": "Multiply 3 by 4."}]
840
+ if self.is_vlm:
841
+ messages = prepare_multimodal_messages(messages)
842
+
843
+ before = tokenizer.apply_chat_template(messages, tokenize=False, tools=tools)
844
+ new_chat_template = get_training_chat_template(tokenizer)
845
+ after = tokenizer.apply_chat_template(messages, tokenize=False, tools=tools, chat_template=new_chat_template)
846
+ assert before == after
847
+
848
+ def test_behavior_unchanged_with_tools_with_system_message(self, tokenizer_name):
849
+ tokenizer = self._load(tokenizer_name)
850
+ if not supports_tool_calling(tokenizer):
851
+ pytest.skip("Template does not support tool calling; skipping tool_calls test.")
852
+ tools = [
853
+ {
854
+ "type": "function",
855
+ "function": {
856
+ "name": "multiply",
857
+ "description": "Multiply two numbers.",
858
+ "parameters": {
859
+ "type": "object",
860
+ "properties": {"a": {"type": "number"}, "b": {"type": "number"}},
861
+ "required": ["a", "b"],
862
+ },
863
+ },
864
+ }
865
+ ]
866
+ messages = [
867
+ {"role": "system", "content": "You are a helpful assistant."},
868
+ {"role": "user", "content": "Multiply 3 by 4."},
869
+ ]
870
+ if self.is_vlm:
871
+ messages = prepare_multimodal_messages(messages)
872
+
873
+ before = tokenizer.apply_chat_template(messages, tokenize=False, tools=tools)
874
+ new_chat_template = get_training_chat_template(tokenizer)
875
+ after = tokenizer.apply_chat_template(messages, tokenize=False, tools=tools, chat_template=new_chat_template)
876
+ assert before == after
877
+
878
+ def test_behavior_unchanged_generation_prompt_with_enable_thinking_false(self, tokenizer_name):
879
+ tokenizer = self._load(tokenizer_name)
880
+ messages = [{"role": "user", "content": "What color is the sky?"}]
881
+ if self.is_vlm:
882
+ messages = prepare_multimodal_messages(messages)
883
+
884
+ before = tokenizer.apply_chat_template(
885
+ messages, tokenize=False, add_generation_prompt=True, enable_thinking=False
886
+ )
887
+ new_chat_template = get_training_chat_template(tokenizer)
888
+ after = tokenizer.apply_chat_template(
889
+ messages,
890
+ tokenize=False,
891
+ add_generation_prompt=True,
892
+ enable_thinking=False,
893
+ chat_template=new_chat_template,
894
+ )
895
+ assert before == after
896
+
897
+ def test_assistant_masks(self, tokenizer_name, request):
898
+ if tokenizer_name == "trl-internal-testing/tiny-LlavaForConditionalGeneration":
899
+ request.node.add_marker(
900
+ pytest.mark.xfail(
901
+ reason="Llava's official chat template `{% generation %}` markers don't yield assistant masks "
902
+ "through the processor path. It is not a supported training template.",
903
+ strict=True,
904
+ )
905
+ )
906
+ tokenizer = self._load(tokenizer_name)
907
+ messages = [
908
+ {"role": "user", "content": "What color is the sky?"},
909
+ {"role": "assistant", "content": "It is blue."},
910
+ ]
911
+ if self.is_vlm:
912
+ messages = prepare_multimodal_messages(messages)
913
+
914
+ chat_template = get_training_chat_template(tokenizer)
915
+ result = tokenizer.apply_chat_template(
916
+ messages, chat_template=chat_template, return_assistant_tokens_mask=True, return_dict=True, tokenize=True
917
+ )
918
+ masks = result["assistant_masks"]
919
+ if self.is_vlm: # VLM processors return batched output
920
+ masks = masks[0]
921
+ assert 1 in masks
922
+ # The first tokens (user turn) should not be masked
923
+ assert masks[0] == 0
924
+ # The last tokens (assistant turn ending with <|im_end|>) should be masked
925
+ assert masks[-1] == 1
926
+
927
+ def test_assistant_masks_multi_turn(self, tokenizer_name, request):
928
+ if tokenizer_name == "trl-internal-testing/tiny-LlavaForConditionalGeneration":
929
+ request.node.add_marker(
930
+ pytest.mark.xfail(
931
+ reason="Llava's official chat template `{% generation %}` markers don't yield assistant masks "
932
+ "through the processor path. It is not a supported training template.",
933
+ strict=True,
934
+ )
935
+ )
936
+ tokenizer = self._load(tokenizer_name)
937
+ messages = [
938
+ {"role": "user", "content": "Hi"},
939
+ {"role": "assistant", "content": "Hello!"},
940
+ {"role": "user", "content": "Bye"},
941
+ {"role": "assistant", "content": "Goodbye!"},
942
+ ]
943
+ if self.is_vlm:
944
+ messages = prepare_multimodal_messages(messages)
945
+
946
+ chat_template = get_training_chat_template(tokenizer)
947
+ result = tokenizer.apply_chat_template(
948
+ messages, chat_template=chat_template, return_assistant_tokens_mask=True, return_dict=True, tokenize=True
949
+ )
950
+ masks = result["assistant_masks"]
951
+ if self.is_vlm: # VLM processors return batched output
952
+ masks = masks[0]
953
+ # Should have two masked regions (two assistant turns): 0→1, 1→0, 0→1
954
+ transitions = sum(1 for i in range(1, len(masks)) if masks[i] != masks[i - 1])
955
+ assert transitions == 3
956
+
957
+
958
+ @pytest.mark.parametrize(
959
+ "model_name",
960
+ [
961
+ pytest.param("trl-internal-testing/tiny-Glm4MoeForCausalLM", id="glm4moe"),
962
+ pytest.param("trl-internal-testing/tiny-GptOssForCausalLM", id="gptoss"),
963
+ pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.1", id="llama3.1"),
964
+ pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.2", id="llama3.2"),
965
+ pytest.param(
966
+ "trl-internal-testing/tiny-NemotronHForCausalLM-nano",
967
+ id="nemotron_3_nano",
968
+ marks=pytest.mark.skipif(
969
+ Version(transformers.__version__) < Version("5.3.0"),
970
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
971
+ ),
972
+ ),
973
+ pytest.param(
974
+ "trl-internal-testing/tiny-NemotronHForCausalLM-super",
975
+ id="nemotron_3_super",
976
+ marks=pytest.mark.skipif(
977
+ Version(transformers.__version__) < Version("5.3.0"),
978
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
979
+ ),
980
+ ),
981
+ pytest.param(
982
+ "trl-internal-testing/tiny-NemotronHForCausalLM-ultra",
983
+ id="nemotron_3_ultra",
984
+ marks=pytest.mark.skipif(
985
+ Version(transformers.__version__) < Version("5.3.0"),
986
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
987
+ ),
988
+ ),
989
+ pytest.param("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", id="qwen2.5"),
990
+ pytest.param("trl-internal-testing/tiny-Qwen3MoeForCausalLM", id="qwen3"),
991
+ pytest.param("trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", id="qwen3_instruct_2507"),
992
+ pytest.param("trl-internal-testing/tiny-Qwen3VLForConditionalGeneration", id="qwen3_vl"),
993
+ pytest.param("trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", id="qwen35-nothink"),
994
+ pytest.param("trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-Think", id="qwen35-think"),
995
+ pytest.param("trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", id="qwen36"),
996
+ pytest.param(
997
+ "trl-internal-testing/tiny-Gemma4ForConditionalGeneration",
998
+ id="gemma4",
999
+ marks=pytest.mark.skipif(
1000
+ Version(transformers.__version__) < Version("5.5.0"),
1001
+ reason="Gemma4 models were introduced in transformers-5.5.0",
1002
+ ),
1003
+ ),
1004
+ ],
1005
+ )
1006
+ @pytest.mark.xfail(
1007
+ condition=Version(transformers.__version__) < Version("5.0.0"),
1008
+ reason="Response parsing is not supported in transformers versions below 5.0.0",
1009
+ strict=True,
1010
+ )
1011
+ @require_jmespath
1012
+ class TestParseResponse:
1013
+ def _load(self, model_name):
1014
+ if "ForCausalLM" in model_name:
1015
+ self.is_vlm = False
1016
+ processing_class = AutoTokenizer.from_pretrained(model_name)
1017
+ response_schema = getattr(processing_class, "response_schema", None)
1018
+ elif "ForConditionalGeneration" in model_name:
1019
+ self.is_vlm = True
1020
+ processing_class = AutoProcessor.from_pretrained(model_name)
1021
+ response_schema = getattr(processing_class.tokenizer, "response_schema", None)
1022
+
1023
+ if response_schema is None:
1024
+ processing_class = add_response_schema(processing_class)
1025
+
1026
+ return processing_class
1027
+
1028
+ def test_parse_response(self, model_name):
1029
+ if model_name in ("trl-internal-testing/tiny-GptOssForCausalLM",) and Version(
1030
+ transformers.__version__
1031
+ ) < Version("5.5.0"):
1032
+ pytest.skip("Upstream bug in response parsing (see #5753; fixed in transformers#45166)")
1033
+ processing_class = self._load(model_name)
1034
+ messages = [
1035
+ {"role": "user", "content": "What is 3*4?"},
1036
+ {"role": "assistant", "content": "12"},
1037
+ ]
1038
+ expected = messages[-1]
1039
+ messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
1040
+ prefix = processing_class.apply_chat_template(
1041
+ messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True
1042
+ ).input_ids
1043
+ text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
1044
+ if self.is_vlm: # VLM processors return batched output
1045
+ prefix = prefix[0]
1046
+ text = text[0]
1047
+ response = text[len(prefix) :]
1048
+ tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
1049
+ parsed = parse_response(tokenizer, response)
1050
+ assert parsed == expected
1051
+
1052
+ def test_parse_response_with_reasoning_content(self, model_name):
1053
+ if model_name in (
1054
+ "trl-internal-testing/tiny-Gemma4ForConditionalGeneration",
1055
+ "trl-internal-testing/tiny-GptOssForCausalLM",
1056
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.1",
1057
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.2",
1058
+ "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1059
+ "trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507",
1060
+ "trl-internal-testing/tiny-Qwen3VLForConditionalGeneration",
1061
+ ):
1062
+ pytest.skip("This tokenizer doesn't support inline reasoning_content.")
1063
+
1064
+ processing_class = self._load(model_name)
1065
+ messages = [
1066
+ {"role": "user", "content": "What is 3*4?"},
1067
+ {"role": "assistant", "reasoning_content": "Hmmm.", "content": "12"},
1068
+ ]
1069
+ expected = messages[-1]
1070
+ messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
1071
+ # enable_thinking=True is required here because the Qwen3.5 NoThink fixture disables thinking by default
1072
+ # for the generation prompt.
1073
+ prefix = processing_class.apply_chat_template(
1074
+ messages[:1], add_generation_prompt=True, enable_thinking=True, tokenize=True, return_dict=True
1075
+ ).input_ids
1076
+ text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
1077
+ if self.is_vlm: # VLM processors return batched output
1078
+ prefix = prefix[0]
1079
+ text = text[0]
1080
+ response = text[len(prefix) :]
1081
+ tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
1082
+ parsed = parse_response(tokenizer, response)
1083
+ assert parsed == expected
1084
+
1085
+ def test_parse_response_tool_call(self, model_name):
1086
+ if model_name in (
1087
+ "trl-internal-testing/tiny-GptOssForCausalLM",
1088
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.1",
1089
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.2",
1090
+ ) and Version(transformers.__version__) < Version("5.5.0"):
1091
+ pytest.skip("Upstream bug in response parsing (see #5753; fixed in transformers#45166)")
1092
+ processing_class = self._load(model_name)
1093
+ tool_calls = [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}]
1094
+ messages = [
1095
+ {"role": "user", "content": "What is 3*4?"},
1096
+ {
1097
+ "role": "assistant",
1098
+ # "content" is required here because VLM processors crash on tokenize=True without it
1099
+ # (KeyError in processing_utils.py). See huggingface/transformers#45290.
1100
+ "content": "",
1101
+ "tool_calls": tool_calls,
1102
+ },
1103
+ ]
1104
+ expected = messages[-1]
1105
+ messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
1106
+ prefix = processing_class.apply_chat_template(
1107
+ messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True
1108
+ ).input_ids
1109
+ text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
1110
+ if self.is_vlm: # VLM processors return batched output
1111
+ prefix = prefix[0]
1112
+ text = text[0]
1113
+ response = text[len(prefix) :]
1114
+ tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
1115
+ parsed = parse_response(tokenizer, response)
1116
+ assert parsed == expected
1117
+
1118
+ def test_parse_response_tool_call_with_content(self, model_name):
1119
+ if model_name in (
1120
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.1",
1121
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.2",
1122
+ ):
1123
+ pytest.skip("Llama 3.1 / 3.2 templates only allow a single tool call per assistant turn, with no content.")
1124
+ if model_name in ("trl-internal-testing/tiny-GptOssForCausalLM",) and Version(
1125
+ transformers.__version__
1126
+ ) < Version("5.5.0"):
1127
+ pytest.skip("Upstream bug in response parsing (see #5753; fixed in transformers#45166)")
1128
+ processing_class = self._load(model_name)
1129
+ tool_calls = [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}]
1130
+ messages = [
1131
+ {"role": "user", "content": "What is 3*4?"},
1132
+ {"role": "assistant", "content": "Let's call the tool.", "tool_calls": tool_calls},
1133
+ ]
1134
+ expected = messages[-1]
1135
+ messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
1136
+ prefix = processing_class.apply_chat_template(
1137
+ messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True
1138
+ ).input_ids
1139
+ text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
1140
+ if self.is_vlm: # VLM processors return batched output
1141
+ prefix = prefix[0]
1142
+ text = text[0]
1143
+ response = text[len(prefix) :]
1144
+ tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
1145
+ parsed = parse_response(tokenizer, response)
1146
+ assert parsed == expected
1147
+
1148
+ def test_parse_response_tool_call_without_arguments(self, model_name):
1149
+ if model_name in ("trl-internal-testing/tiny-GptOssForCausalLM",) and Version(
1150
+ transformers.__version__
1151
+ ) < Version("5.5.0"):
1152
+ pytest.skip("Upstream bug in response parsing (see #5753; fixed in transformers#45166)")
1153
+ processing_class = self._load(model_name)
1154
+ tool_calls = [{"type": "function", "function": {"name": "ping", "arguments": {}}}]
1155
+ messages = [
1156
+ {"role": "user", "content": "Ping the service."},
1157
+ {
1158
+ "role": "assistant",
1159
+ # "content" is required here because VLM processors crash on tokenize=True without it
1160
+ # (KeyError in processing_utils.py). See huggingface/transformers#45290.
1161
+ "content": "",
1162
+ "tool_calls": tool_calls,
1163
+ },
1164
+ ]
1165
+ expected = messages[-1]
1166
+ messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
1167
+ prefix = processing_class.apply_chat_template(
1168
+ messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True
1169
+ ).input_ids
1170
+ text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
1171
+ if self.is_vlm: # VLM processors return batched output
1172
+ prefix = prefix[0]
1173
+ text = text[0]
1174
+ response = text[len(prefix) :]
1175
+ tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
1176
+ parsed = parse_response(tokenizer, response)
1177
+ assert parsed == expected
1178
+
1179
+ def test_parse_response_multiple_tool_calls(self, model_name):
1180
+ if model_name in (
1181
+ "trl-internal-testing/tiny-GptOssForCausalLM",
1182
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.1",
1183
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.2",
1184
+ ):
1185
+ pytest.skip("This template only renders one tool call per assistant message.")
1186
+ processing_class = self._load(model_name)
1187
+ tool_calls = [
1188
+ {"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}},
1189
+ {"type": "function", "function": {"name": "addition", "arguments": {"a": 4, "b": 3}}},
1190
+ ]
1191
+ messages = [
1192
+ {"role": "user", "content": "What is 3*4?"},
1193
+ {
1194
+ "role": "assistant",
1195
+ # "content" is required here because VLM processors crash on tokenize=True without it
1196
+ # (KeyError in processing_utils.py). See huggingface/transformers#45290.
1197
+ "content": "",
1198
+ "tool_calls": tool_calls,
1199
+ },
1200
+ ]
1201
+ expected = messages[-1]
1202
+ messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
1203
+ prefix = processing_class.apply_chat_template(
1204
+ messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True
1205
+ ).input_ids
1206
+ text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
1207
+ if self.is_vlm: # VLM processors return batched output
1208
+ prefix = prefix[0]
1209
+ text = text[0]
1210
+ response = text[len(prefix) :]
1211
+ tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
1212
+ parsed = parse_response(tokenizer, response)
1213
+ assert parsed == expected
1214
+
1215
+ def test_parse_response_malformed_tool_call(self, model_name):
1216
+ if model_name != "trl-internal-testing/tiny-Qwen3MoeForCausalLM":
1217
+ pytest.skip("For simplicity, we only test the malformed tool call case on one tokenizer.")
1218
+ processing_class = self._load(model_name)
1219
+ text = '<tool_call>\n{"name": "multiply", "arguments": {"a": 3, "b": 4}\n</tool_call><|im_end|>'
1220
+ assistant_text = processing_class(text)["input_ids"]
1221
+ parsed = parse_response(processing_class, assistant_text)
1222
+ expected = {
1223
+ "role": "assistant",
1224
+ "content": '<tool_call>\n{"name": "multiply", "arguments": {"a": 3, "b": 4}\n</tool_call>',
1225
+ }
1226
+
1227
+ assert parsed == expected
1228
+
1229
+ def test_parse_response_truncated(self, model_name):
1230
+ processing_class = self._load(model_name)
1231
+ # Here we use 2 tool calls as it seems to be a more common source of failure when truncated.
1232
+ # Llama 3.1 / 3.2 templates only allow a single tool call per assistant turn, so fall back to one.
1233
+ tool_calls = [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}]
1234
+ if model_name not in (
1235
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.1",
1236
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.2",
1237
+ ):
1238
+ tool_calls.append({"type": "function", "function": {"name": "addition", "arguments": {"a": 4, "b": 3}}})
1239
+ messages = [
1240
+ {"role": "user", "content": "What is 3*4?"},
1241
+ {"role": "assistant", "content": "", "tool_calls": tool_calls},
1242
+ ]
1243
+ messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
1244
+ prefix = processing_class.apply_chat_template(
1245
+ messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True
1246
+ ).input_ids
1247
+ text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
1248
+ if self.is_vlm: # VLM processors return batched output
1249
+ prefix = prefix[0]
1250
+ text = text[0]
1251
+ response = text[len(prefix) :]
1252
+ tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
1253
+ # Truncate the response mid-tool-call and just check that parsing doesn't crash.
1254
+ for end in range(1, len(response)):
1255
+ parse_response(tokenizer, response[:end])
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_cli.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from io import StringIO
17
+ from unittest.mock import patch
18
+
19
+ import pytest
20
+ import yaml
21
+
22
+ from .testing_utils import TrlTestCase
23
+
24
+
25
+ @pytest.mark.parametrize("command", ["dpo", "grpo", "kto", "reward", "rloo", "sft"])
26
+ def test_help_no_type_error(command):
27
+ # Regression test for https://github.com/huggingface/trl/issues/5099:
28
+ # TrainingArguments help strings with unescaped "%" caused TypeError in argparse.
29
+ from trl.cli import main
30
+
31
+ with pytest.raises(SystemExit) as exc_info:
32
+ with patch("sys.argv", ["trl", command, "--help"]), patch("sys.stdout", new_callable=StringIO):
33
+ main()
34
+ assert exc_info.value.code == 0
35
+
36
+
37
+ class TestCLI(TrlTestCase):
38
+ def test_dpo(self):
39
+ from trl.cli import main
40
+
41
+ command = f"trl dpo --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_preference --report_to none"
42
+ with patch("sys.argv", command.split(" ")):
43
+ main()
44
+
45
+ def test_dpo_multiple_loss_types(self):
46
+ from trl.cli import main
47
+
48
+ command = f"trl dpo --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_preference --report_to none --loss_type sigmoid bco_pair --loss_weights 1.0 0.5"
49
+ with patch("sys.argv", command.split(" ")):
50
+ main()
51
+
52
+ @patch("sys.stdout", new_callable=StringIO)
53
+ def test_env(self, mock_stdout):
54
+ from trl.cli import main
55
+
56
+ command = "trl env"
57
+ with patch("sys.argv", command.split(" ")):
58
+ main()
59
+ assert "TRL version: " in mock_stdout.getvalue().strip()
60
+
61
+ def test_grpo(self):
62
+ from trl.cli import main
63
+
64
+ command = f"trl grpo --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --reward_model_name_or_path trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_prompt_only --num_generations 4 --max_completion_length 32 --report_to none"
65
+ with patch("sys.argv", command.split(" ")):
66
+ main()
67
+
68
+ def test_kto(self):
69
+ from trl.cli import main
70
+
71
+ command = f"trl kto --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_unpaired_preference --report_to none"
72
+ with patch("sys.argv", command.split(" ")):
73
+ main()
74
+
75
+ def test_reward(self):
76
+ from trl.cli import main
77
+
78
+ command = f"trl reward --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_implicit_prompt_preference --report_to none"
79
+ with patch("sys.argv", command.split(" ")):
80
+ main()
81
+
82
+ def test_rloo(self):
83
+ from trl.cli import main
84
+
85
+ command = f"trl rloo --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --reward_model_name_or_path trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_prompt_only --num_generations 2 --max_completion_length 32 --report_to none"
86
+ with patch("sys.argv", command.split(" ")):
87
+ main()
88
+
89
+ def test_sft(self):
90
+ from trl.cli import main
91
+
92
+ command = f"trl sft --output_dir {self.tmp_dir} --model_name_or_path trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 --dataset_name trl-internal-testing/zen --dataset_config standard_language_modeling --report_to none"
93
+ with patch("sys.argv", command.split(" ")):
94
+ main()
95
+
96
+ def test_sft_config_file(self):
97
+ from trl.cli import main
98
+
99
+ output_dir = os.path.join(self.tmp_dir, "output")
100
+
101
+ # Create a temporary config file
102
+ config_path = os.path.join(self.tmp_dir, "config.yaml")
103
+ config_content = {
104
+ "model_name_or_path": "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
105
+ "dataset_name": "trl-internal-testing/zen",
106
+ "dataset_config": "standard_language_modeling",
107
+ "report_to": "none",
108
+ "output_dir": output_dir,
109
+ "lr_scheduler_type": "cosine_with_restarts",
110
+ }
111
+ with open(config_path, "w") as config_file:
112
+ yaml.dump(config_content, config_file)
113
+
114
+ # Test the CLI with config file
115
+ command = f"trl sft --config {config_path}"
116
+ with patch("sys.argv", command.split(" ")):
117
+ main()
118
+
119
+ # Verify that output directory was created
120
+ assert os.path.exists(output_dir)
121
+
122
+ def test_vllm_serve_config_file(self):
123
+ """
124
+ Test `trl vllm-serve --config config.yaml` must not raise "the following arguments are required: --model" when
125
+ the required field is satisfied by the config file rather than the command line.
126
+ """
127
+ from trl.cli import main
128
+
129
+ config_path = os.path.join(self.tmp_dir, "config.yaml")
130
+ with open(config_path, "w") as f:
131
+ yaml.dump({"model": "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"}, f)
132
+
133
+ # Patch the actual function that `VllmServeCommand.run` imports as `vllm_serve_main`
134
+ with patch("trl.scripts.vllm_serve.main") as mock_serve:
135
+ with patch("sys.argv", ["trl", "vllm-serve", "--config", config_path]):
136
+ main()
137
+
138
+ mock_serve.assert_called_once()
139
+ script_args = mock_serve.call_args.args[0]
140
+ assert script_args.model == "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_cli_utils.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 tempfile
16
+ from dataclasses import dataclass
17
+ from unittest.mock import mock_open, patch
18
+
19
+ import pytest
20
+ from datasets import DatasetDict, load_dataset
21
+
22
+ from trl import DatasetMixtureConfig, TrlParser, get_dataset
23
+ from trl.scripts.utils import DatasetConfig
24
+
25
+ from .testing_utils import TrlTestCase
26
+
27
+
28
+ @dataclass
29
+ class MyDataclass:
30
+ arg1: int
31
+ arg2: str = "default"
32
+
33
+
34
+ @dataclass
35
+ class InvalidDataclass:
36
+ config: str # This should raise an error in the TrlParser
37
+
38
+
39
+ class TestTrlParser(TrlTestCase):
40
+ def test_init_without_config_field(self):
41
+ """Test initialization without 'config' field in the dataclasses."""
42
+ parser = TrlParser(dataclass_types=[MyDataclass])
43
+ assert isinstance(parser, TrlParser)
44
+
45
+ def test_init_with_config_field(self):
46
+ """Test initialization with a 'config' field in the dataclass (should raise ValueError)."""
47
+ with pytest.raises(ValueError, match="has a field named 'config'"):
48
+ TrlParser(dataclass_types=[InvalidDataclass])
49
+
50
+ @patch("builtins.open", mock_open(read_data="env:\n VAR1: value1\n VAR2: value2\narg1: 2"))
51
+ @patch("yaml.safe_load")
52
+ @patch("os.environ", new_callable=dict) # Mock os.environ as a dictionary
53
+ def test_parse_args_and_config_with_valid_config(self, mock_environ, mock_yaml_load):
54
+ """Test parse_args_and_config method with valid arguments and config."""
55
+ mock_yaml_load.return_value = {"env": {"VAR1": "value1", "VAR2": "value2"}, "arg1": 2}
56
+
57
+ parser = TrlParser(dataclass_types=[MyDataclass])
58
+
59
+ args = ["--arg2", "value", "--config", "config.yaml"] # don't set arg1 to test default value
60
+
61
+ # Simulate the config being loaded and environment variables being set
62
+ result_args = parser.parse_args_and_config(args)
63
+
64
+ # Set the environment variables using the mock
65
+ mock_environ["VAR1"] = "value1"
66
+ mock_environ["VAR2"] = "value2"
67
+
68
+ # Ensure that the environment variables were set correctly
69
+ assert mock_environ.get("VAR1") == "value1"
70
+ assert mock_environ.get("VAR2") == "value2"
71
+
72
+ # Check the parsed arguments
73
+ assert len(result_args) == 1
74
+ assert isinstance(result_args[0], MyDataclass)
75
+ assert result_args[0].arg1 == 2
76
+ assert result_args[0].arg2 == "value"
77
+
78
+ @patch("builtins.open", mock_open(read_data="arg1: 2"))
79
+ @patch("yaml.safe_load")
80
+ def test_parse_args_and_arg_override_config(self, mock_yaml_load):
81
+ """Test parse_args_and_config method and check that arguments override the config."""
82
+ mock_yaml_load.return_value = {"arg1": 2} # this arg is meant to be overridden
83
+
84
+ parser = TrlParser(dataclass_types=[MyDataclass])
85
+
86
+ args = ["--arg1", "3", "--config", "config.yaml"] # override arg1 default with 3
87
+
88
+ # Simulate the config being loaded and arguments being passed
89
+ result_args = parser.parse_args_and_config(args)
90
+
91
+ # Check the parsed arguments
92
+ assert len(result_args) == 1
93
+ assert isinstance(result_args[0], MyDataclass)
94
+ assert result_args[0].arg1 == 3
95
+
96
+ @patch("builtins.open", mock_open(read_data="env: not_a_dict"))
97
+ @patch("yaml.safe_load")
98
+ def test_parse_args_and_config_with_invalid_env(self, mock_yaml_load):
99
+ """Test parse_args_and_config method when the 'env' field is not a dictionary."""
100
+ mock_yaml_load.return_value = {"env": "not_a_dict"}
101
+
102
+ parser = TrlParser(dataclass_types=[MyDataclass])
103
+
104
+ args = ["--arg1", "2", "--arg2", "value", "--config", "config.yaml"]
105
+
106
+ with pytest.raises(ValueError, match="`env` field should be a dict in the YAML file."):
107
+ parser.parse_args_and_config(args)
108
+
109
+ def test_parse_args_and_config_without_config(self):
110
+ """Test parse_args_and_config without the `--config` argument."""
111
+ parser = TrlParser(dataclass_types=[MyDataclass])
112
+
113
+ args = ["--arg1", "2", "--arg2", "value"]
114
+
115
+ # Simulate no config, just parse args normally
116
+ result_args = parser.parse_args_and_config(args)
117
+
118
+ # Check that the arguments are parsed as is
119
+ assert len(result_args) == 1
120
+ assert isinstance(result_args[0], MyDataclass)
121
+ assert result_args[0].arg1 == 2
122
+ assert result_args[0].arg2 == "value"
123
+
124
+ def test_set_defaults_with_config(self):
125
+ """Test set_defaults_with_config updates the defaults."""
126
+ parser = TrlParser(dataclass_types=[MyDataclass])
127
+
128
+ # Update defaults
129
+ parser.set_defaults_with_config(arg1=42)
130
+
131
+ # Ensure the default value is updated
132
+ result_args = parser.parse_args_and_config([])
133
+ assert len(result_args) == 1
134
+ assert isinstance(result_args[0], MyDataclass)
135
+ assert result_args[0].arg1 == 42
136
+
137
+ def test_parse_args_and_config_with_remaining_strings(self):
138
+ parser = TrlParser(dataclass_types=[MyDataclass])
139
+
140
+ args = ["--arg1", "2", "--arg2", "value", "remaining"]
141
+
142
+ # Simulate no config, just parse args normally
143
+ result_args = parser.parse_args_and_config(args, return_remaining_strings=True)
144
+
145
+ # Check that the arguments are parsed as is
146
+ assert len(result_args) == 2
147
+ assert isinstance(result_args[0], MyDataclass)
148
+ assert result_args[0].arg1 == 2
149
+ assert result_args[0].arg2 == "value"
150
+ assert result_args[1] == ["remaining"]
151
+
152
+ @patch("builtins.open", mock_open(read_data="remaining_string_in_config: abc"))
153
+ @patch("yaml.safe_load")
154
+ def test_parse_args_and_config_with_remaining_strings_in_config_and_args(self, mock_yaml_load):
155
+ mock_yaml_load.return_value = {"remaining_string_in_config": "abc"}
156
+
157
+ parser = TrlParser(dataclass_types=[MyDataclass])
158
+
159
+ args = ["--arg1", "2", "--remaining_string_in_args", "def", "--config", "config.yaml"]
160
+
161
+ # Simulate the config being loaded and arguments being passed
162
+ result_args = parser.parse_args_and_config(args, return_remaining_strings=True)
163
+
164
+ # Check that the arguments are parsed as is
165
+ assert len(result_args) == 2
166
+ assert isinstance(result_args[0], MyDataclass)
167
+ assert result_args[0].arg1 == 2
168
+ assert result_args[1] == ["--remaining_string_in_config", "abc", "--remaining_string_in_args", "def"]
169
+
170
+ @patch("builtins.open", mock_open(read_data="arg1: 2\narg2: config_value"))
171
+ @patch("yaml.safe_load")
172
+ def test_subparsers_with_config_defaults(self, mock_yaml_load):
173
+ """Test that config defaults are applied to all subparsers."""
174
+ mock_yaml_load.return_value = {"arg1": 2, "arg2": "config_value"}
175
+
176
+ # Create the main parser
177
+ parser = TrlParser()
178
+
179
+ # Add subparsers
180
+ subparsers = parser.add_subparsers(dest="command", parser_class=TrlParser)
181
+
182
+ # Create a subparser for a specific command
183
+ subparsers.add_parser("subcommand", dataclass_types=[MyDataclass])
184
+
185
+ # Parse with config file
186
+ args = ["subcommand", "--config", "config.yaml"]
187
+ result_args = parser.parse_args_and_config(args)
188
+
189
+ # Check main parser arguments
190
+ assert len(result_args) == 1
191
+
192
+ # Check that config values were applied to the subparser
193
+ assert result_args[0].arg1 == 2 # Default from config
194
+ assert result_args[0].arg2 == "config_value" # Default from config
195
+
196
+ @patch("builtins.open", mock_open(read_data="arg1: 2\narg2: config_value"))
197
+ @patch("yaml.safe_load")
198
+ def test_subparsers_with_config_defaults_and_arg_override(self, mock_yaml_load):
199
+ """Test that config defaults are applied to all subparsers."""
200
+ mock_yaml_load.return_value = {"arg1": 2, "arg2": "config_value"}
201
+
202
+ # Create the main parser
203
+ parser = TrlParser()
204
+
205
+ # Add subparsers
206
+ subparsers = parser.add_subparsers(dest="command", parser_class=TrlParser)
207
+
208
+ # Create a subparser for a specific command
209
+ subparsers.add_parser("subcommand", dataclass_types=[MyDataclass])
210
+
211
+ # Test with command line arguments overriding config
212
+ args = ["subcommand", "--arg1", "3", "--config", "config.yaml"]
213
+ result_args = parser.parse_args_and_config(args)
214
+
215
+ # Command line arguments should override config
216
+ assert result_args[0].arg1 == 3
217
+ assert result_args[0].arg2 == "config_value" # Still from config
218
+
219
+ @patch("builtins.open", mock_open(read_data="arg1: 2\nthis_arg_does_not_exist: config_value"))
220
+ @patch("yaml.safe_load")
221
+ def test_subparsers_with_config_defaults_and_arg_override_wrong_name(self, mock_yaml_load):
222
+ """Test that config defaults are applied to all subparsers."""
223
+ mock_yaml_load.return_value = {"arg1": 2, "this_arg_does_not_exist": "config_value"}
224
+
225
+ # Create the main parser
226
+ parser = TrlParser()
227
+
228
+ # Add subparsers
229
+ subparsers = parser.add_subparsers(dest="command", parser_class=TrlParser)
230
+
231
+ # Create a subparser for a specific command
232
+ subparsers.add_parser("subcommand", dataclass_types=[MyDataclass])
233
+
234
+ # Test with command line arguments overriding config
235
+ args = ["subcommand", "--arg1", "3", "--config", "config.yaml"]
236
+ with pytest.raises(ValueError):
237
+ parser.parse_args_and_config(args)
238
+
239
+ parser.parse_args_and_config(args, fail_with_unknown_args=False)
240
+
241
+ @patch("builtins.open", mock_open(read_data="arg1: 2\narg2: config_value"))
242
+ @patch("yaml.safe_load")
243
+ def test_subparsers_multiple_with_config_defaults(self, mock_yaml_load):
244
+ """Test that config defaults are applied to all subparsers."""
245
+ mock_yaml_load.return_value = {"arg1": 2, "arg2": "config_value"}
246
+
247
+ # Create the main parser
248
+ parser = TrlParser()
249
+
250
+ # Add subparsers
251
+ subparsers = parser.add_subparsers(dest="command", parser_class=TrlParser)
252
+
253
+ # Create a subparser for a specific command
254
+ subparsers.add_parser("subcommand0", dataclass_types=[MyDataclass])
255
+ subparsers.add_parser("subcommand1", dataclass_types=[MyDataclass])
256
+
257
+ for idx in range(2):
258
+ # Parse with config file
259
+ args = [f"subcommand{idx}", "--config", "config.yaml"]
260
+ result_args = parser.parse_args_and_config(args)
261
+
262
+ # Check main parser arguments
263
+ assert len(result_args) == 1
264
+
265
+ # Check that config values were applied to the subparser
266
+ assert result_args[0].arg1 == 2 # Default from config
267
+ assert result_args[0].arg2 == "config_value" # Default from config
268
+
269
+
270
+ class TestGetDataset:
271
+ def test_single_dataset_with_config(self):
272
+ mixture_config = DatasetMixtureConfig(
273
+ datasets=[DatasetConfig(path="trl-internal-testing/zen", name="standard_language_modeling")]
274
+ )
275
+ result = get_dataset(mixture_config)
276
+ expected = load_dataset("trl-internal-testing/zen", "standard_language_modeling")
277
+ assert expected["train"][:] == result["train"][:]
278
+
279
+ def test_single_dataset_preference_config(self):
280
+ mixture_config = DatasetMixtureConfig(
281
+ datasets=[DatasetConfig(path="trl-internal-testing/zen", name="standard_preference")]
282
+ )
283
+ result = get_dataset(mixture_config)
284
+ expected = load_dataset("trl-internal-testing/zen", "standard_preference")
285
+ assert expected["train"][:] == result["train"][:]
286
+
287
+ def test_single_dataset_streaming(self):
288
+ mixture_config = DatasetMixtureConfig(
289
+ datasets=[DatasetConfig(path="trl-internal-testing/zen", name="standard_language_modeling")],
290
+ streaming=True,
291
+ )
292
+ result = get_dataset(mixture_config)
293
+ expected = load_dataset("trl-internal-testing/zen", "standard_language_modeling")
294
+ assert expected["train"].to_list() == list(result["train"])
295
+
296
+ def test_dataset_mixture_basic(self):
297
+ dataset_config1 = DatasetConfig(
298
+ path="trl-internal-testing/zen", name="standard_prompt_completion", split="train", columns=["prompt"]
299
+ )
300
+ dataset_config2 = DatasetConfig(
301
+ path="trl-internal-testing/zen", name="standard_preference", split="train", columns=["prompt"]
302
+ )
303
+ mixture_config = DatasetMixtureConfig(datasets=[dataset_config1, dataset_config2])
304
+ result = get_dataset(mixture_config)
305
+ assert isinstance(result, DatasetDict)
306
+ assert "train" in result
307
+ train_dataset = result["train"]
308
+ assert train_dataset.column_names == ["prompt"]
309
+ prompts = train_dataset["prompt"]
310
+ expected_first_half = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
311
+ assert prompts[: len(prompts) // 2] == expected_first_half["prompt"]
312
+ expected_second_half = load_dataset("trl-internal-testing/zen", "standard_prompt_completion", split="train")
313
+ assert prompts[len(prompts) // 2 :] == expected_second_half["prompt"]
314
+
315
+ def test_dataset_mixture_with_weights(self):
316
+ dataset_config1 = DatasetConfig(
317
+ path="trl-internal-testing/zen", name="standard_prompt_completion", split="train[:50%]", columns=["prompt"]
318
+ )
319
+ dataset_config2 = DatasetConfig(
320
+ path="trl-internal-testing/zen", name="standard_preference", split="train[:50%]", columns=["prompt"]
321
+ )
322
+ mixture_config = DatasetMixtureConfig(datasets=[dataset_config1, dataset_config2])
323
+ result = get_dataset(mixture_config)
324
+ assert isinstance(result, DatasetDict)
325
+ assert "train" in result
326
+ train_dataset = result["train"]
327
+ assert train_dataset.column_names == ["prompt"]
328
+ prompts = train_dataset["prompt"]
329
+ expected_first_half = load_dataset("trl-internal-testing/zen", "standard_preference", split="train[:50%]")
330
+ assert prompts[: len(prompts) // 2] == expected_first_half["prompt"]
331
+ expected_second_half = load_dataset(
332
+ "trl-internal-testing/zen", "standard_prompt_completion", split="train[:50%]"
333
+ )
334
+ assert prompts[len(prompts) // 2 :] == expected_second_half["prompt"]
335
+
336
+ def test_dataset_mixture_with_test_split(self):
337
+ mixture_config = DatasetMixtureConfig(
338
+ datasets=[DatasetConfig(path="trl-internal-testing/zen", name="standard_language_modeling")],
339
+ test_split_size=2,
340
+ )
341
+ result = get_dataset(mixture_config)
342
+ assert isinstance(result, DatasetDict)
343
+ assert "train" in result
344
+ assert "test" in result
345
+ assert len(result["train"]) == 15
346
+ assert len(result["test"]) == 2
347
+
348
+ def test_empty_dataset_mixture_raises_error(self):
349
+ mixture_config = DatasetMixtureConfig(datasets=[])
350
+
351
+ with pytest.raises(ValueError, match="No datasets were loaded"):
352
+ get_dataset(mixture_config)
353
+
354
+ def test_mixture_multiple_different_configs(self):
355
+ dataset_config1 = DatasetConfig(
356
+ path="trl-internal-testing/zen", name="conversational_preference", split="train", columns=["prompt"]
357
+ )
358
+ dataset_config2 = DatasetConfig(
359
+ path="trl-internal-testing/zen", name="conversational_prompt_only", split="test"
360
+ )
361
+ mixture_config = DatasetMixtureConfig(datasets=[dataset_config1, dataset_config2])
362
+ result = get_dataset(mixture_config)
363
+ assert isinstance(result, DatasetDict)
364
+ assert "train" in result
365
+ assert len(result["train"]) > 0
366
+
367
+ def test_trlparser_parses_yaml_config_correctly(self):
368
+ # Prepare YAML content exactly like your example
369
+ # docstyle-ignore
370
+ yaml_content = """
371
+ datasets:
372
+ - path: trl-internal-testing/zen
373
+ name: standard_prompt_only
374
+ - path: trl-internal-testing/zen
375
+ name: standard_preference
376
+ columns:
377
+ - prompt
378
+ """
379
+
380
+ # Write YAML to a temporary file
381
+ with tempfile.NamedTemporaryFile("w+", suffix=".yaml") as tmpfile:
382
+ tmpfile.write(yaml_content)
383
+ tmpfile.flush()
384
+ parser = TrlParser((DatasetMixtureConfig,))
385
+ args = parser.parse_args_and_config(args=["--config", tmpfile.name])[0]
386
+
387
+ # Assert that we got DatasetMixtureConfig instance
388
+ assert isinstance(args, DatasetMixtureConfig)
389
+
390
+ # Assert datasets list length
391
+ assert len(args.datasets) == 2
392
+
393
+ # Check first dataset
394
+ dataset_config1 = args.datasets[0]
395
+ assert isinstance(dataset_config1, DatasetConfig)
396
+ assert dataset_config1.path == "trl-internal-testing/zen"
397
+ assert dataset_config1.name == "standard_prompt_only"
398
+ assert dataset_config1.columns is None # No columns specified
399
+
400
+ # Check second dataset
401
+ dataset_config2 = args.datasets[1]
402
+ assert isinstance(dataset_config2, DatasetConfig)
403
+ assert dataset_config2.path == "trl-internal-testing/zen"
404
+ assert dataset_config2.name == "standard_preference"
405
+ assert dataset_config2.columns == ["prompt"] # Columns specified
406
+
407
+ def test_trlparser_parses_yaml_and_loads_dataset(self):
408
+ # Prepare YAML content exactly like your example
409
+ # docstyle-ignore
410
+ yaml_content = """
411
+ datasets:
412
+ - path: trl-internal-testing/zen
413
+ name: standard_language_modeling
414
+ """
415
+
416
+ # Write YAML to a temporary file
417
+ with tempfile.NamedTemporaryFile("w+", suffix=".yaml") as tmpfile:
418
+ tmpfile.write(yaml_content)
419
+ tmpfile.flush()
420
+ parser = TrlParser((DatasetMixtureConfig,))
421
+ args = parser.parse_args_and_config(args=["--config", tmpfile.name])[0]
422
+
423
+ # Load the dataset using get_dataset
424
+ result = get_dataset(args)
425
+ expected = load_dataset("trl-internal-testing/zen", "standard_language_modeling")
426
+ assert expected["train"][:] == result["train"][:]
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_data_utils.py ADDED
@@ -0,0 +1,1335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 copy
16
+ import textwrap
17
+ from time import strftime
18
+
19
+ import pytest
20
+ import transformers
21
+ from datasets import Dataset, DatasetDict
22
+ from packaging.version import Version
23
+ from transformers import AutoProcessor, AutoTokenizer, is_vision_available
24
+
25
+ from trl.data_utils import (
26
+ apply_chat_template,
27
+ extract_prompt,
28
+ is_conversational,
29
+ is_conversational_from_value,
30
+ maybe_apply_chat_template,
31
+ maybe_convert_to_chatml,
32
+ maybe_extract_prompt,
33
+ maybe_unpair_preference_dataset,
34
+ pack_dataset,
35
+ prepare_multimodal_messages,
36
+ prepare_multimodal_messages_vllm,
37
+ unpair_preference_dataset,
38
+ )
39
+
40
+ from .testing_utils import TrlTestCase, require_vision
41
+
42
+
43
+ if is_vision_available():
44
+ from PIL import Image
45
+
46
+
47
+ @require_vision
48
+ class TestPrepareMultimodalMessages:
49
+ def test_basic_user_assistant_conversation(self):
50
+ """Test basic conversation with user and assistant messages."""
51
+ messages = [
52
+ {"role": "user", "content": "What color is the sky?"},
53
+ {"role": "assistant", "content": "It is blue."},
54
+ ]
55
+ image = Image.new("RGB", (10, 10), color="blue")
56
+ messages = prepare_multimodal_messages(messages, images=[image])
57
+
58
+ expected = [
59
+ {
60
+ "role": "user",
61
+ "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}],
62
+ },
63
+ {
64
+ "role": "assistant",
65
+ "content": [{"type": "text", "text": "It is blue."}],
66
+ },
67
+ ]
68
+
69
+ assert messages == expected
70
+
71
+ def test_first_user_message_gets_image(self):
72
+ """Test that only the first user message gets an image."""
73
+ messages = [
74
+ {"role": "user", "content": "What color is the sky?"},
75
+ {"role": "assistant", "content": "It is blue."},
76
+ {"role": "user", "content": "How about the grass?"},
77
+ ]
78
+
79
+ image = Image.new("RGB", (10, 10), color="blue")
80
+ messages = prepare_multimodal_messages(messages, images=[image])
81
+
82
+ expected = [
83
+ {
84
+ "role": "user",
85
+ "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}],
86
+ },
87
+ {
88
+ "role": "assistant",
89
+ "content": [{"type": "text", "text": "It is blue."}],
90
+ },
91
+ {
92
+ "role": "user",
93
+ "content": [{"type": "text", "text": "How about the grass?"}],
94
+ },
95
+ ]
96
+
97
+ assert messages == expected
98
+
99
+ def test_multiple_images(self):
100
+ """Test that multiple images are added to the first user message."""
101
+ messages = [
102
+ {"role": "user", "content": "What color is the sky?"},
103
+ {"role": "assistant", "content": "It is blue."},
104
+ ]
105
+ images = [Image.new("RGB", (10, 10), color=color) for color in ["red", "green", "blue"]]
106
+ messages = prepare_multimodal_messages(messages, images=images)
107
+
108
+ expected = [
109
+ {
110
+ "role": "user",
111
+ "content": [
112
+ {"type": "image", "image": images[0]},
113
+ {"type": "image", "image": images[1]},
114
+ {"type": "image", "image": images[2]},
115
+ {"type": "text", "text": "What color is the sky?"},
116
+ ],
117
+ },
118
+ {
119
+ "role": "assistant",
120
+ "content": [{"type": "text", "text": "It is blue."}],
121
+ },
122
+ ]
123
+
124
+ assert messages == expected
125
+
126
+ def test_system_message_transformation(self):
127
+ """Test that system messages are properly transformed."""
128
+ messages = [
129
+ {"role": "system", "content": "You are a helpful assistant"},
130
+ {"role": "user", "content": "What color is the sky?"},
131
+ ]
132
+
133
+ image = Image.new("RGB", (10, 10), color="blue")
134
+ messages = prepare_multimodal_messages(messages, images=[image])
135
+
136
+ expected = [
137
+ {
138
+ "role": "system",
139
+ "content": [{"type": "text", "text": "You are a helpful assistant"}],
140
+ },
141
+ {
142
+ "role": "user",
143
+ "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}],
144
+ },
145
+ ]
146
+
147
+ assert messages == expected
148
+
149
+ def test_already_prepared_messages_unchanged(self):
150
+ """Test that messages with list content are not modified."""
151
+ messages = [
152
+ {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant"}]},
153
+ {"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What color is the sky?"}]},
154
+ {"role": "assistant", "content": [{"type": "text", "text": "It is blue."}]},
155
+ ]
156
+
157
+ image = Image.new("RGB", (10, 10), color="blue")
158
+ messages = prepare_multimodal_messages(messages, images=[image])
159
+
160
+ expected = [
161
+ {
162
+ "role": "system",
163
+ "content": [{"type": "text", "text": "You are a helpful assistant"}],
164
+ },
165
+ {
166
+ "role": "user",
167
+ "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}],
168
+ },
169
+ {
170
+ "role": "assistant",
171
+ "content": [{"type": "text", "text": "It is blue."}],
172
+ },
173
+ ]
174
+
175
+ assert messages == expected
176
+
177
+ def test_mixed_prepared_and_unprepared_messages(self):
178
+ """Test handling of mixed prepared and unprepared messages."""
179
+ messages = [
180
+ {"role": "user", "content": "What color is the sky?"},
181
+ {"role": "assistant", "content": [{"type": "text", "text": "It is blue."}]},
182
+ {"role": "user", "content": "What about the grass?"},
183
+ ]
184
+
185
+ image = Image.new("RGB", (10, 10), color="blue")
186
+ messages = prepare_multimodal_messages(messages, images=[image])
187
+
188
+ expected = [
189
+ {
190
+ "role": "user",
191
+ "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}],
192
+ },
193
+ {
194
+ "role": "assistant",
195
+ "content": [{"type": "text", "text": "It is blue."}],
196
+ },
197
+ {
198
+ "role": "user",
199
+ "content": [{"type": "text", "text": "What about the grass?"}],
200
+ },
201
+ ]
202
+
203
+ assert messages == expected
204
+
205
+ def test_message_with_tool_calling_turns(self):
206
+ """Test that both the assistant tool call and the tool role turns messages are properly transformed."""
207
+ messages = [
208
+ {"role": "user", "content": "What's the weather like in New York?"},
209
+ {
210
+ "role": "assistant",
211
+ "tool_calls": [
212
+ {
213
+ "type": "tool",
214
+ "function": {"name": "get_current_weather", "arguments": {"location": "New York"}},
215
+ }
216
+ ],
217
+ },
218
+ {"role": "tool", "name": "get_current_weather", "content": "22.0"},
219
+ {"role": "assistant", "content": "The current weather in New York is 22.0 degrees Celsius."},
220
+ ]
221
+
222
+ messages = prepare_multimodal_messages(messages)
223
+
224
+ expected = [
225
+ {
226
+ "role": "user",
227
+ "content": [{"type": "text", "text": "What's the weather like in New York?"}],
228
+ },
229
+ {
230
+ "role": "assistant",
231
+ "tool_calls": [
232
+ {
233
+ "type": "tool",
234
+ "function": {"name": "get_current_weather", "arguments": {"location": "New York"}},
235
+ }
236
+ ],
237
+ },
238
+ {"role": "tool", "name": "get_current_weather", "content": [{"type": "text", "text": "22.0"}]},
239
+ {
240
+ "role": "assistant",
241
+ "content": [{"type": "text", "text": "The current weather in New York is 22.0 degrees Celsius."}],
242
+ },
243
+ ]
244
+
245
+ assert messages == expected
246
+
247
+ def test_prepared_image_blocks_without_new_images(self):
248
+ """Test that existing image payloads are preserved when no new images are provided."""
249
+ image = Image.new("RGB", (10, 10), color="blue")
250
+ messages = [
251
+ {
252
+ "role": "user",
253
+ "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}],
254
+ },
255
+ {"role": "assistant", "content": "It is blue."},
256
+ ]
257
+
258
+ messages = prepare_multimodal_messages(messages)
259
+
260
+ expected = [
261
+ {
262
+ "role": "user",
263
+ "content": [{"type": "image", "image": image}, {"type": "text", "text": "What color is the sky?"}],
264
+ },
265
+ {"role": "assistant", "content": [{"type": "text", "text": "It is blue."}]},
266
+ ]
267
+
268
+ assert messages == expected
269
+
270
+
271
+ @require_vision
272
+ class TestPrepareMultimodalMessagesVLLM:
273
+ def test_single_image_conversion(self):
274
+ messages = [
275
+ {
276
+ "role": "user",
277
+ "content": [
278
+ {"type": "image", "image": Image.new("RGB", (10, 10), color="blue")},
279
+ {"type": "text", "text": "What color is the sky?"},
280
+ ],
281
+ }
282
+ ]
283
+
284
+ result = prepare_multimodal_messages_vllm(messages)
285
+
286
+ # Original should remain unchanged (deepcopy test)
287
+ assert messages[0]["content"][0]["type"] == "image"
288
+
289
+ # Converted version should have correct structure
290
+ assert result[0]["content"][0]["type"] == "image_pil"
291
+ assert "image_pil" in result[0]["content"][0]
292
+ assert "image" not in result[0]["content"][0]
293
+ assert isinstance(result[0]["content"][0]["image_pil"], Image.Image)
294
+ assert result[0]["content"][1]["type"] == "text"
295
+
296
+ def test_mixed_content_conversion(self):
297
+ messages = [
298
+ {
299
+ "role": "user",
300
+ "content": [
301
+ {"type": "text", "text": "What color is the sky?"},
302
+ {"type": "image", "image": Image.new("RGB", (10, 10), color="blue")},
303
+ ],
304
+ }
305
+ ]
306
+
307
+ result = prepare_multimodal_messages_vllm(messages)
308
+
309
+ # The image part should be converted, text should be unchanged
310
+ assert result[0]["content"][0]["type"] == "text"
311
+ assert result[0]["content"][1]["type"] == "image_pil"
312
+
313
+ def test_no_images(self):
314
+ messages = [{"role": "user", "content": [{"type": "text", "text": "What color is the sky?"}]}]
315
+
316
+ result = prepare_multimodal_messages_vllm(messages)
317
+
318
+ # Should be identical since there are no images
319
+ assert result == messages
320
+ # And a deepcopy — not the same object
321
+ assert result is not messages
322
+ assert result[0] is not messages[0]
323
+
324
+ def test_multiple_messages(self):
325
+ messages = [
326
+ {
327
+ "role": "user",
328
+ "content": [
329
+ {"type": "text", "text": "What color is the sky?"},
330
+ {"type": "image", "image": Image.new("RGB", (10, 10), color="blue")},
331
+ ],
332
+ },
333
+ {
334
+ "role": "assistant",
335
+ "content": [{"type": "text", "text": "It is blue."}],
336
+ },
337
+ ]
338
+
339
+ result = prepare_multimodal_messages_vllm(messages)
340
+
341
+ assert result[0]["content"][1]["type"] == "image_pil"
342
+ assert result[1]["content"][0]["type"] == "text"
343
+ assert result[1]["content"][0]["text"] == "It is blue."
344
+
345
+ def test_deepcopy_integrity(self):
346
+ messages = [
347
+ {
348
+ "role": "user",
349
+ "content": [
350
+ {"type": "text", "text": "What color is the sky?"},
351
+ {"type": "image", "image": Image.new("RGB", (10, 10), color="blue")},
352
+ ],
353
+ },
354
+ ]
355
+ original = copy.deepcopy(messages)
356
+
357
+ _ = prepare_multimodal_messages_vllm(messages)
358
+
359
+ # Original should not be mutated
360
+ assert messages == original
361
+
362
+
363
+ class TestIsConversational(TrlTestCase):
364
+ # fmt: off
365
+ conversational_examples = [
366
+ { # Language modeling
367
+ "messages": [
368
+ {"role": "user", "content": "What color is the sky?"},
369
+ {"role": "assistant", "content": "It is blue."},
370
+ ],
371
+ },
372
+ { # Prompt-only
373
+ "prompt": [{"role": "user", "content": "What color is the sky?"}],
374
+ },
375
+ { # Prompt-completion
376
+ "prompt": [{"role": "user", "content": "What color is the sky?"}],
377
+ "completion": [{"role": "assistant", "content": "It is blue."}],
378
+ },
379
+ { # Preference
380
+ "prompt": [{"role": "user", "content": "What color is the sky?"}],
381
+ "chosen": [{"role": "assistant", "content": "It is blue."}],
382
+ "rejected": [{"role": "assistant", "content": "It is green."}],
383
+ },
384
+ { # Preference with implicit prompt
385
+ "chosen": [
386
+ {"role": "user", "content": "What color is the sky?"},
387
+ {"role": "assistant", "content": "It is blue."},
388
+ ],
389
+ "rejected": [
390
+ {"role": "user", "content": "What color is the sky?"},
391
+ {"role": "assistant", "content": "It is green."},
392
+ ],
393
+ },
394
+ { # Preference with tool calls
395
+ "prompt": [{"role": "user", "content": "What color is the sky?"}],
396
+ "chosen": [
397
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_color", "arguments": {"what": "sky"}}}]},
398
+ {"role": "tool", "name": "get_color", "content": "blue"},
399
+ {"role": "assistant", "content": "It is blue."},
400
+ ],
401
+ "rejected": [
402
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_color", "arguments": {"what": "tree"}}}]},
403
+ {"role": "tool", "name": "get_color", "content": "green"},
404
+ {"role": "assistant", "content": "It is green."},
405
+ ],
406
+ "tools": [
407
+ {
408
+ "type": "function",
409
+ "function": {
410
+ "description": "Gets the color.",
411
+ "name": "get_color",
412
+ "parameters": {"properties": {"what": {"description": "What to get the color of.", "type": "string"}}, "required": ["what"], "type": "object"},
413
+ "return": {"description": "The color.", "type": "string"},
414
+ },
415
+ },
416
+ ],
417
+ },
418
+ { # Unpaired preference
419
+ "prompt": [{"role": "user", "content": "What color is the sky?"}],
420
+ "completion": [{"role": "assistant", "content": "It is blue."}],
421
+ "label": True,
422
+ },
423
+ { # Language modeling with harmony
424
+ "messages": [
425
+ {"role": "system", "content": "Respond in a friendly manner."},
426
+ {"role": "user", "content": "What color is the sky?"},
427
+ {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."},
428
+ ],
429
+ },
430
+ { # Prompt-only with harmony
431
+ "prompt": [
432
+ {"role": "system", "content": "Respond in a friendly manner."},
433
+ {"role": "user", "content": "What color is the sky?"},
434
+ ],
435
+ },
436
+ { # Prompt-completion with harmony
437
+ "prompt": [
438
+ {"role": "system", "content": "Respond in a friendly manner."},
439
+ {"role": "user", "content": "What color is the sky?"},
440
+ ],
441
+ "completion": [
442
+ {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."},
443
+ ],
444
+ },
445
+ { # Preference with harmony
446
+ "prompt": [
447
+ {"role": "system", "content": "Respond in a friendly manner."},
448
+ {"role": "user", "content": "What color is the sky?"},
449
+ ],
450
+ "chosen": [
451
+ {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."},
452
+ ],
453
+ "rejected": [
454
+ {"role": "assistant", "thinking": "The user asks the color of the tree...", "content": "It is green."},
455
+ ],
456
+ },
457
+ { # Preference with implicit prompt and harmony
458
+ "chosen": [
459
+ {"role": "system", "content": "Respond in a friendly manner."},
460
+ {"role": "user", "content": "What color is the sky?"},
461
+ {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."},
462
+ ],
463
+ "rejected": [
464
+ {"role": "system", "content": "Respond in a friendly manner."},
465
+ {"role": "user", "content": "What color is the sky?"},
466
+ {"role": "assistant", "thinking": "The user asks the color of the tree...", "content": "It is green."},
467
+ ],
468
+ },
469
+ { # Unpaired preference with harmony
470
+ "prompt": [
471
+ {"role": "system", "content": "Respond in a friendly manner."},
472
+ {"role": "user", "content": "What color is the sky?"},
473
+ ],
474
+ "completion": [
475
+ {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."},
476
+ ],
477
+ "label": True,
478
+ },
479
+ ]
480
+ # fmt: on
481
+
482
+ non_conversational_examples = [
483
+ {"prompt": "The sky is", "completion": " blue."},
484
+ {"text": "The sky is blue."},
485
+ {"prompt": "The sky is"},
486
+ {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."},
487
+ {"prompt": "The sky is", "completion": " blue.", "label": True},
488
+ ]
489
+
490
+ @pytest.mark.parametrize("example", conversational_examples)
491
+ def test_conversational(self, example):
492
+ assert is_conversational(example)
493
+
494
+ @pytest.mark.parametrize("example", non_conversational_examples)
495
+ def test_non_conversational(self, example):
496
+ assert not is_conversational(example)
497
+
498
+
499
+ class TestIsConversationalFromValue(TrlTestCase):
500
+ def test_positive_1(self):
501
+ example = {
502
+ "conversations": [
503
+ {"from": "user", "value": "What color is the sky?"},
504
+ {"from": "assistant", "value": "It is blue."},
505
+ ],
506
+ }
507
+ assert is_conversational_from_value(example)
508
+
509
+ def test_negative_1(self):
510
+ example = {
511
+ "messages": [
512
+ {"role": "user", "content": "What color is the sky?"},
513
+ {"role": "assistant", "content": "It is blue."},
514
+ ],
515
+ }
516
+ assert not is_conversational_from_value(example)
517
+
518
+ def test_negative_2(self):
519
+ example = {"text": "The sky is blue."}
520
+ assert not is_conversational_from_value(example)
521
+
522
+
523
+ class TestApplyChatTemplate(TrlTestCase):
524
+ tokenizers = [
525
+ "trl-internal-testing/tiny-CohereForCausalLM",
526
+ "trl-internal-testing/tiny-Cohere2ForCausalLM",
527
+ "trl-internal-testing/tiny-DeepseekV3ForCausalLM",
528
+ "trl-internal-testing/tiny-DeepseekV3ForCausalLM-0528",
529
+ "trl-internal-testing/tiny-FalconMambaForCausalLM",
530
+ "trl-internal-testing/tiny-Gemma2ForCausalLM",
531
+ "trl-internal-testing/tiny-GemmaForCausalLM",
532
+ "trl-internal-testing/tiny-GptOssForCausalLM",
533
+ pytest.param(
534
+ "trl-internal-testing/tiny-Glm4MoeForCausalLM",
535
+ marks=pytest.mark.skipif(
536
+ Version(transformers.__version__) < Version("5.0.0"),
537
+ reason="GLM4 tokenizer requires transformers>=5.0.0",
538
+ ),
539
+ ),
540
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.1",
541
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.2",
542
+ "trl-internal-testing/tiny-LlamaForCausalLM-3",
543
+ "trl-internal-testing/tiny-MistralForCausalLM-0.1",
544
+ "trl-internal-testing/tiny-MistralForCausalLM-0.2",
545
+ pytest.param(
546
+ "trl-internal-testing/tiny-NemotronHForCausalLM-nano",
547
+ marks=pytest.mark.skipif(
548
+ Version(transformers.__version__) < Version("5.3.0"),
549
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
550
+ ),
551
+ ),
552
+ pytest.param(
553
+ "trl-internal-testing/tiny-NemotronHForCausalLM-super",
554
+ marks=pytest.mark.skipif(
555
+ Version(transformers.__version__) < Version("5.3.0"),
556
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
557
+ ),
558
+ ),
559
+ pytest.param(
560
+ "trl-internal-testing/tiny-NemotronHForCausalLM-ultra",
561
+ marks=pytest.mark.skipif(
562
+ Version(transformers.__version__) < Version("5.3.0"),
563
+ reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
564
+ ),
565
+ ),
566
+ pytest.param(
567
+ "trl-internal-testing/tiny-Olmo3ForCausalLM",
568
+ marks=pytest.mark.skipif(
569
+ Version(transformers.__version__) < Version("4.57.0"),
570
+ reason="Olmo 3 requires transformers>=4.57.0",
571
+ ),
572
+ ),
573
+ "trl-internal-testing/tiny-Phi3ForCausalLM-3",
574
+ "trl-internal-testing/tiny-Phi3ForCausalLM-3.5",
575
+ "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
576
+ "trl-internal-testing/tiny-Qwen3ForCausalLM",
577
+ "trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507",
578
+ pytest.param(
579
+ "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink",
580
+ marks=pytest.mark.skipif(
581
+ Version(transformers.__version__) < Version("5.0.0"),
582
+ reason="Qwen3.5 tokenizer requires transformers>=5.0.0",
583
+ ),
584
+ ),
585
+ pytest.param(
586
+ "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6",
587
+ marks=pytest.mark.skipif(
588
+ Version(transformers.__version__) < Version("5.0.0"),
589
+ reason="Qwen3.5 tokenizer requires transformers>=5.0.0",
590
+ ),
591
+ ),
592
+ ]
593
+
594
+ conversational_examples = [
595
+ { # Language modeling
596
+ "messages": [
597
+ {"role": "user", "content": "What color is the sky?"},
598
+ {"role": "assistant", "content": "It is blue."},
599
+ ],
600
+ },
601
+ { # Prompt-only
602
+ "prompt": [{"role": "user", "content": "What color is the sky?"}],
603
+ },
604
+ { # Prompt-completion
605
+ "prompt": [{"role": "user", "content": "What color is the sky?"}],
606
+ "completion": [{"role": "assistant", "content": "It is blue."}],
607
+ },
608
+ { # Preference
609
+ "prompt": [{"role": "user", "content": "What color is the sky?"}],
610
+ "chosen": [{"role": "assistant", "content": "It is blue."}],
611
+ "rejected": [{"role": "assistant", "content": "It is green."}],
612
+ },
613
+ { # Preference with implicit prompt
614
+ "chosen": [
615
+ {"role": "user", "content": "What color is the sky?"},
616
+ {"role": "assistant", "content": "It is blue."},
617
+ ],
618
+ "rejected": [
619
+ {"role": "user", "content": "What color is the sky?"},
620
+ {"role": "assistant", "content": "It is green."},
621
+ ],
622
+ },
623
+ { # Unpaired preference
624
+ "prompt": [{"role": "user", "content": "What color is the sky?"}],
625
+ "completion": [{"role": "assistant", "content": "It is blue."}],
626
+ "label": True,
627
+ },
628
+ ]
629
+
630
+ non_conversational_examples = [
631
+ {"text": "The sky is blue."}, # Language modeling
632
+ {"prompt": "The sky is"}, # Prompt-only
633
+ {"prompt": "The sky is", "completion": " blue."}, # Prompt-completion
634
+ {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."}, # Preference
635
+ {"chosen": "The sky is blue.", "rejected": "The sky is green."}, # Preference with implicit prompt
636
+ {"prompt": "The sky is", "completion": " blue.", "label": True}, # Unpaired preference
637
+ ]
638
+
639
+ @pytest.mark.parametrize("example", conversational_examples)
640
+ @pytest.mark.parametrize("tokenizer_id", tokenizers)
641
+ def test_apply_chat_template(self, tokenizer_id, example):
642
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_id)
643
+ result = apply_chat_template(example, tokenizer)
644
+
645
+ # Checking if the result is a dictionary
646
+ assert isinstance(result, dict)
647
+
648
+ # The chat template should be applied to the following keys
649
+ for key in ["prompt", "chosen", "rejected", "completion"]:
650
+ if key in example:
651
+ assert key in result
652
+ assert isinstance(result[key], str)
653
+
654
+ # Exception for messages, the key is "text" once the chat template is applied
655
+ if "messages" in example:
656
+ assert "text" in result
657
+ assert isinstance(result["text"], str)
658
+
659
+ # The label should be kept
660
+ if "label" in example:
661
+ assert "label" in result
662
+ assert isinstance(result["label"], bool)
663
+ assert result["label"] == example["label"]
664
+
665
+ # both conversational and non-conversational examples
666
+ @pytest.mark.parametrize("example", conversational_examples + non_conversational_examples)
667
+ @pytest.mark.parametrize("tokenizer_id", tokenizers)
668
+ def test_maybe_apply_chat_template(self, tokenizer_id, example):
669
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_id)
670
+ result = maybe_apply_chat_template(example, tokenizer)
671
+
672
+ # Checking if the result is a dictionary
673
+ assert isinstance(result, dict)
674
+
675
+ # The chat template should be applied to the following keys
676
+ for key in ["prompt", "chosen", "rejected", "completion"]:
677
+ if key in example:
678
+ assert key in result
679
+ assert isinstance(result[key], str)
680
+
681
+ # Exception for messages, the key is "text" once the chat template is applied
682
+ if "messages" in example:
683
+ assert "text" in result
684
+ assert isinstance(result["text"], str)
685
+
686
+ # The label should be kept
687
+ if "label" in example:
688
+ assert "label" in result
689
+ assert isinstance(result["label"], bool)
690
+ assert result["label"] == example["label"]
691
+
692
+ def test_apply_chat_template_with_chat_template_kwargs(self):
693
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3ForCausalLM")
694
+
695
+ example = {
696
+ "prompt": [{"role": "user", "content": "What color is the sky?"}],
697
+ # with this tokenizer, when you pass enable_thinking=False, it will add "<think>\n\n</think>\n\n"
698
+ "chat_template_kwargs": {"enable_thinking": False},
699
+ }
700
+ result = apply_chat_template(example, tokenizer)
701
+
702
+ # docstyle-ignore
703
+ expected = textwrap.dedent("""\
704
+ <|im_start|>user
705
+ What color is the sky?<|im_end|>
706
+ <|im_start|>assistant
707
+ <think>
708
+
709
+ </think>
710
+
711
+ """)
712
+
713
+ assert result["prompt"] == expected
714
+
715
+ def test_apply_chat_template_with_tools(self):
716
+ tokenizer = AutoProcessor.from_pretrained("trl-internal-testing/tiny-LlamaForCausalLM-3.2")
717
+
718
+ # Define dummy test tools
719
+ def get_current_temperature(location: str):
720
+ """
721
+ Gets the temperature at a given location.
722
+
723
+ Args:
724
+ location: The location to get the temperature for
725
+ """
726
+ return 22.0
727
+
728
+ # Define test case
729
+ test_case = {
730
+ "prompt": [
731
+ {"content": "What's the temperature in London?", "role": "user"},
732
+ ]
733
+ }
734
+ # Test with tools
735
+ result_with_tools = apply_chat_template(test_case, tokenizer, tools=[get_current_temperature])
736
+
737
+ # Verify tools are included in the output
738
+ assert "get_current_temperature" in result_with_tools["prompt"]
739
+
740
+ # Test without tools
741
+ result_without_tools = apply_chat_template(test_case, tokenizer, tools=None)
742
+
743
+ # Verify tools are not included in the output
744
+ assert "get_current_temperature" not in result_without_tools["prompt"]
745
+
746
+
747
+ class TestApplyChatTemplateHarmony(TrlTestCase):
748
+ def test_language_modeling(self):
749
+ messages = {
750
+ "messages": [
751
+ {"role": "system", "content": "Respond in a friendly manner."},
752
+ {"role": "user", "content": "What color is the sky?"},
753
+ {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."},
754
+ ],
755
+ }
756
+ output = apply_chat_template(
757
+ messages,
758
+ processing_class=AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM"),
759
+ reasoning_effort="low",
760
+ model_identity="You are HuggingGPT.",
761
+ )
762
+
763
+ # docstyle-ignore
764
+ expected = textwrap.dedent(f"""\
765
+ <|start|>system<|message|>You are HuggingGPT.
766
+ Knowledge cutoff: 2024-06
767
+ Current date: {strftime("%Y-%m-%d")}
768
+
769
+ Reasoning: low
770
+
771
+ # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions
772
+
773
+ Respond in a friendly manner.
774
+
775
+ <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant<|channel|>analysis<|message|>The user asks the color of the sky...<|end|><|start|>assistant<|channel|>final<|message|>It is blue.<|return|>""")
776
+
777
+ assert output["text"] == expected
778
+
779
+ def test_prompt_only(self):
780
+ messages = {
781
+ "prompt": [
782
+ {"role": "system", "content": "Respond in a friendly manner."},
783
+ {"role": "user", "content": "What color is the sky?"},
784
+ ],
785
+ }
786
+ output = apply_chat_template(
787
+ messages,
788
+ processing_class=AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM"),
789
+ reasoning_effort="low",
790
+ model_identity="You are HuggingGPT.",
791
+ )
792
+
793
+ # docstyle-ignore
794
+ expected = textwrap.dedent(f"""\
795
+ <|start|>system<|message|>You are HuggingGPT.
796
+ Knowledge cutoff: 2024-06
797
+ Current date: {strftime("%Y-%m-%d")}
798
+
799
+ Reasoning: low
800
+
801
+ # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions
802
+
803
+ Respond in a friendly manner.
804
+
805
+ <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant""")
806
+
807
+ assert output["prompt"] == expected
808
+
809
+ def test_prompt_completion(self):
810
+ messages = {
811
+ "prompt": [
812
+ {"role": "system", "content": "Respond in a friendly manner."},
813
+ {"role": "user", "content": "What color is the sky?"},
814
+ ],
815
+ "completion": [
816
+ {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."},
817
+ ],
818
+ }
819
+ output = apply_chat_template(
820
+ messages,
821
+ processing_class=AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM"),
822
+ reasoning_effort="low",
823
+ model_identity="You are HuggingGPT.",
824
+ )
825
+
826
+ # docstyle-ignore
827
+ expected_prompt = textwrap.dedent(f"""\
828
+ <|start|>system<|message|>You are HuggingGPT.
829
+ Knowledge cutoff: 2024-06
830
+ Current date: {strftime("%Y-%m-%d")}
831
+
832
+ Reasoning: low
833
+
834
+ # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions
835
+
836
+ Respond in a friendly manner.
837
+
838
+ <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant""")
839
+ expected_completion = "<|channel|>analysis<|message|>The user asks the color of the sky...<|end|><|start|>assistant<|channel|>final<|message|>It is blue.<|return|>"
840
+
841
+ assert output["prompt"] == expected_prompt
842
+ assert output["completion"] == expected_completion
843
+
844
+ def test_preference(self):
845
+ messages = {
846
+ "prompt": [
847
+ {"role": "system", "content": "Respond in a friendly manner."},
848
+ {"role": "user", "content": "What color is the sky?"},
849
+ ],
850
+ "chosen": [
851
+ {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."},
852
+ ],
853
+ "rejected": [
854
+ {"role": "assistant", "thinking": "The user asks the color of the tree...", "content": "It is green."},
855
+ ],
856
+ }
857
+ output = apply_chat_template(
858
+ messages,
859
+ processing_class=AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM"),
860
+ reasoning_effort="low",
861
+ model_identity="You are HuggingGPT.",
862
+ )
863
+
864
+ # docstyle-ignore
865
+ expected_prompt = textwrap.dedent(f"""\
866
+ <|start|>system<|message|>You are HuggingGPT.
867
+ Knowledge cutoff: 2024-06
868
+ Current date: {strftime("%Y-%m-%d")}
869
+
870
+ Reasoning: low
871
+
872
+ # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions
873
+
874
+ Respond in a friendly manner.
875
+
876
+ <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant""")
877
+ expected_chosen = "<|channel|>analysis<|message|>The user asks the color of the sky...<|end|><|start|>assistant<|channel|>final<|message|>It is blue.<|return|>"
878
+ expected_rejected = "<|channel|>analysis<|message|>The user asks the color of the tree...<|end|><|start|>assistant<|channel|>final<|message|>It is green.<|return|>"
879
+
880
+ assert output["prompt"] == expected_prompt
881
+ assert output["chosen"] == expected_chosen
882
+ assert output["rejected"] == expected_rejected
883
+
884
+ def test_preference_with_implicit_prompt(self):
885
+ messages = {
886
+ "chosen": [
887
+ {"role": "system", "content": "Respond in a friendly manner."},
888
+ {"role": "user", "content": "What color is the sky?"},
889
+ {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."},
890
+ ],
891
+ "rejected": [
892
+ {"role": "system", "content": "Respond in a friendly manner."},
893
+ {"role": "user", "content": "What color is the sky?"},
894
+ {"role": "assistant", "thinking": "The user asks the color of the tree...", "content": "It is green."},
895
+ ],
896
+ }
897
+ output = apply_chat_template(
898
+ messages,
899
+ processing_class=AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM"),
900
+ reasoning_effort="low",
901
+ model_identity="You are HuggingGPT.",
902
+ )
903
+
904
+ # docstyle-ignore
905
+ expected_chosen = textwrap.dedent(f"""\
906
+ <|start|>system<|message|>You are HuggingGPT.
907
+ Knowledge cutoff: 2024-06
908
+ Current date: {strftime("%Y-%m-%d")}
909
+
910
+ Reasoning: low
911
+
912
+ # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions
913
+
914
+ Respond in a friendly manner.
915
+
916
+ <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant<|channel|>analysis<|message|>The user asks the color of the sky...<|end|><|start|>assistant<|channel|>final<|message|>It is blue.<|return|>""")
917
+
918
+ # docstyle-ignore
919
+ expected_rejected = textwrap.dedent(f"""\
920
+ <|start|>system<|message|>You are HuggingGPT.
921
+ Knowledge cutoff: 2024-06
922
+ Current date: {strftime("%Y-%m-%d")}
923
+
924
+ Reasoning: low
925
+
926
+ # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions
927
+
928
+ Respond in a friendly manner.
929
+
930
+ <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant<|channel|>analysis<|message|>The user asks the color of the tree...<|end|><|start|>assistant<|channel|>final<|message|>It is green.<|return|>""")
931
+
932
+ assert output["chosen"] == expected_chosen
933
+ assert output["rejected"] == expected_rejected
934
+
935
+ def test_unpaired_preference(self):
936
+ messages = {
937
+ "prompt": [
938
+ {"role": "system", "content": "Respond in a friendly manner."},
939
+ {"role": "user", "content": "What color is the sky?"},
940
+ ],
941
+ "completion": [
942
+ {"role": "assistant", "thinking": "The user asks the color of the sky...", "content": "It is blue."},
943
+ ],
944
+ "label": True,
945
+ }
946
+ output = apply_chat_template(
947
+ messages,
948
+ processing_class=AutoTokenizer.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM"),
949
+ reasoning_effort="low",
950
+ model_identity="You are HuggingGPT.",
951
+ )
952
+
953
+ # docstyle-ignore
954
+ expected_prompt = textwrap.dedent(f"""\
955
+ <|start|>system<|message|>You are HuggingGPT.
956
+ Knowledge cutoff: 2024-06
957
+ Current date: {strftime("%Y-%m-%d")}
958
+
959
+ Reasoning: low
960
+
961
+ # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions
962
+
963
+ Respond in a friendly manner.
964
+
965
+ <|end|><|start|>user<|message|>What color is the sky?<|end|><|start|>assistant""")
966
+ expected_completion = "<|channel|>analysis<|message|>The user asks the color of the sky...<|end|><|start|>assistant<|channel|>final<|message|>It is blue.<|return|>"
967
+
968
+ assert output["prompt"] == expected_prompt
969
+ assert output["completion"] == expected_completion
970
+ assert output["label"]
971
+
972
+
973
+ class TestUnpairPreferenceDataset(TrlTestCase):
974
+ paired_dataset = Dataset.from_dict(
975
+ {
976
+ "prompt": ["The sky is", "The sun is"],
977
+ "chosen": [" blue.", " in the sky."],
978
+ "rejected": [" green.", " in the sea."],
979
+ }
980
+ )
981
+
982
+ unpaired_dataset = Dataset.from_dict(
983
+ {
984
+ "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"],
985
+ "completion": [" blue.", " in the sky.", " green.", " in the sea."],
986
+ "label": [True, True, False, False],
987
+ }
988
+ )
989
+
990
+ def test_unpair_preference_dataset(self):
991
+ # Test that a paired dataset is correctly converted to unpaired
992
+ unpaired_dataset = unpair_preference_dataset(self.paired_dataset)
993
+ assert unpaired_dataset.to_dict() == self.unpaired_dataset.to_dict(), (
994
+ "The paired dataset should be converted to unpaired."
995
+ )
996
+
997
+ def test_unpair_preference_dataset_extra_columns(self):
998
+ # Test that extra columns are dropped (not causing a length mismatch error)
999
+ paired_dataset = Dataset.from_dict(
1000
+ {
1001
+ "prompt": ["The sky is", "The sun is"],
1002
+ "chosen": [" blue.", " in the sky."],
1003
+ "rejected": [" green.", " in the sea."],
1004
+ "extra": [1, 2],
1005
+ }
1006
+ )
1007
+ unpaired_dataset = unpair_preference_dataset(paired_dataset)
1008
+ assert unpaired_dataset.to_dict() == self.unpaired_dataset.to_dict()
1009
+
1010
+ def test_unpair_preference_dataset_iterable(self):
1011
+ # Test that an IterableDataset with extra columns is correctly unpaired
1012
+ paired_dataset = self.paired_dataset.to_iterable_dataset()
1013
+ unpaired_dataset = unpair_preference_dataset(paired_dataset)
1014
+ assert list(unpaired_dataset) == [
1015
+ dict(zip(self.unpaired_dataset.column_names, vals, strict=False))
1016
+ for vals in zip(*self.unpaired_dataset.to_dict().values(), strict=False)
1017
+ ]
1018
+
1019
+ def test_unpair_preference_dataset_iterable_extra_columns(self):
1020
+ # Test that an IterableDataset with extra columns drops them without error
1021
+ paired_iterable = Dataset.from_dict(
1022
+ {
1023
+ "prompt": ["The sky is", "The sun is"],
1024
+ "chosen": [" blue.", " in the sky."],
1025
+ "rejected": [" green.", " in the sea."],
1026
+ "extra": [1, 2],
1027
+ }
1028
+ ).to_iterable_dataset()
1029
+ unpaired_dataset = unpair_preference_dataset(paired_iterable)
1030
+ assert list(unpaired_dataset) == [
1031
+ dict(zip(self.unpaired_dataset.column_names, vals, strict=False))
1032
+ for vals in zip(*self.unpaired_dataset.to_dict().values(), strict=False)
1033
+ ]
1034
+
1035
+ def test_unpair_preference_dataset_dict(self):
1036
+ # Test that a paired dataset dict is correctly converted to unpaired
1037
+ paired_dataset_dict = DatasetDict({"abc": self.paired_dataset})
1038
+ unpaired_dataset_dict = unpair_preference_dataset(paired_dataset_dict)
1039
+ assert unpaired_dataset_dict["abc"].to_dict() == self.unpaired_dataset.to_dict(), (
1040
+ "The paired dataset should be converted to unpaired."
1041
+ )
1042
+
1043
+ def test_maybe_unpair_preference_dataset(self):
1044
+ # Test that a paired dataset is correctly converted to unpaired with maybe_unpair_preference_dataset
1045
+ unpaired_dataset = maybe_unpair_preference_dataset(self.paired_dataset)
1046
+ assert unpaired_dataset.to_dict() == self.unpaired_dataset.to_dict(), (
1047
+ "The paired dataset should be converted to unpaired."
1048
+ )
1049
+
1050
+ def test_maybe_unpair_preference_dataset_dict(self):
1051
+ # Test that a paired dataset dict is correctly converted to unpaired with maybe_unpair_preference_dataset
1052
+ paired_dataset_dict = DatasetDict({"abc": self.paired_dataset})
1053
+ unpaired_dataset_dict = maybe_unpair_preference_dataset(paired_dataset_dict)
1054
+ assert unpaired_dataset_dict["abc"].to_dict() == self.unpaired_dataset.to_dict(), (
1055
+ "The paired dataset should be converted to unpaired."
1056
+ )
1057
+
1058
+ def test_maybe_unpair_preference_dataset_already_paired(self):
1059
+ # Test that a paired dataset remains unchanged with maybe_unpair_preference_dataset
1060
+ unpaired_dataset = maybe_unpair_preference_dataset(self.unpaired_dataset)
1061
+ assert unpaired_dataset.to_dict() == self.unpaired_dataset.to_dict(), (
1062
+ "The unpaired dataset should remain unchanged."
1063
+ )
1064
+
1065
+ def test_maybe_unpair_preference_dataset_dict_already_paired(self):
1066
+ # Test that a paired dataset dict remains unchanged with maybe_unpair_preference_dataset
1067
+ unpaired_dataset_dict = maybe_unpair_preference_dataset(DatasetDict({"abc": self.unpaired_dataset}))
1068
+ assert unpaired_dataset_dict["abc"].to_dict() == self.unpaired_dataset.to_dict(), (
1069
+ "The unpaired dataset should remain unchanged."
1070
+ )
1071
+
1072
+
1073
+ class TestExtractPrompt(TrlTestCase):
1074
+ example_implicit_prompt_conversational = {
1075
+ "chosen": [
1076
+ {"role": "user", "content": "What color is the sky?"},
1077
+ {"role": "assistant", "content": "It is blue."},
1078
+ ],
1079
+ "rejected": [
1080
+ {"role": "user", "content": "What color is the sky?"},
1081
+ {"role": "assistant", "content": "It is green."},
1082
+ ],
1083
+ }
1084
+
1085
+ example_explicit_prompt_conversational = {
1086
+ "prompt": [
1087
+ {"role": "user", "content": "What color is the sky?"},
1088
+ ],
1089
+ "chosen": [
1090
+ {"role": "assistant", "content": "It is blue."},
1091
+ ],
1092
+ "rejected": [
1093
+ {"role": "assistant", "content": "It is green."},
1094
+ ],
1095
+ }
1096
+
1097
+ example_implicit_prompt_standard = {
1098
+ "chosen": "The sky is blue.",
1099
+ "rejected": "The sky is green.",
1100
+ }
1101
+
1102
+ example_explicit_prompt_standard = {
1103
+ "prompt": "The sky is",
1104
+ "chosen": " blue.",
1105
+ "rejected": " green.",
1106
+ }
1107
+
1108
+ def test_extract_prompt_conversational(self):
1109
+ # Test that the prompt is correctly extracted from the dataset
1110
+ example_extracted_prompt = extract_prompt(self.example_implicit_prompt_conversational)
1111
+ assert example_extracted_prompt == self.example_explicit_prompt_conversational, (
1112
+ "The prompt is not correctly extracted from the dataset."
1113
+ )
1114
+
1115
+ def test_maybe_extract_prompt_conversational(self):
1116
+ # Test that the prompt is correctly extracted from the dataset with maybe_extract_prompt
1117
+ example_extracted_prompt = maybe_extract_prompt(self.example_implicit_prompt_conversational)
1118
+ assert example_extracted_prompt == self.example_explicit_prompt_conversational, (
1119
+ "The prompt is not correctly extracted from the dataset."
1120
+ )
1121
+
1122
+ def test_maybe_extract_prompt_conversational_already_explicit(self):
1123
+ # Test that the prompt remains unchanged with maybe_extract_prompt
1124
+ example_extracted_prompt = maybe_extract_prompt(self.example_explicit_prompt_conversational)
1125
+ assert example_extracted_prompt == self.example_explicit_prompt_conversational, (
1126
+ "The prompt should remain unchanged."
1127
+ )
1128
+
1129
+ def test_extract_prompt_standard(self):
1130
+ # Test that the prompt is correctly extracted from the dataset
1131
+ example_extracted_prompt = extract_prompt(self.example_implicit_prompt_standard)
1132
+ assert example_extracted_prompt == self.example_explicit_prompt_standard, (
1133
+ "The prompt is not correctly extracted from the dataset."
1134
+ )
1135
+
1136
+ def test_maybe_extract_prompt_standard(self):
1137
+ # Test that the prompt is correctly extracted from the dataset with maybe_extract_prompt
1138
+ example_extracted_prompt = maybe_extract_prompt(self.example_implicit_prompt_standard)
1139
+ assert example_extracted_prompt == self.example_explicit_prompt_standard, (
1140
+ "The prompt is not correctly extracted from the dataset."
1141
+ )
1142
+
1143
+ def test_maybe_extract_prompt_standard_already_explicit(self):
1144
+ # Test that the prompt remains unchanged with maybe_extract_prompt
1145
+ example_extracted_prompt = maybe_extract_prompt(self.example_explicit_prompt_standard)
1146
+ assert example_extracted_prompt == self.example_explicit_prompt_standard, "The prompt should remain unchanged."
1147
+
1148
+
1149
+ class TestPackDatasetWrapped(TrlTestCase):
1150
+ def test_with_dataset(self):
1151
+ examples = {
1152
+ "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]],
1153
+ "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]],
1154
+ }
1155
+ dataset = Dataset.from_dict(examples)
1156
+ dataset = dataset.with_format("numpy", dtype="float32")
1157
+ format = dataset.format
1158
+ seq_length = 3
1159
+ expected_output = {
1160
+ "input_ids": [[1, 2, 3], [4, 5, 6], [7, 8]],
1161
+ "attention_mask": [[0, 1, 1], [0, 0, 1], [1, 1]],
1162
+ }
1163
+ dataset = pack_dataset(dataset, seq_length, strategy="wrapped")
1164
+ assert dataset.to_dict() == expected_output
1165
+ assert format == dataset.format
1166
+
1167
+ def test_with_iterable_dataset(self):
1168
+ examples = {
1169
+ "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]],
1170
+ "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]],
1171
+ }
1172
+ dataset = Dataset.from_dict(examples).to_iterable_dataset()
1173
+ dataset = dataset.with_format("numpy")
1174
+ formatting = dataset._formatting
1175
+ seq_length = 3
1176
+ expected_output = {
1177
+ "input_ids": [[1, 2, 3], [4, 5, 6], [7, 8]],
1178
+ "attention_mask": [[0, 1, 1], [0, 0, 1], [1, 1]],
1179
+ }
1180
+ dataset = pack_dataset(dataset, seq_length, strategy="wrapped")
1181
+ num_examples = len(examples[next(iter(examples))])
1182
+ assert next(iter(dataset.with_format(None).batch(batch_size=num_examples))) == expected_output
1183
+ assert formatting == dataset._formatting
1184
+
1185
+
1186
+ class TestPackDatasetBfd(TrlTestCase):
1187
+ def test_with_dataset(self):
1188
+ examples = {
1189
+ "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]],
1190
+ }
1191
+ dataset = Dataset.from_dict(examples)
1192
+ dataset = dataset.with_format("numpy", dtype="float32")
1193
+ format = dataset.format
1194
+ seq_length = 4
1195
+ expected_output = {
1196
+ "input_ids": [[4, 5, 6, 7], [1, 2, 3, 8]],
1197
+ "seq_lengths": [[4], [3, 1]],
1198
+ }
1199
+ dataset = pack_dataset(dataset, seq_length, strategy="bfd")
1200
+ expected_format = dataset.format
1201
+ assert dataset.to_dict() == expected_output
1202
+ assert "seq_lengths" in expected_format["columns"]
1203
+ expected_format["columns"].remove("seq_lengths")
1204
+ assert format == dataset.format
1205
+
1206
+ def test_with_iterable_dataset(self):
1207
+ examples = {
1208
+ "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]],
1209
+ }
1210
+ dataset = Dataset.from_dict(examples).to_iterable_dataset()
1211
+ dataset = dataset.with_format("numpy")
1212
+ formatting = dataset._formatting
1213
+ seq_length = 4
1214
+ expected_output = {
1215
+ "input_ids": [[4, 5, 6, 7], [1, 2, 3, 8]],
1216
+ "seq_lengths": [[4], [3, 1]],
1217
+ }
1218
+ dataset = pack_dataset(dataset, seq_length, strategy="bfd")
1219
+ num_examples = len(examples[next(iter(examples))])
1220
+ assert next(iter(dataset.with_format(None).batch(batch_size=num_examples))) == expected_output
1221
+ assert formatting == dataset._formatting
1222
+
1223
+ def test_with_overlong_0(self):
1224
+ examples = {
1225
+ "input_ids": [[1, 2, 3, 4, 5], [6, 7], [8, 9, 10, 11], [12]],
1226
+ }
1227
+ dataset = Dataset.from_dict(examples)
1228
+ seq_length = 4
1229
+ expected_output = {
1230
+ "input_ids": [[1, 2, 3, 4], [8, 9, 10, 11], [6, 7, 5, 12]],
1231
+ "seq_lengths": [[4], [4], [2, 1, 1]],
1232
+ }
1233
+ dataset = pack_dataset(dataset, seq_length, strategy="bfd_split")
1234
+ assert dataset.to_dict() == expected_output
1235
+
1236
+ def test_with_overlong_two_coluns(self):
1237
+ examples = {
1238
+ "col1": [[1, -2, 3, -4, 5, -6], [7, -8, 9], [-10, 11, -12], [13, -14, 15, -16]],
1239
+ "col2": [[-1, 2, -3, 4, -5, 6], [-7, 8, -9], [10, -11, 12], [-13, 14, -15, 16]],
1240
+ }
1241
+ dataset = Dataset.from_dict(examples)
1242
+ seq_length = 4
1243
+ expected_output = {
1244
+ "col1": [[1, -2, 3, -4], [13, -14, 15, -16], [7, -8, 9], [-10, 11, -12], [5, -6]],
1245
+ "col2": [[-1, 2, -3, 4], [-13, 14, -15, 16], [-7, 8, -9], [10, -11, 12], [-5, 6]],
1246
+ "seq_lengths": [[4], [4], [3], [3], [2]],
1247
+ }
1248
+ dataset = pack_dataset(dataset, seq_length, strategy="bfd_split")
1249
+ assert dataset.to_dict() == expected_output
1250
+
1251
+ def test_with_non_power_of_2(self):
1252
+ examples = {
1253
+ "input_ids": [[1, 2, 3, 4, 5], [6], [7, 8, 9, 10], [11, 12, 13]],
1254
+ }
1255
+ dataset = Dataset.from_dict(examples)
1256
+ seq_length = 5
1257
+ expected_output = {
1258
+ "input_ids": [[1, 2, 3, 4, 5], [7, 8, 9, 10, 6], [11, 12, 13]],
1259
+ "seq_lengths": [[5], [4, 1], [3]],
1260
+ }
1261
+ dataset = pack_dataset(dataset, seq_length, strategy="bfd_split")
1262
+ assert dataset.to_dict() == expected_output
1263
+
1264
+ def test_default_no_split(self):
1265
+ """Test default 'bfd' strategy for SFT datasets (truncates overflow)."""
1266
+ examples = {
1267
+ "input_ids": [[1, 2, 3, 4, 5], [6, 7], [8, 9, 10, 11], [12]],
1268
+ }
1269
+ dataset = Dataset.from_dict(examples)
1270
+ seq_length = 4
1271
+ # With default 'bfd' strategy, overflow tokens are discarded
1272
+ expected_output = {
1273
+ "input_ids": [[1, 2, 3, 4], [8, 9, 10, 11], [6, 7, 12]],
1274
+ "seq_lengths": [[4], [4], [2, 1]],
1275
+ }
1276
+ dataset = pack_dataset(dataset, seq_length, strategy="bfd")
1277
+ assert dataset.to_dict() == expected_output
1278
+
1279
+ def test_with_empty_sequences(self):
1280
+ examples = {
1281
+ "input_ids": [[1, 2], [], [3, 4, 5], [], [6]],
1282
+ }
1283
+ dataset = Dataset.from_dict(examples)
1284
+ seq_length = 4
1285
+ expected_output = {
1286
+ "input_ids": [[3, 4, 5, 6], [1, 2]],
1287
+ "seq_lengths": [[3, 1], [2]],
1288
+ }
1289
+ dataset = pack_dataset(dataset, seq_length, strategy="bfd_split")
1290
+ assert dataset.to_dict() == expected_output
1291
+
1292
+
1293
+ class TestMaybeConvertToChatML(TrlTestCase):
1294
+ def test_with_conversations_key(self):
1295
+ # Particular case where the key is "conversations": we rename it to "messages"
1296
+ example = {
1297
+ "conversations": [
1298
+ {"from": "user", "value": "What color is the sky?"},
1299
+ {"from": "assistant", "value": "It is blue."},
1300
+ ]
1301
+ }
1302
+ expected_output = {
1303
+ "messages": [
1304
+ {"role": "user", "content": "What color is the sky?"},
1305
+ {"role": "assistant", "content": "It is blue."},
1306
+ ]
1307
+ }
1308
+ assert maybe_convert_to_chatml(example) == expected_output
1309
+
1310
+ def test_without_conversations_key(self):
1311
+ # Same as before, but we don't rename the keys
1312
+ example = {
1313
+ "prompt": [{"from": "user", "value": "What color is the sky?"}],
1314
+ "completion": [{"from": "assistant", "value": "It is blue."}],
1315
+ }
1316
+ expected_output = {
1317
+ "prompt": [{"role": "user", "content": "What color is the sky?"}],
1318
+ "completion": [{"role": "assistant", "content": "It is blue."}],
1319
+ }
1320
+ assert maybe_convert_to_chatml(example) == expected_output
1321
+
1322
+ def test_not_conversional(self):
1323
+ # When not needed, the example should remain unchanged
1324
+ example = {"text": "The sky is blue."}
1325
+ assert maybe_convert_to_chatml(example) == example
1326
+
1327
+ def test_already_chatml(self):
1328
+ # When the example is already in ChatML format, it should remain unchanged
1329
+ example = {
1330
+ "messages": [
1331
+ {"role": "user", "content": "What color is the sky?"},
1332
+ {"role": "assistant", "content": "It is blue."},
1333
+ ]
1334
+ }
1335
+ assert maybe_convert_to_chatml(example) == example
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_dpo_trainer.py ADDED
@@ -0,0 +1,1286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 pytest
16
+ import torch
17
+ import transformers
18
+ from datasets import load_dataset
19
+ from packaging.version import Version
20
+ from packaging.version import parse as parse_version
21
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
22
+ from transformers.testing_utils import torch_device
23
+ from transformers.utils import is_peft_available
24
+
25
+ from trl import DPOConfig, DPOTrainer
26
+ from trl.trainer.dpo_trainer import DataCollatorForPreference, DataCollatorForVisionPreference
27
+
28
+ from .testing_utils import (
29
+ TrlTestCase,
30
+ is_ampere_or_newer,
31
+ require_bitsandbytes,
32
+ require_kernels,
33
+ require_liger_kernel,
34
+ require_peft,
35
+ require_vision,
36
+ )
37
+
38
+
39
+ if is_peft_available():
40
+ from peft import LoraConfig, get_peft_model
41
+
42
+
43
+ class TestDataCollatorForPreference(TrlTestCase):
44
+ def test_padding_and_masks(self):
45
+ collator = DataCollatorForPreference(pad_token_id=0)
46
+ examples = [
47
+ {"prompt_ids": [1, 2, 3], "chosen_ids": [4, 5], "rejected_ids": [6]},
48
+ {"prompt_ids": [7, 8], "chosen_ids": [9, 10], "rejected_ids": [11, 12, 13]},
49
+ ]
50
+ result = collator(examples)
51
+
52
+ expected_input_ids = torch.tensor(
53
+ [
54
+ [1, 2, 3, 4, 5], # prompt + chosen (example 1)
55
+ [7, 8, 9, 10, 0], # prompt + chosen (example 2, padded)
56
+ [1, 2, 3, 6, 0], # prompt + rejected (example 1, padded)
57
+ [7, 8, 11, 12, 13], # prompt + rejected (example 2)
58
+ ]
59
+ )
60
+ expected_attention_mask = torch.tensor(
61
+ [
62
+ [1, 1, 1, 1, 1],
63
+ [1, 1, 1, 1, 0],
64
+ [1, 1, 1, 1, 0],
65
+ [1, 1, 1, 1, 1],
66
+ ]
67
+ )
68
+ expected_completion_mask = torch.tensor(
69
+ [
70
+ [0, 0, 0, 1, 1], # chosen completion (example 1)
71
+ [0, 0, 1, 1, 0], # chosen completion (example 2, padded)
72
+ [0, 0, 0, 1, 0], # rejected completion (example 1, padded)
73
+ [0, 0, 1, 1, 1], # rejected completion (example 2)
74
+ ]
75
+ )
76
+
77
+ assert set(result.keys()) == {"input_ids", "attention_mask", "completion_mask"}
78
+ torch.testing.assert_close(result["input_ids"], expected_input_ids)
79
+ torch.testing.assert_close(result["attention_mask"], expected_attention_mask)
80
+ torch.testing.assert_close(result["completion_mask"], expected_completion_mask)
81
+
82
+ def test_optional_reference_logps(self):
83
+ collator = DataCollatorForPreference(pad_token_id=0)
84
+ examples = [
85
+ {
86
+ "prompt_ids": [1, 2],
87
+ "chosen_ids": [3],
88
+ "rejected_ids": [4],
89
+ "ref_chosen_logps": 0.1,
90
+ "ref_rejected_logps": 0.2,
91
+ },
92
+ {
93
+ "prompt_ids": [5],
94
+ "chosen_ids": [6, 7],
95
+ "rejected_ids": [8, 9],
96
+ "ref_chosen_logps": 0.3,
97
+ "ref_rejected_logps": 0.4,
98
+ },
99
+ ]
100
+ result = collator(examples)
101
+
102
+ expected_ref_chosen_logps = torch.tensor([0.1, 0.3])
103
+ expected_ref_rejected_logps = torch.tensor([0.2, 0.4])
104
+
105
+ assert set(result.keys()) == {
106
+ "input_ids",
107
+ "attention_mask",
108
+ "completion_mask",
109
+ "ref_chosen_logps",
110
+ "ref_rejected_logps",
111
+ }
112
+ torch.testing.assert_close(result["ref_chosen_logps"], expected_ref_chosen_logps)
113
+ torch.testing.assert_close(result["ref_rejected_logps"], expected_ref_rejected_logps)
114
+
115
+ def test_with_pad_to_multiple_of(self):
116
+ collator = DataCollatorForPreference(pad_token_id=0, pad_to_multiple_of=5)
117
+ examples = [
118
+ {"prompt_ids": [1], "chosen_ids": [2], "rejected_ids": [3]},
119
+ {"prompt_ids": [4, 5], "chosen_ids": [6, 7], "rejected_ids": [8, 9]},
120
+ ]
121
+ result = collator(examples)
122
+
123
+ expected_input_ids = torch.tensor(
124
+ [
125
+ [1, 2, 0, 0, 0], # prompt + chosen (example 1, padded to multiple of 5)
126
+ [4, 5, 6, 7, 0], # prompt + chosen (example 2)
127
+ [1, 3, 0, 0, 0], # prompt + rejected (example 1, padded to multiple of 5)
128
+ [4, 5, 8, 9, 0], # prompt + rejected (example 2)
129
+ ]
130
+ )
131
+
132
+ assert set(result.keys()) == {"input_ids", "attention_mask", "completion_mask"}
133
+ torch.testing.assert_close(result["input_ids"], expected_input_ids)
134
+
135
+
136
+ class TestDataCollatorForVisionPreference(TrlTestCase):
137
+ @pytest.mark.skipif(
138
+ Version(transformers.__version__) < Version("5.3.0"),
139
+ reason="mm_token_type_ids are returned by default since transformers-5.3.0 (see transformers#43972)",
140
+ )
141
+ @require_vision
142
+ def test_mm_token_type_ids_shape(self):
143
+ # Regression test: when the processor returns mm_token_type_ids (e.g. Qwen2.5-VL after
144
+ # transformers#43972), the collator must concatenate it with zeros for the completion part
145
+ # so that its shape matches input_ids. Without the fix this raises an IndexError in the model.
146
+ from PIL import Image
147
+ from transformers import AutoProcessor
148
+
149
+ processor = AutoProcessor.from_pretrained("trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration")
150
+ collator = DataCollatorForVisionPreference(processor)
151
+ image = Image.new("RGB", (16, 16))
152
+ examples = [
153
+ {
154
+ "images": [image],
155
+ "prompt": [{"role": "user", "content": "What is this?"}],
156
+ "chosen": [{"role": "assistant", "content": "A red square."}],
157
+ "rejected": [{"role": "assistant", "content": "A blue circle."}],
158
+ }
159
+ ]
160
+ output = collator(examples)
161
+ assert "mm_token_type_ids" in output
162
+ assert output["mm_token_type_ids"].shape == output["input_ids"].shape, (
163
+ f"mm_token_type_ids shape {output['mm_token_type_ids'].shape} != "
164
+ f"input_ids shape {output['input_ids'].shape}"
165
+ )
166
+
167
+
168
+ class TestDPOTrainer(TrlTestCase):
169
+ @pytest.mark.parametrize(
170
+ "model_id",
171
+ [
172
+ "trl-internal-testing/tiny-Cohere2ForCausalLM",
173
+ pytest.param(
174
+ "trl-internal-testing/tiny-Glm4MoeForCausalLM",
175
+ marks=pytest.mark.skipif(
176
+ Version(transformers.__version__) < Version("5.0.0"),
177
+ reason="GLM4 tokenizer requires transformers>=5.0.0",
178
+ ),
179
+ ),
180
+ "trl-internal-testing/tiny-GptOssForCausalLM",
181
+ "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
182
+ "trl-internal-testing/tiny-Qwen3MoeForCausalLM",
183
+ pytest.param(
184
+ "trl-internal-testing/tiny-NemotronHForCausalLM-nano",
185
+ marks=pytest.mark.skipif(
186
+ Version(transformers.__version__) < Version("5.7.0"),
187
+ reason="Nemotron 3 gradient checkpointing requires transformers>=5.7.0 (see transformers#45625)",
188
+ ),
189
+ ),
190
+ pytest.param(
191
+ "trl-internal-testing/tiny-Olmo3ForCausalLM",
192
+ marks=pytest.mark.skipif(
193
+ Version(transformers.__version__) < Version("4.57.0"),
194
+ reason="Olmo 3 requires transformers>=4.57.0",
195
+ ),
196
+ ),
197
+ ],
198
+ )
199
+ def test_train(self, model_id):
200
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
201
+
202
+ training_args = DPOConfig(
203
+ output_dir=self.tmp_dir,
204
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
205
+ report_to="none",
206
+ )
207
+ trainer = DPOTrainer(model=model_id, args=training_args, train_dataset=dataset)
208
+
209
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
210
+
211
+ trainer.train()
212
+
213
+ assert trainer.state.log_history[-1]["train_loss"] is not None
214
+
215
+ # Check that the params have changed
216
+ for n, param in previous_trainable_params.items():
217
+ new_param = trainer.model.get_parameter(n)
218
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
219
+
220
+ @pytest.mark.parametrize(
221
+ "config_name",
222
+ [
223
+ "standard_preference",
224
+ "conversational_preference",
225
+ "standard_implicit_prompt_preference",
226
+ "conversational_implicit_prompt_preference",
227
+ ],
228
+ )
229
+ def test_train_dataset_format(self, config_name):
230
+ dataset = load_dataset("trl-internal-testing/zen", config_name, split="train")
231
+
232
+ training_args = DPOConfig(
233
+ output_dir=self.tmp_dir,
234
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
235
+ report_to="none",
236
+ )
237
+ trainer = DPOTrainer(
238
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
239
+ )
240
+
241
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
242
+
243
+ trainer.train()
244
+
245
+ assert trainer.state.log_history[-1]["train_loss"] is not None
246
+
247
+ # Check that the params have changed
248
+ for n, param in previous_trainable_params.items():
249
+ new_param = trainer.model.get_parameter(n)
250
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
251
+
252
+ # Special case for harmony
253
+ def test_train_gpt_oss(self):
254
+ dataset = load_dataset("trl-internal-testing/harmony", "preference", split="train")
255
+
256
+ training_args = DPOConfig(
257
+ output_dir=self.tmp_dir,
258
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
259
+ report_to="none",
260
+ )
261
+ trainer = DPOTrainer(
262
+ model="trl-internal-testing/tiny-GptOssForCausalLM", args=training_args, train_dataset=dataset
263
+ )
264
+
265
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
266
+
267
+ trainer.train()
268
+
269
+ assert trainer.state.log_history[-1]["train_loss"] is not None
270
+
271
+ # Check that the params have changed
272
+ for n, param in previous_trainable_params.items():
273
+ new_param = trainer.model.get_parameter(n)
274
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
275
+
276
+ def test_train_model(self):
277
+ model = AutoModelForCausalLM.from_pretrained(
278
+ "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
279
+ dtype="float32",
280
+ )
281
+
282
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
283
+
284
+ training_args = DPOConfig(
285
+ output_dir=self.tmp_dir,
286
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
287
+ report_to="none",
288
+ )
289
+ trainer = DPOTrainer(model=model, args=training_args, train_dataset=dataset)
290
+
291
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
292
+
293
+ trainer.train()
294
+
295
+ assert trainer.state.log_history[-1]["train_loss"] is not None
296
+
297
+ # Check that the params have changed
298
+ for n, param in previous_trainable_params.items():
299
+ new_param = trainer.model.get_parameter(n)
300
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
301
+
302
+ @pytest.mark.parametrize(
303
+ "loss_type",
304
+ [
305
+ "sigmoid",
306
+ "hinge",
307
+ "ipo",
308
+ "exo_pair",
309
+ "nca_pair",
310
+ "robust",
311
+ "bco_pair",
312
+ "sppo_hard",
313
+ "aot",
314
+ "aot_unpaired",
315
+ "apo_zero",
316
+ "apo_down",
317
+ "discopop",
318
+ "sft",
319
+ "sigmoid_norm",
320
+ ],
321
+ )
322
+ def test_train_loss_types(self, loss_type):
323
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference")
324
+
325
+ training_args = DPOConfig(
326
+ output_dir=self.tmp_dir,
327
+ loss_type=loss_type,
328
+ label_smoothing=1e-3 if loss_type == "exo_pair" else 0.0,
329
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
330
+ report_to="none",
331
+ eval_strategy="steps",
332
+ eval_steps=3,
333
+ )
334
+ trainer = DPOTrainer(
335
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
336
+ args=training_args,
337
+ train_dataset=dataset["train"],
338
+ eval_dataset=dataset["test"],
339
+ )
340
+
341
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
342
+
343
+ trainer.train()
344
+
345
+ assert trainer.state.log_history[-1]["train_loss"] is not None
346
+
347
+ # Check that the params have changed
348
+ for n, param in previous_trainable_params.items():
349
+ new_param = trainer.model.get_parameter(n)
350
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
351
+
352
+ def test_train_multi_loss_types(self):
353
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
354
+
355
+ training_args = DPOConfig(
356
+ output_dir=self.tmp_dir,
357
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
358
+ loss_type=["sigmoid", "bco_pair", "sft"], # this specific combination is used in MPO
359
+ report_to="none",
360
+ )
361
+ trainer = DPOTrainer(
362
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
363
+ args=training_args,
364
+ train_dataset=dataset,
365
+ )
366
+
367
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
368
+
369
+ trainer.train()
370
+
371
+ assert trainer.state.log_history[-1]["train_loss"] is not None
372
+
373
+ # Check that the params have changed
374
+ for n, param in previous_trainable_params.items():
375
+ new_param = trainer.model.get_parameter(n)
376
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
377
+
378
+ def test_train_with_wpo(self):
379
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
380
+
381
+ training_args = DPOConfig(
382
+ output_dir=self.tmp_dir,
383
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
384
+ report_to="none",
385
+ use_weighting=True,
386
+ )
387
+ trainer = DPOTrainer(
388
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
389
+ args=training_args,
390
+ train_dataset=dataset,
391
+ )
392
+
393
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
394
+
395
+ trainer.train()
396
+
397
+ assert trainer.state.log_history[-1]["train_loss"] is not None
398
+
399
+ # Check that the params have changed
400
+ for n, param in previous_trainable_params.items():
401
+ new_param = trainer.model.get_parameter(n)
402
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
403
+
404
+ def test_train_with_ld(self):
405
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
406
+
407
+ training_args = DPOConfig(
408
+ output_dir=self.tmp_dir,
409
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
410
+ report_to="none",
411
+ ld_alpha=0.5,
412
+ )
413
+ trainer = DPOTrainer(
414
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
415
+ args=training_args,
416
+ train_dataset=dataset,
417
+ )
418
+
419
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
420
+
421
+ trainer.train()
422
+
423
+ assert trainer.state.log_history[-1]["train_loss"] is not None
424
+
425
+ # Check that the params have changed
426
+ for n, param in previous_trainable_params.items():
427
+ new_param = trainer.model.get_parameter(n)
428
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
429
+
430
+ @pytest.mark.parametrize(
431
+ "f_divergence_type",
432
+ ["reverse_kl", "forward_kl", "js_divergence", "alpha_divergence"],
433
+ )
434
+ def test_train_with_f_divergence(self, f_divergence_type):
435
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
436
+
437
+ training_args = DPOConfig(
438
+ output_dir=self.tmp_dir,
439
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
440
+ report_to="none",
441
+ f_divergence_type=f_divergence_type,
442
+ )
443
+ trainer = DPOTrainer(
444
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
445
+ args=training_args,
446
+ train_dataset=dataset,
447
+ )
448
+
449
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
450
+
451
+ trainer.train()
452
+
453
+ assert trainer.state.log_history[-1]["train_loss"] is not None
454
+
455
+ # Check that the params have changed
456
+ for n, param in previous_trainable_params.items():
457
+ new_param = trainer.model.get_parameter(n)
458
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
459
+
460
+ def test_train_with_explicit_ref_model(self):
461
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
462
+
463
+ training_args = DPOConfig(
464
+ output_dir=self.tmp_dir,
465
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
466
+ report_to="none",
467
+ )
468
+ # When specifying a ref model, it's usually because we want it to be a different checkpoint, but for testing
469
+ # purposes we will just just use the same checkpoint
470
+ ref_model = AutoModelForCausalLM.from_pretrained(
471
+ "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32"
472
+ )
473
+ trainer = DPOTrainer(
474
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
475
+ ref_model=ref_model,
476
+ args=training_args,
477
+ train_dataset=dataset,
478
+ )
479
+
480
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
481
+
482
+ trainer.train()
483
+
484
+ assert trainer.state.log_history[-1]["train_loss"] is not None
485
+
486
+ # Check that the params have changed
487
+ for n, param in previous_trainable_params.items():
488
+ new_param = trainer.model.get_parameter(n)
489
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
490
+ new_ref_param = trainer.ref_model.get_parameter(n)
491
+ torch.testing.assert_close(param, new_ref_param, msg=f"Reference model parameter {n} has changed.")
492
+
493
+ def test_train_with_sync_ref_model(self):
494
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
495
+
496
+ training_args = DPOConfig(
497
+ output_dir=self.tmp_dir,
498
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
499
+ sync_ref_model=True,
500
+ ref_model_sync_steps=2, # reduce sync steps to ensure a sync happens
501
+ report_to="none",
502
+ )
503
+ trainer = DPOTrainer(
504
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
505
+ )
506
+
507
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
508
+ assert trainer.ref_model is not None
509
+ previous_ref_params = {n: param.clone() for n, param in trainer.ref_model.named_parameters()}
510
+
511
+ trainer.train()
512
+
513
+ assert trainer.state.log_history[-1]["train_loss"] is not None
514
+
515
+ # Check that the params have changed
516
+ for n, param in previous_trainable_params.items():
517
+ new_param = trainer.model.get_parameter(n)
518
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
519
+ new_ref_param = trainer.ref_model.get_parameter(n)
520
+ assert not torch.equal(previous_ref_params[n], new_ref_param), f"Ref Parameter {n} has not changed."
521
+
522
+ def test_train_model_dtype(self):
523
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
524
+
525
+ training_args = DPOConfig(
526
+ output_dir=self.tmp_dir,
527
+ model_init_kwargs={"dtype": torch.float16},
528
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
529
+ report_to="none",
530
+ )
531
+ trainer = DPOTrainer(
532
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
533
+ )
534
+
535
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
536
+
537
+ trainer.train()
538
+
539
+ assert trainer.state.log_history[-1]["train_loss"] is not None
540
+
541
+ # Check that the params have changed
542
+ for n, param in previous_trainable_params.items():
543
+ # For some reasonn model.layers.0.input_layernorm.weight doesn't change in GitHub Actions but does
544
+ # locally. We ignore this parameter for now
545
+ if "layernorm" in n:
546
+ continue
547
+ new_param = trainer.model.get_parameter(n)
548
+ # Check the torch dtype
549
+ assert new_param.dtype == torch.float16
550
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
551
+
552
+ @require_peft
553
+ def test_train_dense_with_peft_config_lora(self):
554
+ model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
555
+ model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
556
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
557
+
558
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
559
+
560
+ training_args = DPOConfig(
561
+ output_dir=self.tmp_dir,
562
+ learning_rate=1.0, # use higher lr because gradients are tiny and default lr can stall updates
563
+ report_to="none",
564
+ )
565
+
566
+ trainer = DPOTrainer(
567
+ model=model_id,
568
+ args=training_args,
569
+ train_dataset=dataset,
570
+ peft_config=LoraConfig(),
571
+ )
572
+
573
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
574
+
575
+ trainer.train()
576
+
577
+ assert trainer.state.log_history[-1]["train_loss"] is not None
578
+
579
+ # Check that the peft params have changed and the base model params have not changed
580
+ for n, param in previous_trainable_params.items():
581
+ new_param = trainer.model.get_parameter(n)
582
+ if n in base_param_names: # We expect the base model params to be the same
583
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
584
+ elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
585
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
586
+
587
+ @require_peft
588
+ def test_train_moe_with_peft_config(self):
589
+ model_id = "trl-internal-testing/tiny-GptOssForCausalLM"
590
+ model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
591
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
592
+
593
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
594
+
595
+ training_args = DPOConfig(
596
+ output_dir=self.tmp_dir,
597
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
598
+ report_to="none",
599
+ )
600
+
601
+ trainer = DPOTrainer(
602
+ model=model_id,
603
+ args=training_args,
604
+ train_dataset=dataset,
605
+ peft_config=LoraConfig(target_parameters=["mlp.experts.down_proj", "mlp.experts.gate_up_proj"]),
606
+ )
607
+
608
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
609
+
610
+ trainer.train()
611
+
612
+ assert trainer.state.log_history[-1]["train_loss"] is not None
613
+
614
+ # Check that the peft params have changed and the base model params have not changed
615
+ for n, param in previous_trainable_params.items():
616
+ new_param = trainer.model.get_parameter(n)
617
+ if n in base_param_names: # We expect the base model params to be the same
618
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
619
+ elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
620
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
621
+
622
+ @require_peft
623
+ def test_train_peft_model(self):
624
+ model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
625
+ model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
626
+
627
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
628
+
629
+ lora_config = LoraConfig()
630
+ model = get_peft_model(model, lora_config)
631
+
632
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
633
+
634
+ training_args = DPOConfig(
635
+ output_dir=self.tmp_dir,
636
+ learning_rate=1.0, # use higher lr because gradients are tiny and default lr can stall updates
637
+ report_to="none",
638
+ )
639
+ trainer = DPOTrainer(model=model, args=training_args, train_dataset=dataset)
640
+
641
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
642
+
643
+ trainer.train()
644
+
645
+ assert trainer.state.log_history[-1]["train_loss"] is not None
646
+
647
+ # Check that the peft params have changed and the base model params have not changed
648
+ for n, param in previous_trainable_params.items():
649
+ new_param = trainer.model.get_parameter(n)
650
+ if n in base_param_names: # We expect the base model params to be the same
651
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
652
+ elif "base_layer" not in n and "ref" not in n: # and the peft params to be different (except base and ref)
653
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
654
+
655
+ # In practice, this test is the same as `test_train_dense_with_peft_config_lora`, since gradient checkpointing is
656
+ # enabled by default in `DPOTrainer`. We keep it as a regression guard: if the default ever changes, we still
657
+ # explicitly test PEFT + gradient checkpointing, which has caused issues in the past.
658
+ @require_peft
659
+ def test_train_with_peft_config_and_gradient_checkpointing(self):
660
+ model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
661
+ model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
662
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
663
+
664
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
665
+
666
+ training_args = DPOConfig(
667
+ output_dir=self.tmp_dir,
668
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
669
+ gradient_checkpointing=True,
670
+ report_to="none",
671
+ )
672
+
673
+ trainer = DPOTrainer(
674
+ model=model_id,
675
+ args=training_args,
676
+ train_dataset=dataset,
677
+ peft_config=LoraConfig(),
678
+ )
679
+
680
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
681
+
682
+ trainer.train()
683
+
684
+ assert trainer.state.log_history[-1]["train_loss"] is not None
685
+
686
+ # Check that the peft params have changed and the base model params have not changed
687
+ for n, param in previous_trainable_params.items():
688
+ new_param = trainer.model.get_parameter(n)
689
+ if n in base_param_names: # We expect the base model params to be the same
690
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
691
+ elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
692
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
693
+
694
+ @require_liger_kernel
695
+ def test_train_with_liger(self):
696
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
697
+
698
+ training_args = DPOConfig(
699
+ output_dir=self.tmp_dir,
700
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
701
+ use_liger_kernel=True,
702
+ report_to="none",
703
+ )
704
+ trainer = DPOTrainer(
705
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
706
+ )
707
+
708
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
709
+
710
+ trainer.train()
711
+
712
+ assert trainer.state.log_history[-1]["train_loss"] is not None
713
+
714
+ # Check that the params have changed
715
+ for n, param in previous_trainable_params.items():
716
+ new_param = trainer.model.get_parameter(n)
717
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
718
+
719
+ @require_liger_kernel
720
+ @require_peft
721
+ def test_init_fails_with_peft_and_liger(self):
722
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
723
+
724
+ training_args = DPOConfig(
725
+ output_dir=self.tmp_dir,
726
+ use_liger_kernel=True,
727
+ report_to="none",
728
+ )
729
+
730
+ with pytest.raises(NotImplementedError, match="Liger DPO loss is not implemented for PEFT models."):
731
+ DPOTrainer(
732
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
733
+ args=training_args,
734
+ train_dataset=dataset,
735
+ peft_config=LoraConfig(),
736
+ )
737
+
738
+ def test_train_with_iterable_dataset(self):
739
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train", streaming=True)
740
+
741
+ training_args = DPOConfig(
742
+ output_dir=self.tmp_dir,
743
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
744
+ max_steps=3,
745
+ report_to="none",
746
+ )
747
+ trainer = DPOTrainer(
748
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
749
+ )
750
+
751
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
752
+
753
+ trainer.train()
754
+
755
+ assert trainer.state.log_history[-1]["train_loss"] is not None
756
+
757
+ # Check that the params have changed
758
+ for n, param in previous_trainable_params.items():
759
+ new_param = trainer.model.get_parameter(n)
760
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
761
+
762
+ @require_kernels
763
+ @pytest.mark.skipif(
764
+ not is_ampere_or_newer() and torch_device != "xpu",
765
+ reason="Flash Attention 2 requires Ampere or newer GPU, or XPU",
766
+ )
767
+ def test_train_padding_free(self):
768
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
769
+
770
+ training_args = DPOConfig(
771
+ output_dir=self.tmp_dir,
772
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
773
+ padding_free=True,
774
+ model_init_kwargs={"attn_implementation": "kernels-community/flash-attn2"},
775
+ bf16=True, # flash_attention_2 only supports bf16 and fp16
776
+ report_to="none",
777
+ )
778
+ trainer = DPOTrainer(
779
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
780
+ )
781
+
782
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
783
+
784
+ trainer.train()
785
+
786
+ assert trainer.state.log_history[-1]["train_loss"] is not None
787
+
788
+ # Check that the params have changed
789
+ for n, param in previous_trainable_params.items():
790
+ new_param = trainer.model.get_parameter(n)
791
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
792
+
793
+ def test_train_with_chat_template_kwargs(self):
794
+ dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train")
795
+
796
+ training_args = DPOConfig(
797
+ output_dir=self.tmp_dir,
798
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
799
+ report_to="none",
800
+ )
801
+
802
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
803
+ # The following template is a simplified version of the Qwen chat template, where an additional argument
804
+ # `role_capital` is used to control the capitalization of roles.
805
+ tokenizer.chat_template = '{%- if messages[0]["role"] == "system" -%} {{ "<|im_start|>" + ("SYSTEM" if role_capital else "system") + "\\n" + messages[0]["content"] + "<|im_end|>\\n" }}{%- else -%} {{ "<|im_start|>" + ("SYSTEM" if role_capital else "system") + "\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n" }}{%- endif -%}{%- for message in messages -%} {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) -%} {{ "<|im_start|>" + (message.role.upper() if role_capital else message.role) + "\\n" + message.content + "<|im_end|>\\n" }} {%- elif message.role == "assistant" -%} {{ "<|im_start|>" + ("ASSISTANT" if role_capital else "assistant") }} {%- if message.content -%} {{ "\\n" + message.content }} {%- endif -%} {{ "<|im_end|>\\n" }} {%- elif message.role == "tool" -%} {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") -%} {{ "<|im_start|>" + ("USER" if role_capital else "user") }} {%- endif -%} {{ "\\n<tool_response>\\n" + message.content + "\\n</tool_response>" }} {%- if loop.last or (messages[loop.index0 + 1].role != "tool") -%} {{ "<|im_end|>\\n" }} {%- endif -%} {%- endif -%}{%- endfor -%}{%- if add_generation_prompt -%} {{ "<|im_start|>" + ("ASSISTANT" if role_capital else "assistant") + "\\n" }}{%- endif -%}'
806
+
807
+ dataset = dataset.add_column(
808
+ "chat_template_kwargs", [{"role_capital": bool(i % 2)} for i in range(len(dataset))]
809
+ )
810
+ assert "chat_template_kwargs" in dataset.features
811
+
812
+ trainer = DPOTrainer(
813
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
814
+ args=training_args,
815
+ train_dataset=dataset,
816
+ processing_class=tokenizer,
817
+ )
818
+
819
+ assert trainer.processing_class.chat_template == tokenizer.chat_template
820
+
821
+ for i in range(2):
822
+ role = "SYSTEM" if i else "system"
823
+ system_prompt = (
824
+ f"<|im_start|>{role}\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>"
825
+ )
826
+ system_prompt_ids = trainer.processing_class(system_prompt)["input_ids"]
827
+ assert trainer.train_dataset[i]["prompt_ids"][: len(system_prompt_ids)] == system_prompt_ids
828
+
829
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
830
+
831
+ trainer.train()
832
+
833
+ assert trainer.state.log_history[-1]["train_loss"] is not None
834
+
835
+ # Check that the params have changed
836
+ for n, param in previous_trainable_params.items():
837
+ new_param = trainer.model.get_parameter(n)
838
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
839
+
840
+ def test_train_toolcall_data(self):
841
+ dataset = load_dataset("trl-internal-testing/toolcall", "preference", split="train")
842
+
843
+ training_args = DPOConfig(
844
+ output_dir=self.tmp_dir,
845
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
846
+ per_device_train_batch_size=2, # toolcall sequences are longer than standard data, reduce batch size to avoid OOM
847
+ max_length=512, # toolcall sequences are longer than standard data, limit length to avoid OOM
848
+ report_to="none",
849
+ )
850
+ trainer = DPOTrainer(
851
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
852
+ )
853
+
854
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
855
+
856
+ trainer.train()
857
+
858
+ assert trainer.state.log_history[-1]["train_loss"] is not None
859
+
860
+ # Check that the params have changed
861
+ for n, param in previous_trainable_params.items():
862
+ new_param = trainer.model.get_parameter(n)
863
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
864
+
865
+ def test_train_with_eval(self):
866
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference")
867
+
868
+ training_args = DPOConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none")
869
+ trainer = DPOTrainer(
870
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
871
+ args=training_args,
872
+ train_dataset=dataset["train"],
873
+ eval_dataset=dataset["test"],
874
+ )
875
+
876
+ trainer.train()
877
+
878
+ assert trainer.state.log_history[0]["eval_loss"] is not None
879
+
880
+ def test_train_with_multiple_eval_dataset(self):
881
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference")
882
+
883
+ training_args = DPOConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none")
884
+ trainer = DPOTrainer(
885
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
886
+ args=training_args,
887
+ train_dataset=dataset["train"],
888
+ eval_dataset={"data1": dataset["test"], "data2": dataset["test"]},
889
+ )
890
+ trainer.train()
891
+
892
+ assert trainer.state.log_history[-3]["eval_data1_loss"] is not None
893
+ assert trainer.state.log_history[-2]["eval_data2_loss"] is not None
894
+
895
+ def test_train_with_compute_metrics(self):
896
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference")
897
+
898
+ def dummy_compute_metrics(eval_pred):
899
+ return {"my_metric": 0.123}
900
+
901
+ training_args = DPOConfig(
902
+ output_dir=self.tmp_dir,
903
+ eval_strategy="steps",
904
+ eval_steps=3,
905
+ report_to="none",
906
+ )
907
+ trainer = DPOTrainer(
908
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
909
+ args=training_args,
910
+ train_dataset=dataset["train"],
911
+ eval_dataset=dataset["test"],
912
+ compute_metrics=dummy_compute_metrics,
913
+ )
914
+
915
+ trainer.train()
916
+
917
+ assert trainer.state.log_history[-2]["eval_my_metric"] == 0.123
918
+
919
+ # In practice, this test is the same as `test_train`, since gradient checkpointing is enabled by default in
920
+ # `DPOTrainer`. We keep it as a regression guard: if the default ever changes, we still explicitly test gradient
921
+ # checkpointing, which has caused issues in the past.
922
+ def test_train_with_gradient_checkpointing(self):
923
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
924
+
925
+ training_args = DPOConfig(
926
+ output_dir=self.tmp_dir,
927
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
928
+ gradient_checkpointing=True,
929
+ report_to="none",
930
+ )
931
+ trainer = DPOTrainer(
932
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
933
+ )
934
+
935
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
936
+
937
+ trainer.train()
938
+
939
+ assert trainer.state.log_history[-1]["train_loss"] is not None
940
+
941
+ # Check that the params have changed
942
+ for n, param in previous_trainable_params.items():
943
+ new_param = trainer.model.get_parameter(n)
944
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
945
+
946
+ def test_tag_added(self):
947
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
948
+
949
+ trainer = DPOTrainer(
950
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
951
+ train_dataset=dataset,
952
+ )
953
+
954
+ for tag in ["dpo", "trl"]:
955
+ assert tag in trainer.model.model_tags
956
+
957
+ @require_peft
958
+ def test_tag_added_peft(self):
959
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
960
+
961
+ trainer = DPOTrainer(
962
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
963
+ train_dataset=dataset,
964
+ peft_config=LoraConfig(),
965
+ )
966
+
967
+ for tag in ["dpo", "trl"]:
968
+ assert tag in trainer.model.model_tags
969
+
970
+ @require_peft
971
+ @require_bitsandbytes
972
+ def test_peft_with_quantization(self):
973
+ model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
974
+
975
+ quantization_config = BitsAndBytesConfig(
976
+ load_in_4bit=True,
977
+ bnb_4bit_use_double_quant=True,
978
+ bnb_4bit_quant_type="nf4",
979
+ bnb_4bit_compute_dtype=torch.float16,
980
+ )
981
+ model = AutoModelForCausalLM.from_pretrained(
982
+ model_id,
983
+ dtype="float32",
984
+ quantization_config=quantization_config,
985
+ )
986
+
987
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
988
+
989
+ # Initialize the trainer with the already configured PeftModel
990
+ training_args = DPOConfig(output_dir=self.tmp_dir, learning_rate=0.1, report_to="none")
991
+ trainer = DPOTrainer(model=model, args=training_args, train_dataset=dataset, peft_config=LoraConfig())
992
+
993
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
994
+
995
+ trainer.train()
996
+
997
+ assert trainer.state.log_history[-1]["train_loss"] is not None
998
+ assert trainer.state.log_history[-1]["mean_token_accuracy"] is not None
999
+
1000
+ # Check that the peft params have changed and the base model params have not changed
1001
+ for n, param in previous_trainable_params.items():
1002
+ new_param = trainer.model.get_parameter(n)
1003
+ # In bitsandbytes, bias parameters are automatically cast to the input dtype during the forward pass if
1004
+ # their dtype doesn’t match. This causes the module to change unexpectedly during the first forward pass of
1005
+ # the training. To handle this, we cast these specific bias parameters to float32 before comparison.
1006
+ # https://github.com/bitsandbytes-foundation/bitsandbytes/blob/45553f7392e524eacf400b132cfe01261f6477be/bitsandbytes/nn/modules.py#L518
1007
+ # We still need to investigate why the compute dtype ends up being different than for these parameters.
1008
+ if n in [
1009
+ "base_model.model.model.layers.1.self_attn.k_proj.bias",
1010
+ "base_model.model.model.layers.1.self_attn.q_proj.base_layer.bias",
1011
+ "base_model.model.model.layers.1.self_attn.v_proj.base_layer.bias",
1012
+ ]:
1013
+ param = param.float()
1014
+
1015
+ if "lora" not in n: # We expect the base model params to be the same
1016
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
1017
+ elif "lora" in n: # We expect the peft params to be different
1018
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
1019
+ else:
1020
+ raise ValueError(f"Unexpected parameter {n} in model: {trainer.model}")
1021
+
1022
+
1023
+ @require_vision
1024
+ class TestDPOTrainerVLM(TrlTestCase):
1025
+ @pytest.mark.parametrize(
1026
+ "model_id",
1027
+ [
1028
+ "trl-internal-testing/tiny-Gemma3ForConditionalGeneration",
1029
+ pytest.param(
1030
+ "trl-internal-testing/tiny-Gemma4ForConditionalGeneration",
1031
+ marks=pytest.mark.skipif(
1032
+ Version(transformers.__version__) < Version("5.5.0"),
1033
+ reason="Gemma4 models were introduced in transformers-5.5.0",
1034
+ ),
1035
+ ),
1036
+ # "trl-internal-testing/tiny-Idefics2ForConditionalGeneration", high memory peak, skipped for now
1037
+ # "trl-internal-testing/tiny-Idefics3ForConditionalGeneration", high memory peak, skipped for now
1038
+ "trl-internal-testing/tiny-LlavaForConditionalGeneration",
1039
+ "trl-internal-testing/tiny-LlavaNextForConditionalGeneration",
1040
+ "trl-internal-testing/tiny-Qwen2VLForConditionalGeneration",
1041
+ "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
1042
+ # "trl-internal-testing/tiny-SmolVLMForConditionalGeneration", seems not to support bf16 properly
1043
+ pytest.param(
1044
+ "trl-internal-testing/tiny-Qwen3VLForConditionalGeneration",
1045
+ marks=[
1046
+ pytest.mark.skipif(
1047
+ Version(transformers.__version__) < Version("4.57.0"),
1048
+ reason="Qwen3-VL series were introduced in transformers-4.57.0",
1049
+ ),
1050
+ ],
1051
+ ),
1052
+ pytest.param(
1053
+ "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink",
1054
+ marks=pytest.mark.skipif(
1055
+ Version(transformers.__version__) < Version("5.2.0"),
1056
+ reason="Qwen3.5 models were introduced in transformers-5.2.0",
1057
+ ),
1058
+ ),
1059
+ pytest.param(
1060
+ "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6",
1061
+ marks=pytest.mark.skipif(
1062
+ Version(transformers.__version__) < Version("5.2.0"),
1063
+ reason="Qwen3.5 models were introduced in transformers-5.2.0",
1064
+ ),
1065
+ ),
1066
+ ],
1067
+ )
1068
+ def test_train_vlm(self, model_id):
1069
+ dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
1070
+
1071
+ training_args = DPOConfig(
1072
+ output_dir=self.tmp_dir,
1073
+ max_length=None, # for VLMs, truncating can remove image tokens, leading to errors
1074
+ per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
1075
+ report_to="none",
1076
+ )
1077
+ trainer = DPOTrainer(model=model_id, args=training_args, train_dataset=dataset)
1078
+
1079
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1080
+
1081
+ trainer.train()
1082
+
1083
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1084
+
1085
+ # Check that the params have changed
1086
+ for n, param in previous_trainable_params.items():
1087
+ new_param = trainer.model.get_parameter(n)
1088
+ # LLaVA & LLaVA-Next: vision_feature_layer=-2 leaves the last encoder layer (layers.1) and
1089
+ # post_layernorm (pooler-only path) without gradient by design. Assert they stay frozen — if they
1090
+ # ever start training, the feature-selection plumbing has likely regressed.
1091
+ if model_id in (
1092
+ "trl-internal-testing/tiny-LlavaForConditionalGeneration",
1093
+ "trl-internal-testing/tiny-LlavaNextForConditionalGeneration",
1094
+ ) and ("encoder.layers.1" in n or "post_layernorm" in n):
1095
+ assert torch.equal(param, new_param), f"Param {n} expected frozen by LLaVA design, but changed"
1096
+ else:
1097
+ assert not torch.equal(param, new_param), f"Param {n} is not updated"
1098
+
1099
+ @pytest.mark.parametrize(
1100
+ "model_id",
1101
+ [
1102
+ "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
1103
+ ],
1104
+ )
1105
+ @pytest.mark.xfail(
1106
+ parse_version(transformers.__version__) < parse_version("4.57.0"),
1107
+ reason="Mixing text-only and image+text examples is only supported in transformers >= 4.57.0",
1108
+ strict=False,
1109
+ )
1110
+ def test_train_vlm_multi_image(self, model_id):
1111
+ dataset = load_dataset("trl-internal-testing/zen-multi-image", "conversational_preference", split="train")
1112
+
1113
+ training_args = DPOConfig(
1114
+ output_dir=self.tmp_dir,
1115
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1116
+ max_length=None, # for VLMs, truncating can remove image tokens, leading to errors
1117
+ per_device_train_batch_size=1, # VLM training is memory intensive, reduce batch size to avoid OOM
1118
+ report_to="none",
1119
+ )
1120
+ trainer = DPOTrainer(
1121
+ model=model_id,
1122
+ args=training_args,
1123
+ train_dataset=dataset,
1124
+ )
1125
+
1126
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1127
+
1128
+ trainer.train()
1129
+
1130
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1131
+
1132
+ # Check that the params have changed
1133
+ for n, param in previous_trainable_params.items():
1134
+ new_param = trainer.model.get_parameter(n)
1135
+ assert not torch.equal(param, new_param), f"Param {n} is not updated"
1136
+
1137
+ @pytest.mark.parametrize(
1138
+ "model_id",
1139
+ [
1140
+ "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
1141
+ ],
1142
+ )
1143
+ @pytest.mark.parametrize(
1144
+ "dataset_config",
1145
+ ["conversational_preference", "standard_preference"],
1146
+ )
1147
+ def test_train_vlm_text_only_data(self, model_id, dataset_config):
1148
+ dataset = load_dataset("trl-internal-testing/zen", dataset_config, split="train")
1149
+
1150
+ training_args = DPOConfig(output_dir=self.tmp_dir, report_to="none")
1151
+ trainer = DPOTrainer(
1152
+ model=model_id,
1153
+ args=training_args,
1154
+ train_dataset=dataset,
1155
+ )
1156
+
1157
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1158
+
1159
+ trainer.train()
1160
+
1161
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1162
+
1163
+ # Check that the params have changed
1164
+ for n, param in previous_trainable_params.items():
1165
+ new_param = trainer.model.get_parameter(n)
1166
+ if n.startswith("model.visual"):
1167
+ torch.testing.assert_close(param, new_param, rtol=1e-12, atol=1e-12, msg=f"Param {n} is updated")
1168
+ else:
1169
+ assert not torch.equal(param, new_param), f"Param {n} is not updated"
1170
+
1171
+ def test_train_vlm_with_max_length(self):
1172
+ # Regression test for #5283: mm_token_type_ids must be truncated alongside input_ids when max_length is set,
1173
+ # otherwise a shape mismatch crashes the model forward pass.
1174
+ # max_length=37 truncates 1 completion token (total_len=38) while keeping all image tokens (prompt_len=34) safe.
1175
+ dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
1176
+ training_args = DPOConfig(
1177
+ output_dir=self.tmp_dir,
1178
+ max_length=37, # total_len=38, prompt_len=34 — truncates completion, not image tokens
1179
+ per_device_train_batch_size=2,
1180
+ report_to="none",
1181
+ )
1182
+ trainer = DPOTrainer(
1183
+ model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
1184
+ args=training_args,
1185
+ train_dataset=dataset,
1186
+ )
1187
+ trainer.train()
1188
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1189
+
1190
+ def test_train_vlm_keep_end_raises(self):
1191
+ # Regression test for #5285: keep_end with a VLM must raise at init time, not silently corrupt training.
1192
+ # Image tokens live at the start of the sequence (in the prompt); keep_end would drop them.
1193
+ dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
1194
+ with pytest.warns(FutureWarning, match="keep_end.*deprecated"):
1195
+ training_args = DPOConfig(
1196
+ output_dir=self.tmp_dir,
1197
+ max_length=32,
1198
+ truncation_mode="keep_end",
1199
+ report_to="none",
1200
+ )
1201
+ with pytest.raises(ValueError, match="truncation_mode='keep_end' is not supported for vision-language models"):
1202
+ DPOTrainer(
1203
+ model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
1204
+ args=training_args,
1205
+ train_dataset=dataset,
1206
+ )
1207
+
1208
+ def test_vision_dataset_with_text_model_raises(self):
1209
+ dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
1210
+ training_args = DPOConfig(output_dir=self.tmp_dir, report_to="none")
1211
+ with pytest.raises(ValueError, match="vision-related.*vision-language model"):
1212
+ DPOTrainer(
1213
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1214
+ args=training_args,
1215
+ train_dataset=dataset,
1216
+ )
1217
+
1218
+ def test_precompute_ref_log_probs_raises_for_vision(self):
1219
+ dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
1220
+ training_args = DPOConfig(output_dir=self.tmp_dir, report_to="none", precompute_ref_log_probs=True)
1221
+ with pytest.raises(ValueError, match="precompute_ref_log_probs.*not supported for vision datasets"):
1222
+ DPOTrainer(
1223
+ model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
1224
+ args=training_args,
1225
+ train_dataset=dataset,
1226
+ )
1227
+
1228
+ @require_liger_kernel
1229
+ def test_train_vlm_liger(self):
1230
+ dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
1231
+ training_args = DPOConfig(
1232
+ output_dir=self.tmp_dir,
1233
+ max_length=None, # for VLMs, truncating can remove image tokens, leading to errors
1234
+ per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
1235
+ use_liger_kernel=True,
1236
+ report_to="none",
1237
+ )
1238
+ trainer = DPOTrainer(
1239
+ model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
1240
+ args=training_args,
1241
+ train_dataset=dataset,
1242
+ )
1243
+
1244
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1245
+
1246
+ trainer.train()
1247
+
1248
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1249
+
1250
+ for n, param in previous_trainable_params.items():
1251
+ new_param = trainer.model.get_parameter(n)
1252
+ assert not torch.equal(param, new_param), f"Param {n} is not updated"
1253
+
1254
+
1255
+ @pytest.mark.slow
1256
+ class TestDPOTrainerSlow(TrlTestCase):
1257
+ # Gemma 3n uses a timm encoder, making it difficult to create a smaller variant for testing.
1258
+ # To ensure coverage, we run tests on the full model but mark them as slow to exclude from default runs.
1259
+ @pytest.mark.skip(reason="Model google/gemma-3n-E2B-it is gated and requires HF token")
1260
+ @require_vision
1261
+ def test_train_vlm_gemma_3n(self):
1262
+ dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
1263
+
1264
+ training_args = DPOConfig(
1265
+ output_dir=self.tmp_dir,
1266
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1267
+ max_length=None, # for VLMs, truncating can remove image tokens, leading to errors
1268
+ per_device_train_batch_size=1, # VLM training is memory intensive, reduce batch size to avoid OOM
1269
+ model_init_kwargs={"dtype": "bfloat16"},
1270
+ report_to="none",
1271
+ )
1272
+ trainer = DPOTrainer(model="google/gemma-3n-E2B-it", args=training_args, train_dataset=dataset)
1273
+
1274
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1275
+
1276
+ trainer.train()
1277
+
1278
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1279
+
1280
+ # Check that the params have changed
1281
+ for n, param in previous_trainable_params.items():
1282
+ new_param = trainer.model.get_parameter(n)
1283
+ if "model.audio_tower" in n or "model.embed_audio" in n:
1284
+ # The audio embedding parameters are not updated because this dataset contains no audio data
1285
+ continue
1286
+ assert not torch.equal(param, new_param), f"Param {n} is not updated"
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_grpo_trainer.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_model_utils.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 transformers import AutoModelForCausalLM
16
+
17
+ from trl.models.utils import disable_gradient_checkpointing
18
+
19
+
20
+ class TestDisableGradientCheckpointing:
21
+ def test_when_disabled(self):
22
+ model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
23
+ assert model.is_gradient_checkpointing is False
24
+ with disable_gradient_checkpointing(model):
25
+ assert model.is_gradient_checkpointing is False
26
+ assert model.is_gradient_checkpointing is False
27
+
28
+ def test_when_enabled(self):
29
+ model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
30
+ model.gradient_checkpointing_enable()
31
+ assert model.is_gradient_checkpointing is True
32
+ with disable_gradient_checkpointing(model):
33
+ assert model.is_gradient_checkpointing is False
34
+ assert model.is_gradient_checkpointing is True
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_reward_trainer.py ADDED
@@ -0,0 +1,837 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 pathlib
17
+
18
+ import pytest
19
+ import torch
20
+ from datasets import load_dataset
21
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
22
+ from transformers.utils import is_peft_available
23
+
24
+ from trl import RewardConfig, RewardTrainer
25
+ from trl.trainer.reward_trainer import DataCollatorForPreference
26
+
27
+ from .testing_utils import TrlTestCase, require_peft
28
+
29
+
30
+ if is_peft_available():
31
+ from peft import LoraConfig, get_peft_model
32
+
33
+
34
+ class TestDataCollatorForPreference(TrlTestCase):
35
+ def test_basic_padding(self):
36
+ """Test basic padding functionality without completion masks."""
37
+ collator = DataCollatorForPreference(pad_token_id=0)
38
+ examples = [
39
+ {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5]},
40
+ {"chosen_ids": [6, 7], "rejected_ids": [8]},
41
+ ]
42
+
43
+ result = collator(examples)
44
+
45
+ torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [6, 7, 0], [4, 5, 0], [8, 0, 0]]))
46
+ torch.testing.assert_close(
47
+ result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0], [1, 1, 0], [1, 0, 0]])
48
+ )
49
+
50
+ def test_pad_to_multiple_of(self):
51
+ """Test padding to multiple of specified value."""
52
+ collator = DataCollatorForPreference(pad_token_id=0, pad_to_multiple_of=4)
53
+ examples = [
54
+ {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5]},
55
+ {"chosen_ids": [6, 7], "rejected_ids": [8]},
56
+ ]
57
+
58
+ result = collator(examples)
59
+
60
+ torch.testing.assert_close(
61
+ result["input_ids"], torch.tensor([[1, 2, 3, 0], [6, 7, 0, 0], [4, 5, 0, 0], [8, 0, 0, 0]])
62
+ )
63
+ torch.testing.assert_close(
64
+ result["attention_mask"], torch.tensor([[1, 1, 1, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 0, 0, 0]])
65
+ )
66
+
67
+ def test_single_example(self):
68
+ """Test collator with a single example."""
69
+ collator = DataCollatorForPreference(pad_token_id=0)
70
+ examples = [{"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5]}]
71
+
72
+ result = collator(examples)
73
+
74
+ torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]]))
75
+ torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]]))
76
+
77
+ def test_different_pad_token_id(self):
78
+ """Test with different pad token ID."""
79
+ collator = DataCollatorForPreference(pad_token_id=999)
80
+ examples = [
81
+ {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5]},
82
+ {"chosen_ids": [6, 7], "rejected_ids": [8]},
83
+ ]
84
+
85
+ result = collator(examples)
86
+
87
+ torch.testing.assert_close(
88
+ result["input_ids"], torch.tensor([[1, 2, 3], [6, 7, 999], [4, 5, 999], [8, 999, 999]])
89
+ )
90
+ torch.testing.assert_close(
91
+ result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0], [1, 1, 0], [1, 0, 0]])
92
+ )
93
+
94
+ def test_collate_with_margin(self):
95
+ collator = DataCollatorForPreference(pad_token_id=0)
96
+ examples = [
97
+ {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5], "margin": 0.1},
98
+ {"chosen_ids": [6, 7], "rejected_ids": [8], "margin": 0.2},
99
+ ]
100
+
101
+ result = collator(examples)
102
+
103
+ torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [6, 7, 0], [4, 5, 0], [8, 0, 0]]))
104
+ torch.testing.assert_close(
105
+ result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0], [1, 1, 0], [1, 0, 0]])
106
+ )
107
+ torch.testing.assert_close(result["margin"], torch.tensor([0.1, 0.2]))
108
+
109
+
110
+ class TestRewardTrainer(TrlTestCase):
111
+ def test_raises_error_when_model_num_labels_not_one(self):
112
+ """Test that RewardTrainer raises ValueError when model doesn't have num_labels=1."""
113
+ model = AutoModelForSequenceClassification.from_pretrained(
114
+ "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
115
+ dtype="float32",
116
+ # num_labels=2, # Defaults to 2 num_labels for causal models
117
+ )
118
+
119
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
120
+
121
+ training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
122
+ with pytest.raises(ValueError, match=r"reward models require `num_labels=1`"):
123
+ RewardTrainer(model=model, args=training_args, train_dataset=dataset)
124
+
125
+ @pytest.mark.parametrize(
126
+ "model_id",
127
+ [
128
+ "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
129
+ "trl-internal-testing/tiny-Qwen3MoeForCausalLM",
130
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.2",
131
+ ],
132
+ )
133
+ def test_train(self, model_id):
134
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
135
+
136
+ training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
137
+ trainer = RewardTrainer(model=model_id, args=training_args, train_dataset=dataset)
138
+
139
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
140
+
141
+ trainer.train()
142
+
143
+ assert trainer.state.log_history[-1]["train_loss"] is not None
144
+
145
+ # Check that the params have changed
146
+ for n, param in previous_trainable_params.items():
147
+ new_param = trainer.model.get_parameter(n)
148
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
149
+
150
+ @pytest.mark.parametrize(
151
+ "config_name",
152
+ [
153
+ "standard_preference",
154
+ "conversational_preference",
155
+ "standard_implicit_prompt_preference",
156
+ "conversational_implicit_prompt_preference",
157
+ ],
158
+ )
159
+ def test_train_dataset_types(self, config_name):
160
+ dataset = load_dataset("trl-internal-testing/zen", config_name, split="train")
161
+
162
+ training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
163
+ trainer = RewardTrainer(
164
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
165
+ args=training_args,
166
+ train_dataset=dataset,
167
+ )
168
+
169
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
170
+
171
+ trainer.train()
172
+
173
+ assert trainer.state.log_history[-1]["train_loss"] is not None
174
+
175
+ # Check that the params have changed
176
+ for n, param in previous_trainable_params.items():
177
+ new_param = trainer.model.get_parameter(n)
178
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
179
+
180
+ def test_train_model(self):
181
+ model = AutoModelForSequenceClassification.from_pretrained(
182
+ "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
183
+ num_labels=1, # required for reward models
184
+ dtype="float32",
185
+ )
186
+
187
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
188
+
189
+ training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
190
+ trainer = RewardTrainer(model=model, args=training_args, train_dataset=dataset)
191
+
192
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
193
+
194
+ trainer.train()
195
+
196
+ assert trainer.state.log_history[-1]["train_loss"] is not None
197
+
198
+ # Check that the params have changed
199
+ for n, param in previous_trainable_params.items():
200
+ new_param = trainer.model.get_parameter(n)
201
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
202
+
203
+ def test_train_from_sequence_classification_model(self):
204
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
205
+
206
+ training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
207
+ trainer = RewardTrainer(
208
+ model="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
209
+ args=training_args,
210
+ train_dataset=dataset,
211
+ )
212
+
213
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
214
+
215
+ trainer.train()
216
+
217
+ assert trainer.state.log_history[-1]["train_loss"] is not None
218
+
219
+ # Check that the params have changed
220
+ for n, param in previous_trainable_params.items():
221
+ new_param = trainer.model.get_parameter(n)
222
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
223
+
224
+ def test_train_model_dtype(self):
225
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
226
+
227
+ training_args = RewardConfig(
228
+ output_dir=self.tmp_dir,
229
+ model_init_kwargs={"dtype": torch.float16},
230
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
231
+ report_to="none",
232
+ )
233
+ trainer = RewardTrainer(
234
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
235
+ args=training_args,
236
+ train_dataset=dataset,
237
+ )
238
+
239
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
240
+
241
+ trainer.train()
242
+
243
+ assert trainer.state.log_history[-1]["train_loss"] is not None
244
+
245
+ # Check that the params have changed
246
+ for n, param in previous_trainable_params.items():
247
+ # For some reasonn model.layers.0.input_layernorm.weight doesn't change in GitHub Actions but does
248
+ # locally. We ignore this parameter for now
249
+ if "layernorm" in n:
250
+ continue
251
+ new_param = trainer.model.get_parameter(n)
252
+ # Check the torch dtype
253
+ assert new_param.dtype == torch.float16
254
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
255
+
256
+ @require_peft
257
+ def test_train_dense_with_peft_config(self):
258
+ model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
259
+ model = AutoModelForSequenceClassification.from_pretrained(model_id, dtype="float32")
260
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
261
+
262
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
263
+
264
+ training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
265
+
266
+ trainer = RewardTrainer(
267
+ model=model_id,
268
+ args=training_args,
269
+ train_dataset=dataset,
270
+ peft_config=LoraConfig(),
271
+ )
272
+
273
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
274
+
275
+ trainer.train()
276
+
277
+ assert trainer.state.log_history[-1]["train_loss"] is not None
278
+
279
+ # Check that the peft params have changed and the base model params have not changed
280
+ for n, param in previous_trainable_params.items():
281
+ new_param = trainer.model.get_parameter(n)
282
+ if n in base_param_names: # We expect the base model params to be the same
283
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
284
+ elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
285
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
286
+
287
+ @require_peft
288
+ def test_train_moe_with_peft_config(self):
289
+ model_id = "trl-internal-testing/tiny-Qwen3MoeForCausalLM"
290
+ model = AutoModelForSequenceClassification.from_pretrained(model_id, dtype="float32")
291
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
292
+
293
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
294
+
295
+ training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
296
+
297
+ trainer = RewardTrainer(
298
+ model=model_id,
299
+ args=training_args,
300
+ train_dataset=dataset,
301
+ peft_config=LoraConfig(target_modules=["gate_proj", "up_proj", "down_proj", "score"]),
302
+ )
303
+
304
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
305
+
306
+ trainer.train()
307
+
308
+ assert trainer.state.log_history[-1]["train_loss"] is not None
309
+
310
+ # Check that the peft params have changed and the base model params have not changed
311
+ for n, param in previous_trainable_params.items():
312
+ new_param = trainer.model.get_parameter(n)
313
+ if n in base_param_names: # We expect the base model params to be the same
314
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
315
+ elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
316
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
317
+
318
+ @require_peft
319
+ def test_train_peft_model(self):
320
+ model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
321
+ model = AutoModelForSequenceClassification.from_pretrained(
322
+ model_id,
323
+ num_labels=1, # required for reward models
324
+ dtype="float32",
325
+ )
326
+
327
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
328
+
329
+ lora_config = LoraConfig()
330
+ model = get_peft_model(model, lora_config)
331
+
332
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
333
+
334
+ training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
335
+ trainer = RewardTrainer(model=model, args=training_args, train_dataset=dataset)
336
+
337
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
338
+
339
+ trainer.train()
340
+
341
+ assert trainer.state.log_history[-1]["train_loss"] is not None
342
+
343
+ # Check that the peft params have changed and the base model params have not changed
344
+ for n, param in previous_trainable_params.items():
345
+ new_param = trainer.model.get_parameter(n)
346
+ if n in base_param_names: # We expect the base model params to be the same
347
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
348
+ elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
349
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
350
+
351
+ # In practice, this test is the same as `test_train_dense_with_peft_config`, since gradient checkpointing is
352
+ # enabled by default in `RewardTrainer`. We keep it as a regression guard: if the default ever changes, we still
353
+ # explicitly test PEFT + gradient checkpointing, which has caused issues in the past.
354
+ @require_peft
355
+ def test_train_with_peft_config_and_gradient_checkpointing(self):
356
+ model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
357
+ model = AutoModelForSequenceClassification.from_pretrained(model_id, dtype="float32")
358
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
359
+
360
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
361
+
362
+ training_args = RewardConfig(output_dir=self.tmp_dir, gradient_checkpointing=True, report_to="none")
363
+
364
+ trainer = RewardTrainer(
365
+ model=model_id,
366
+ args=training_args,
367
+ train_dataset=dataset,
368
+ peft_config=LoraConfig(),
369
+ )
370
+
371
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
372
+
373
+ trainer.train()
374
+
375
+ assert trainer.state.log_history[-1]["train_loss"] is not None
376
+
377
+ # Check that the peft params have changed and the base model params have not changed
378
+ for n, param in previous_trainable_params.items():
379
+ new_param = trainer.model.get_parameter(n)
380
+ if n in base_param_names: # We expect the base model params to be the same
381
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
382
+ elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
383
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
384
+
385
+ @pytest.mark.parametrize("use_reentrant", [True, False])
386
+ @require_peft
387
+ def test_train_with_peft_config_and_gradient_checkpointing_reentrant(self, use_reentrant):
388
+ model_id = "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"
389
+ model = AutoModelForSequenceClassification.from_pretrained(model_id, dtype="float32")
390
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
391
+
392
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
393
+
394
+ training_args = RewardConfig(
395
+ output_dir=self.tmp_dir,
396
+ gradient_checkpointing=True,
397
+ gradient_checkpointing_kwargs={"use_reentrant": use_reentrant},
398
+ report_to="none",
399
+ )
400
+
401
+ trainer = RewardTrainer(
402
+ model=model_id,
403
+ args=training_args,
404
+ train_dataset=dataset,
405
+ peft_config=LoraConfig(),
406
+ )
407
+
408
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
409
+
410
+ trainer.train()
411
+
412
+ assert trainer.state.log_history[-1]["train_loss"] is not None
413
+
414
+ # Check that the peft params have changed and the base model params have not changed
415
+ for n, param in previous_trainable_params.items():
416
+ new_param = trainer.model.get_parameter(n)
417
+ if n in base_param_names: # We expect the base model params to be the same
418
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
419
+ elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
420
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
421
+
422
+ @pytest.mark.parametrize(
423
+ "chosen_column,rejected_column,expect_deprecation_warning",
424
+ [
425
+ ("chosen_ids", "rejected_ids", False),
426
+ ("chosen_input_ids", "rejected_input_ids", True),
427
+ ],
428
+ )
429
+ def test_train_with_pretokenized_data(self, chosen_column, rejected_column, expect_deprecation_warning):
430
+ model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
431
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
432
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
433
+
434
+ def tokenize_example(example):
435
+ return {
436
+ chosen_column: tokenizer(example["chosen"]).input_ids,
437
+ rejected_column: tokenizer(example["rejected"]).input_ids,
438
+ }
439
+
440
+ # Apply tokenization
441
+ tokenized_dataset = dataset.map(tokenize_example, remove_columns=["chosen", "rejected"])
442
+
443
+ training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
444
+ if expect_deprecation_warning:
445
+ with pytest.warns(FutureWarning, match=r"will not be supported in v1"):
446
+ trainer = RewardTrainer(model=model_id, args=training_args, train_dataset=tokenized_dataset)
447
+ else:
448
+ trainer = RewardTrainer(model=model_id, args=training_args, train_dataset=tokenized_dataset)
449
+
450
+ assert "chosen_ids" in trainer.train_dataset.column_names
451
+ assert "rejected_ids" in trainer.train_dataset.column_names
452
+ assert "chosen_input_ids" not in trainer.train_dataset.column_names
453
+ assert "rejected_input_ids" not in trainer.train_dataset.column_names
454
+
455
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
456
+
457
+ trainer.train()
458
+
459
+ assert trainer.state.log_history[-1]["train_loss"] is not None
460
+
461
+ # Check that the params have changed
462
+ for n, param in previous_trainable_params.items():
463
+ new_param = trainer.model.get_parameter(n)
464
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
465
+
466
+ def test_train_with_iterable_dataset(self):
467
+ dataset = load_dataset(
468
+ "trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train", streaming=True
469
+ )
470
+
471
+ training_args = RewardConfig(output_dir=self.tmp_dir, max_steps=3, report_to="none")
472
+ trainer = RewardTrainer(
473
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
474
+ args=training_args,
475
+ train_dataset=dataset,
476
+ )
477
+
478
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
479
+
480
+ trainer.train()
481
+
482
+ assert trainer.state.log_history[-1]["train_loss"] is not None
483
+
484
+ # Check that the params have changed
485
+ for n, param in previous_trainable_params.items():
486
+ new_param = trainer.model.get_parameter(n)
487
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
488
+
489
+ def test_train_with_chat_template_kwargs(self):
490
+ dataset = load_dataset("trl-internal-testing/zen", "conversational_implicit_prompt_preference", split="train")
491
+
492
+ training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
493
+
494
+ tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
495
+ # The following template is a simplified version of the Qwen chat template, where an additional argument
496
+ # `role_capital` is used to control the capitalization of roles.
497
+ tokenizer.chat_template = '{%- if messages[0]["role"] == "system" -%} {{ "<|im_start|>" + ("SYSTEM" if role_capital else "system") + "\\n" + messages[0]["content"] + "<|im_end|>\\n" }}{%- else -%} {{ "<|im_start|>" + ("SYSTEM" if role_capital else "system") + "\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n" }}{%- endif -%}{%- for message in messages -%} {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) -%} {{ "<|im_start|>" + (message.role.upper() if role_capital else message.role) + "\\n" + message.content + "<|im_end|>\\n" }} {%- elif message.role == "assistant" -%} {{ "<|im_start|>" + ("ASSISTANT" if role_capital else "assistant") }} {%- if message.content -%} {{ "\\n" + message.content }} {%- endif -%} {{ "<|im_end|>\\n" }} {%- elif message.role == "tool" -%} {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") -%} {{ "<|im_start|>" + ("USER" if role_capital else "user") }} {%- endif -%} {{ "\\n<tool_response>\\n" + message.content + "\\n</tool_response>" }} {%- if loop.last or (messages[loop.index0 + 1].role != "tool") -%} {{ "<|im_end|>\\n" }} {%- endif -%} {%- endif -%}{%- endfor -%}{%- if add_generation_prompt -%} {{ "<|im_start|>" + ("ASSISTANT" if role_capital else "assistant") + "\\n" }}{%- endif -%}'
498
+
499
+ dataset = dataset.add_column(
500
+ "chat_template_kwargs", [{"role_capital": bool(i % 2)} for i in range(len(dataset))]
501
+ )
502
+ assert "chat_template_kwargs" in dataset.features
503
+
504
+ trainer = RewardTrainer(
505
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
506
+ args=training_args,
507
+ train_dataset=dataset,
508
+ processing_class=tokenizer,
509
+ )
510
+
511
+ assert trainer.processing_class.chat_template == tokenizer.chat_template
512
+
513
+ for i in range(2):
514
+ role = "SYSTEM" if i else "system"
515
+ system_prompt = (
516
+ f"<|im_start|>{role}\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>"
517
+ )
518
+ system_prompt_ids = trainer.processing_class(system_prompt)["input_ids"]
519
+ assert trainer.train_dataset[i]["chosen_ids"][: len(system_prompt_ids)] == system_prompt_ids
520
+ assert trainer.train_dataset[i]["rejected_ids"][: len(system_prompt_ids)] == system_prompt_ids
521
+
522
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
523
+
524
+ trainer.train()
525
+
526
+ assert trainer.state.log_history[-1]["train_loss"] is not None
527
+
528
+ # Check that the params have changed
529
+ for n, param in previous_trainable_params.items():
530
+ new_param = trainer.model.get_parameter(n)
531
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
532
+
533
+ def test_train_with_set_chat_template_from_model(self):
534
+ dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train")
535
+
536
+ training_args = RewardConfig(output_dir=self.tmp_dir, chat_template_path="Qwen/Qwen3-4B", report_to="none")
537
+ # trl-internal-testing/tiny-GPTNeoXForCausalLM doesn't have a chat template set by default
538
+ trainer = RewardTrainer(
539
+ model="trl-internal-testing/tiny-GPTNeoXForCausalLM",
540
+ args=training_args,
541
+ train_dataset=dataset,
542
+ )
543
+
544
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
545
+
546
+ trainer.train()
547
+
548
+ assert trainer.state.log_history[-1]["train_loss"] is not None
549
+
550
+ # Check that the params have changed
551
+ for n, param in previous_trainable_params.items():
552
+ new_param = trainer.model.get_parameter(n)
553
+ # RewardTrainer uses a mean-free loss that cancels uniform shifts in output scores. Since GPT-NeoX models
554
+ # include a final LayerNorm, its bias consistently receives zero gradient and remains unchanged, so we skip
555
+ # this parameter.
556
+ if n == "gpt_neox.final_layer_norm.bias":
557
+ continue
558
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
559
+
560
+ def test_train_with_set_chat_template_from_path(self, lazy_shared_datadir):
561
+ dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train")
562
+
563
+ training_args = RewardConfig(
564
+ output_dir=self.tmp_dir,
565
+ chat_template_path=str(lazy_shared_datadir / "template.jinja"),
566
+ report_to="none",
567
+ )
568
+ # trl-internal-testing/tiny-GPTNeoXForCausalLM doesn't have a chat template set by default
569
+ trainer = RewardTrainer(
570
+ model="trl-internal-testing/tiny-GPTNeoXForCausalLM",
571
+ args=training_args,
572
+ train_dataset=dataset,
573
+ )
574
+
575
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
576
+
577
+ trainer.train()
578
+
579
+ assert trainer.state.log_history[-1]["train_loss"] is not None
580
+
581
+ # Check that the params have changed
582
+ for n, param in previous_trainable_params.items():
583
+ new_param = trainer.model.get_parameter(n)
584
+ # RewardTrainer uses a mean-free loss that cancels uniform shifts in output scores. Since GPT-NeoX models
585
+ # include a final LayerNorm, its bias consistently receives zero gradient and remains unchanged, so we skip
586
+ # this parameter.
587
+ if n == "gpt_neox.final_layer_norm.bias":
588
+ continue
589
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
590
+
591
+ # Check that the template saved in the output directory is the same as the one used for training
592
+ template_path = pathlib.Path(self.tmp_dir) / "checkpoint-9" / "chat_template.jinja"
593
+ assert template_path.exists(), f"Chat template not found at {template_path}"
594
+
595
+ with open(template_path) as f:
596
+ template_content = f.read()
597
+ with open(training_args.chat_template_path) as f:
598
+ original_template_content = f.read()
599
+ assert template_content == original_template_content, "Chat template content does not match the original"
600
+
601
+ def test_train_toolcall_data(self):
602
+ dataset = load_dataset("trl-internal-testing/toolcall", "preference", split="train")
603
+
604
+ training_args = RewardConfig(
605
+ output_dir=self.tmp_dir,
606
+ per_device_train_batch_size=2, # toolcall sequences are longer than standard data, reduce batch size to avoid OOM
607
+ max_length=512, # toolcall sequences are longer than standard data, limit length to avoid OOM
608
+ report_to="none",
609
+ )
610
+ trainer = RewardTrainer(
611
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
612
+ args=training_args,
613
+ train_dataset=dataset,
614
+ )
615
+
616
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
617
+
618
+ trainer.train()
619
+
620
+ assert trainer.state.log_history[-1]["train_loss"] is not None
621
+
622
+ # Check that the params have changed
623
+ for n, param in previous_trainable_params.items():
624
+ new_param = trainer.model.get_parameter(n)
625
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
626
+
627
+ def test_train_toolcall_data_as_json(self):
628
+ # Tabular backends (Arrow/Parquet) can insert `None` for missing keys in nested structures.
629
+ # If `tools` is stored as a list of dicts and examples use different dict schemas, nulls may
630
+ # be introduced and break tool processing. This test ensures we also support `tools` provided
631
+ # as a list of dicts.
632
+ dataset = load_dataset("trl-internal-testing/toolcall", "preference", split="train")
633
+
634
+ def convert_to_json(example):
635
+ return {"tools": json.loads(example["tools"])}
636
+
637
+ dataset = dataset.map(convert_to_json)
638
+
639
+ training_args = RewardConfig(
640
+ output_dir=self.tmp_dir,
641
+ per_device_train_batch_size=2, # toolcall sequences are longer than standard data, reduce batch size to avoid OOM
642
+ max_length=512, # toolcall sequences are longer than standard data, limit length to avoid OOM
643
+ report_to="none",
644
+ )
645
+ trainer = RewardTrainer(
646
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
647
+ args=training_args,
648
+ train_dataset=dataset,
649
+ )
650
+
651
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
652
+
653
+ trainer.train()
654
+
655
+ assert trainer.state.log_history[-1]["train_loss"] is not None
656
+
657
+ # Check that the params have changed
658
+ for n, param in previous_trainable_params.items():
659
+ new_param = trainer.model.get_parameter(n)
660
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
661
+
662
+ def test_train_with_eval(self):
663
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference")
664
+
665
+ training_args = RewardConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none")
666
+ trainer = RewardTrainer(
667
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
668
+ args=training_args,
669
+ train_dataset=dataset["train"],
670
+ eval_dataset=dataset["test"],
671
+ )
672
+
673
+ trainer.train()
674
+
675
+ assert trainer.state.log_history[0]["eval_loss"] is not None
676
+
677
+ def test_train_with_multiple_eval_dataset(self):
678
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference")
679
+
680
+ training_args = RewardConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none")
681
+ trainer = RewardTrainer(
682
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
683
+ args=training_args,
684
+ train_dataset=dataset["train"],
685
+ eval_dataset={"data1": dataset["test"], "data2": dataset["test"]},
686
+ )
687
+ trainer.train()
688
+
689
+ assert trainer.state.log_history[-3]["eval_data1_loss"] is not None
690
+ assert trainer.state.log_history[-2]["eval_data2_loss"] is not None
691
+
692
+ def test_train_with_compute_metrics(self):
693
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference")
694
+
695
+ def dummy_compute_metrics(eval_pred):
696
+ return {"my_metric": 0.123}
697
+
698
+ training_args = RewardConfig(
699
+ output_dir=self.tmp_dir,
700
+ eval_strategy="steps",
701
+ eval_steps=3,
702
+ report_to="none",
703
+ )
704
+ trainer = RewardTrainer(
705
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
706
+ args=training_args,
707
+ train_dataset=dataset["train"],
708
+ eval_dataset=dataset["test"],
709
+ compute_metrics=dummy_compute_metrics,
710
+ )
711
+
712
+ trainer.train()
713
+
714
+ assert trainer.state.log_history[-2]["eval_my_metric"] == 0.123
715
+
716
+ # In practice, this test is the same as `test_train`, since gradient checkpointing is enabled by default in
717
+ # `RewardTrainer`. We keep it as a regression guard: if the default ever changes, we still explicitly test gradient
718
+ # checkpointing, which has caused issues in the past.
719
+ def test_train_with_gradient_checkpointing(self):
720
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
721
+
722
+ training_args = RewardConfig(output_dir=self.tmp_dir, gradient_checkpointing=True, report_to="none")
723
+ trainer = RewardTrainer(
724
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
725
+ args=training_args,
726
+ train_dataset=dataset,
727
+ )
728
+
729
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
730
+
731
+ trainer.train()
732
+
733
+ assert trainer.state.log_history[-1]["train_loss"] is not None
734
+
735
+ # Check that the params have changed
736
+ for n, param in previous_trainable_params.items():
737
+ new_param = trainer.model.get_parameter(n)
738
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
739
+
740
+ @pytest.mark.parametrize("use_reentrant", [True, False])
741
+ def test_train_with_gradient_checkpointing_reentrant(self, use_reentrant):
742
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
743
+
744
+ training_args = RewardConfig(
745
+ output_dir=self.tmp_dir,
746
+ gradient_checkpointing=True,
747
+ gradient_checkpointing_kwargs={"use_reentrant": use_reentrant},
748
+ report_to="none",
749
+ )
750
+ trainer = RewardTrainer(
751
+ model="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
752
+ args=training_args,
753
+ train_dataset=dataset,
754
+ )
755
+
756
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
757
+
758
+ trainer.train()
759
+
760
+ assert trainer.state.log_history[-1]["train_loss"] is not None
761
+
762
+ # Check that the params have changed
763
+ for n, param in previous_trainable_params.items():
764
+ new_param = trainer.model.get_parameter(n)
765
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
766
+
767
+ def test_tag_added(self):
768
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
769
+
770
+ trainer = RewardTrainer(
771
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
772
+ train_dataset=dataset,
773
+ )
774
+
775
+ for tag in ["reward-trainer", "trl"]:
776
+ assert tag in trainer.model.model_tags
777
+
778
+ @require_peft
779
+ def test_tag_added_peft(self):
780
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
781
+
782
+ trainer = RewardTrainer(
783
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
784
+ train_dataset=dataset,
785
+ peft_config=LoraConfig(),
786
+ )
787
+
788
+ for tag in ["reward-trainer", "trl"]:
789
+ assert tag in trainer.model.model_tags
790
+
791
+ def test_train_with_margin(self):
792
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
793
+
794
+ def add_margin(example):
795
+ # dummy margin based on the length of the chosen summary
796
+ return {"margin": len(example["chosen"])}
797
+
798
+ dataset = dataset.map(add_margin)
799
+
800
+ training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
801
+ trainer = RewardTrainer(
802
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
803
+ args=training_args,
804
+ train_dataset=dataset,
805
+ )
806
+
807
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
808
+
809
+ trainer.train()
810
+
811
+ assert trainer.state.log_history[-1]["train_loss"] is not None
812
+
813
+ # Check that the params have changed
814
+ for n, param in previous_trainable_params.items():
815
+ new_param = trainer.model.get_parameter(n)
816
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
817
+
818
+ def test_train_with_center_rewards_coefficient(self):
819
+ dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
820
+
821
+ training_args = RewardConfig(output_dir=self.tmp_dir, center_rewards_coefficient=0.01, report_to="none")
822
+ trainer = RewardTrainer(
823
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
824
+ args=training_args,
825
+ train_dataset=dataset,
826
+ )
827
+
828
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
829
+
830
+ trainer.train()
831
+
832
+ assert trainer.state.log_history[-1]["train_loss"] is not None
833
+
834
+ # Check that the params have changed
835
+ for n, param in previous_trainable_params.items():
836
+ new_param = trainer.model.get_parameter(n)
837
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rewards.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 threading
16
+
17
+ from trl.rewards import accuracy_reward, get_soft_overlong_punishment, reasoning_accuracy_reward, think_format_reward
18
+
19
+ from .testing_utils import TrlTestCase, require_math_latex
20
+
21
+
22
+ class TestThinkFormatReward(TrlTestCase):
23
+ def test_valid_format(self):
24
+ completions = [
25
+ "<think>This is my reasoning.</think>This is my answer.", # Simple, one-line reasoning
26
+ "<think>\nThis is my reasoning.\n</think>\nThis is my answer.", # Multiline reasoning
27
+ "<think>\nThis is\nmy reasoning.\n</think>\nThis is my answer.", # Multiline reasoning
28
+ "<think>\nThis is <some tag> my reasoning.</think>\nThis is my answer.", # Reasoning including other tags
29
+ "<think></think>\nThis is my answer.", # Empty reasoning
30
+ ]
31
+ completions = [[{"content": completion}] for completion in completions]
32
+ expected_rewards = [1.0, 1.0, 1.0, 1.0, 1.0] # All should be valid
33
+ rewards = think_format_reward(completions)
34
+ assert rewards == expected_rewards
35
+
36
+ def test_invalid_format(self):
37
+ completions = [
38
+ "<think>\nThis is my reasoning.\nThis is my answer.", # No closing </think>
39
+ "<think>This is my reasoning.\nThis is my answer.", # No closing </think>
40
+ "This is my reasoning. This is my answer.", # No <think> tags
41
+ "This is my reasoning.\nThis is my answer.", # No <think> tags
42
+ "This is my reasoning.</think>\nThis is my answer.", # No opening <think>
43
+ "This is my reasoning.</think>This is my answer.", # No opening <think>
44
+ "This<think>is my reasoning.</think>\nThis is my answer.", # <think> tag in the middle
45
+ "<think>This is<think>my reasoning.</think></think>This is my answer.", # Nested <think> tags
46
+ "<think>This is</think>\nmy\n<think>reasoning.</think>\nThis is my answer.", # Multiline <think>
47
+ ]
48
+ completions = [[{"content": completion}] for completion in completions]
49
+ expected_rewards = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] # All should be invalid
50
+ rewards = think_format_reward(completions)
51
+ assert rewards == expected_rewards
52
+
53
+ def test_mixed_format(self):
54
+ completions = [
55
+ "<think>This is my reasoning.</think>This is my answer.", # Valid
56
+ "<think>\nThis is my reasoning.\n</think>\nThis is my answer.", # Valid
57
+ "<think>This is my reasoning.\nThis is my answer.", # Invalid
58
+ "This is my reasoning. This is my answer.", # Invalid
59
+ ]
60
+ completions = [[{"content": completion}] for completion in completions]
61
+ expected_rewards = [1.0, 1.0, 0.0, 0.0]
62
+ rewards = think_format_reward(completions)
63
+ assert rewards == expected_rewards
64
+
65
+
66
+ class TestSoftOverlongPunishmentReward:
67
+ def test_soft_overlong_punishment_short_completion(self):
68
+ """Test soft overlong punishment reward function with a short completion."""
69
+ # length 50, with max=100 and soft cache=20, reward should be 0.
70
+ reward_fn = get_soft_overlong_punishment(max_completion_len=100, soft_punish_cache=20)
71
+ completion_ids = [[1] * 50] # 50 <= 80
72
+ rewards = reward_fn(completion_ids=completion_ids)
73
+ assert rewards == [0]
74
+
75
+ def test_soft_overlong_punishment_long_completion(self):
76
+ """Test soft overlong punishment reward function with a longer than max completion."""
77
+ # 110 > 100, reward should be -1.
78
+ reward_fn = get_soft_overlong_punishment(max_completion_len=100, soft_punish_cache=20)
79
+ completion_ids = [[1] * 110]
80
+ rewards = reward_fn(completion_ids)
81
+ assert rewards == [-1]
82
+
83
+ def test_soft_overlong_punishment_intermediate_completion(self):
84
+ """Test soft overlong punishment reward function for intermediate length completion."""
85
+ reward_fn = get_soft_overlong_punishment(max_completion_len=100, soft_punish_cache=20)
86
+ completion_ids = [[1] * 90] # 90 is between 80 and 100
87
+ rewards = reward_fn(completion_ids)
88
+ assert round(abs(rewards[0] - -0.5), 4) == 0
89
+
90
+
91
+ class TestAccuracyReward:
92
+ @require_math_latex
93
+ def test_accuracy_reward_correct_answer(self):
94
+ """Test accuracy_reward with a correct answer."""
95
+ completion = [[{"content": r"\boxed{\frac{63}{400}}"}], [{"content": r"\boxed{\frac{63}{400}}"}]]
96
+ solution = [r"\frac{63}{400}", "63/400"]
97
+ rewards = accuracy_reward(completion, solution)
98
+ assert rewards[0] == 1.0
99
+ assert rewards[1] == 1.0
100
+
101
+ @require_math_latex
102
+ def test_accuracy_reward_wrong_answer(self):
103
+ """Test accuracy_reward with an incorrect answer."""
104
+ completion = [[{"content": r"\boxed{\frac{64}{400}}"}]]
105
+ solution = [r"\frac{63}{400}"]
106
+ rewards = accuracy_reward(completion, solution)
107
+ assert rewards[0] == 0.0
108
+
109
+ @require_math_latex
110
+ def test_accuracy_reward_wrong_answer_no_latex(self):
111
+ """Test accuracy_reward with an incorrect answer and gold solution with no latex."""
112
+ completion = [[{"content": r"\boxed{3}"}]]
113
+ solution = ["6"]
114
+ rewards = accuracy_reward(completion, solution)
115
+ assert rewards[0] == 0.0
116
+
117
+ @require_math_latex
118
+ def test_accuracy_reward_unparsable_gold(self):
119
+ """Test accuracy_reward with an unparsable gold solution."""
120
+ completion = [
121
+ [{"content": "Answer is forty two."}],
122
+ [{"content": r"Some other content. \boxed{43}."}],
123
+ ]
124
+ solution = [
125
+ "Answer is forty two.",
126
+ "Answer is forty three.",
127
+ ]
128
+ rewards = accuracy_reward(completion, solution)
129
+ assert rewards[0] is None
130
+ assert rewards[1] is None
131
+
132
+ @require_math_latex
133
+ def test_accuracy_reward_in_worker_thread(self):
134
+ """Test that accuracy_reward works when called from a non-main thread."""
135
+ completions = [[{"content": r"\boxed{\frac{1}{3}}"}]]
136
+ solutions = [r"\frac{1}{3}"]
137
+ results = []
138
+ exceptions = []
139
+
140
+ def target():
141
+ try:
142
+ results.extend(accuracy_reward(completions, solutions))
143
+ except Exception as e:
144
+ exceptions.append(e)
145
+
146
+ t = threading.Thread(target=target)
147
+ t.start()
148
+ t.join()
149
+
150
+ assert not exceptions, f"accuracy_reward raised in worker thread: {exceptions[0]}"
151
+ assert results == [1.0]
152
+
153
+
154
+ class TestReasoningAccuracyReward:
155
+ @require_math_latex
156
+ def test_correct_answer_yields_unit_reward(self):
157
+ completions = [
158
+ [{"content": r"<think> Reasoning content </think> \boxed{\frac{63}{400}}"}],
159
+ [{"content": r"Reasoning content </think> \boxed{\frac{63}{400}}"}],
160
+ ]
161
+ solutions = [r"\frac{63}{400}", r"\frac{63}{400}"]
162
+ rewards = reasoning_accuracy_reward(completions, solutions)
163
+ assert rewards[0] == 1.0
164
+ assert rewards[1] == 1.0
165
+
166
+ @require_math_latex
167
+ def test_correct_answer_with_custom_tags_yields_unit_reward(self):
168
+ completions = [
169
+ [{"content": r"<REASONING_START> Reasoning content </REASONING_END> \boxed{\frac{63}{400}}"}],
170
+ ]
171
+ solutions = [
172
+ r"\frac{63}{400}",
173
+ ]
174
+ rewards = reasoning_accuracy_reward(completions, solutions, reasoning_delimiters=["</REASONING_END>"])
175
+ assert rewards[0] == 1.0
176
+
177
+ @require_math_latex
178
+ def test_incorrect_answer_yields_zero_reward(self):
179
+ completion = [[{"content": r"<think> Reasoning content </think> \boxed{\frac{64}{400}}"}]]
180
+ solution = [r"\frac{63}{400}"]
181
+ rewards = reasoning_accuracy_reward(completion, solution)
182
+ assert rewards[0] == 0.0
183
+
184
+ @require_math_latex
185
+ def test_correct_answer_in_reasoning_yields_zero_reward(self):
186
+ completions = [
187
+ [{"content": r"<think> My answer is \boxed{42} </think> Some other text."}],
188
+ [{"content": r"<think> The answer is \boxed{42} </think> Here's a wrong answer: \boxed{43}."}],
189
+ ]
190
+ solutions = [r"\boxed{42}", r"\boxed{42}"]
191
+ rewards = reasoning_accuracy_reward(completions, solutions)
192
+ assert rewards[0] == 0.0
193
+ assert rewards[1] == 0.0
194
+
195
+ @require_math_latex
196
+ def test_incomplete_reasoning_yields_zero_reward(self):
197
+ completions = [
198
+ [{"content": r"<think> Incomplete reasoning without closing tag"}],
199
+ [{"content": r"Correct answer \frac{63}{400} but completely missing reasoning content"}],
200
+ ]
201
+ solutions = [r"\frac{63}{400}", r"\frac{63}{400}"]
202
+ rewards = reasoning_accuracy_reward(completions, solutions)
203
+ assert rewards[0] == 0.0
204
+ assert rewards[1] == 0.0
205
+
206
+ @require_math_latex
207
+ def test_unparsable_gold_solution_yields_none_reward(self):
208
+ completions = [
209
+ [{"content": r"<think> Reasoning content </think> \boxed{42}"}],
210
+ ]
211
+ solutions = [
212
+ "forty two",
213
+ ]
214
+ rewards = reasoning_accuracy_reward(completions, solutions)
215
+ assert rewards[0] is None
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rich_progress_callback.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import torch.nn as nn
17
+ from datasets import Dataset
18
+ from transformers import Trainer, TrainingArguments
19
+
20
+ from trl.trainer.callbacks import RichProgressCallback
21
+
22
+ from .testing_utils import TrlTestCase, require_rich
23
+
24
+
25
+ class DummyModel(nn.Module):
26
+ def __init__(self):
27
+ super().__init__()
28
+ self.a = nn.Parameter(torch.tensor(1.0))
29
+
30
+ def forward(self, x):
31
+ return self.a * x
32
+
33
+
34
+ @require_rich
35
+ class TestRichProgressCallback(TrlTestCase):
36
+ def setup_method(self):
37
+ self.dummy_model = DummyModel()
38
+ self.dummy_train_dataset = Dataset.from_list([{"x": 1.0, "y": 2.0}] * 5)
39
+ self.dummy_val_dataset = Dataset.from_list([{"x": 1.0, "y": 2.0}] * 101)
40
+
41
+ def test_rich_progress_callback_logging(self):
42
+ training_args = TrainingArguments(
43
+ output_dir=self.tmp_dir,
44
+ per_device_eval_batch_size=2,
45
+ per_device_train_batch_size=2,
46
+ num_train_epochs=4,
47
+ eval_strategy="steps",
48
+ eval_steps=1,
49
+ logging_strategy="steps",
50
+ logging_steps=1,
51
+ save_strategy="no",
52
+ report_to="none",
53
+ disable_tqdm=True,
54
+ )
55
+ callbacks = [RichProgressCallback()]
56
+ trainer = Trainer(
57
+ model=self.dummy_model,
58
+ train_dataset=self.dummy_train_dataset,
59
+ eval_dataset=self.dummy_val_dataset,
60
+ args=training_args,
61
+ callbacks=callbacks,
62
+ )
63
+
64
+ trainer.train()
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_rloo_trainer.py ADDED
@@ -0,0 +1,1767 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 unittest.mock import patch
16
+
17
+ import pytest
18
+ import torch
19
+ import transformers
20
+ from datasets import load_dataset
21
+ from packaging.version import Version
22
+ from transformers import (
23
+ AutoModelForCausalLM,
24
+ AutoModelForImageTextToText,
25
+ AutoModelForSequenceClassification,
26
+ AutoTokenizer,
27
+ )
28
+ from transformers.utils import is_peft_available
29
+
30
+ from trl import RLOOConfig, RLOOTrainer
31
+
32
+ from .testing_utils import TrlTestCase, require_peft, require_vision, require_vllm
33
+
34
+
35
+ if is_peft_available():
36
+ from peft import LoraConfig, get_peft_model
37
+
38
+
39
+ class TestRLOOTrainer(TrlTestCase):
40
+ def test_init_minimal(self):
41
+ # Test that RLOOTrainer can be instantiated with only model, reward_model and train_dataset
42
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
43
+ RLOOTrainer(
44
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
45
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
46
+ train_dataset=dataset,
47
+ )
48
+
49
+ @pytest.mark.parametrize(
50
+ "model_id",
51
+ [
52
+ "trl-internal-testing/tiny-Cohere2ForCausalLM",
53
+ pytest.param(
54
+ "trl-internal-testing/tiny-Glm4MoeForCausalLM",
55
+ marks=pytest.mark.skipif(
56
+ Version(transformers.__version__) < Version("5.0.0"),
57
+ reason="GLM4 tokenizer requires transformers>=5.0.0",
58
+ ),
59
+ ),
60
+ "trl-internal-testing/tiny-GptOssForCausalLM",
61
+ "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
62
+ "trl-internal-testing/tiny-Qwen3MoeForCausalLM",
63
+ pytest.param(
64
+ "trl-internal-testing/tiny-NemotronHForCausalLM-nano",
65
+ marks=pytest.mark.skipif(
66
+ Version(transformers.__version__) < Version("5.7.0"),
67
+ reason="Nemotron 3 gradient checkpointing requires transformers>=5.7.0 (see transformers#45625)",
68
+ ),
69
+ ),
70
+ ],
71
+ )
72
+ def test_train(self, model_id):
73
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
74
+
75
+ training_args = RLOOConfig(
76
+ output_dir=self.tmp_dir,
77
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
78
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
79
+ num_generations=3, # reduce the number of generations to reduce memory usage
80
+ max_completion_length=8, # reduce the completion length to reduce memory usage
81
+ report_to="none",
82
+ )
83
+ trainer = RLOOTrainer(
84
+ model=model_id,
85
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
86
+ args=training_args,
87
+ train_dataset=dataset,
88
+ )
89
+
90
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
91
+
92
+ trainer.train()
93
+
94
+ assert trainer.state.log_history[-1]["train_loss"] is not None
95
+
96
+ # Check that the params have changed
97
+ for n, param in previous_trainable_params.items():
98
+ new_param = trainer.model.get_parameter(n)
99
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
100
+
101
+ @pytest.mark.parametrize("config_name", ["standard_prompt_only", "conversational_prompt_only"])
102
+ def test_train_dataset_format(self, config_name):
103
+ dataset = load_dataset("trl-internal-testing/zen", config_name, split="train")
104
+
105
+ training_args = RLOOConfig(
106
+ output_dir=self.tmp_dir,
107
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
108
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
109
+ num_generations=3, # reduce the number of generations to reduce memory usage
110
+ max_completion_length=8, # reduce the completion length to reduce memory usage
111
+ report_to="none",
112
+ )
113
+ trainer = RLOOTrainer(
114
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
115
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
116
+ args=training_args,
117
+ train_dataset=dataset,
118
+ )
119
+
120
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
121
+
122
+ trainer.train()
123
+
124
+ assert trainer.state.log_history[-1]["train_loss"] is not None
125
+
126
+ # Check that the params have changed
127
+ for n, param in previous_trainable_params.items():
128
+ new_param = trainer.model.get_parameter(n)
129
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
130
+
131
+ def test_train_with_eval(self):
132
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only")
133
+
134
+ training_args = RLOOConfig(
135
+ output_dir=self.tmp_dir,
136
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
137
+ per_device_eval_batch_size=3, # reduce the batch size to reduce memory usage
138
+ num_generations=3, # reduce the number of generations to reduce memory usage
139
+ max_completion_length=8, # reduce the completion length to reduce memory usage
140
+ eval_strategy="steps",
141
+ eval_steps=2,
142
+ report_to="none",
143
+ )
144
+ trainer = RLOOTrainer(
145
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
146
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
147
+ args=training_args,
148
+ train_dataset=dataset["train"],
149
+ eval_dataset=dataset["test"],
150
+ )
151
+
152
+ trainer.train()
153
+
154
+ def test_train_with_num_generations_eval(self):
155
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only")
156
+
157
+ training_args = RLOOConfig(
158
+ output_dir=self.tmp_dir,
159
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
160
+ per_device_eval_batch_size=3, # reduce the batch size to reduce memory usage
161
+ num_generations=3, # reduce the number of generations to reduce memory usage
162
+ max_completion_length=8, # reduce the completion length to reduce memory usage
163
+ num_generations_eval=1,
164
+ eval_strategy="steps",
165
+ eval_steps=2,
166
+ report_to="none",
167
+ )
168
+ trainer = RLOOTrainer(
169
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
170
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
171
+ args=training_args,
172
+ train_dataset=dataset["train"],
173
+ eval_dataset=dataset["test"],
174
+ )
175
+
176
+ trainer.train()
177
+
178
+ def test_train_multiple_iterations(self):
179
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
180
+
181
+ training_args = RLOOConfig(
182
+ output_dir=self.tmp_dir,
183
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
184
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
185
+ num_generations=3, # reduce the number of generations to reduce memory usage
186
+ max_completion_length=8, # reduce the completion length to reduce memory usage
187
+ num_iterations=2,
188
+ report_to="none",
189
+ )
190
+ trainer = RLOOTrainer(
191
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
192
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
193
+ args=training_args,
194
+ train_dataset=dataset,
195
+ )
196
+
197
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
198
+
199
+ trainer.train()
200
+
201
+ assert trainer.state.log_history[-1]["train_loss"] is not None
202
+
203
+ # Check that the params have changed
204
+ for n, param in previous_trainable_params.items():
205
+ new_param = trainer.model.get_parameter(n)
206
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
207
+
208
+ @require_peft
209
+ def test_train_peft_config(self):
210
+ model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32")
211
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
212
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
213
+
214
+ training_args = RLOOConfig(
215
+ output_dir=self.tmp_dir,
216
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
217
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
218
+ num_generations=3, # reduce the number of generations to reduce memory usage
219
+ max_completion_length=8, # reduce the completion length to reduce memory usage
220
+ report_to="none",
221
+ )
222
+ trainer = RLOOTrainer(
223
+ model=model,
224
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
225
+ args=training_args,
226
+ train_dataset=dataset,
227
+ peft_config=LoraConfig(),
228
+ )
229
+
230
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
231
+
232
+ trainer.train()
233
+
234
+ assert trainer.state.log_history[-1]["train_loss"] is not None
235
+
236
+ # Check that the peft params have changed and the base model params have not changed
237
+ for n, param in previous_trainable_params.items():
238
+ new_param = trainer.model.get_parameter(n)
239
+ if n in base_param_names: # We expect the base model params to be the same
240
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
241
+ elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
242
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
243
+
244
+ @require_peft
245
+ def test_train_peft_model(self):
246
+ model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32")
247
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
248
+ lora_config = LoraConfig()
249
+ model = get_peft_model(model, lora_config)
250
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
251
+
252
+ training_args = RLOOConfig(
253
+ output_dir=self.tmp_dir,
254
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
255
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
256
+ num_generations=3, # reduce the number of generations to reduce memory usage
257
+ max_completion_length=8, # reduce the completion length to reduce memory usage
258
+ report_to="none",
259
+ )
260
+ trainer = RLOOTrainer(
261
+ model=model,
262
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
263
+ args=training_args,
264
+ train_dataset=dataset,
265
+ )
266
+
267
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
268
+
269
+ trainer.train()
270
+
271
+ assert trainer.state.log_history[-1]["train_loss"] is not None
272
+
273
+ # Check that the peft params have changed and the base model params have not changed
274
+ for n, param in previous_trainable_params.items():
275
+ new_param = trainer.model.get_parameter(n)
276
+ if n in base_param_names: # We expect the base model params to be the same
277
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
278
+ elif "base_layer" not in n and "ref" not in n: # and the peft params to be different (except base and ref)
279
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
280
+
281
+ # In practice, this test is the same as `test_train_peft_config`, since gradient checkpointing is enabled by
282
+ # default in `RLOOTrainer`. We keep it as a regression guard: if the default ever changes, we still explicitly test
283
+ # PEFT + gradient checkpointing, which has caused issues in the past.
284
+ @require_peft
285
+ def test_train_peft_with_gradient_checkpointing(self):
286
+ model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32")
287
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
288
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
289
+
290
+ training_args = RLOOConfig(
291
+ output_dir=self.tmp_dir,
292
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
293
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
294
+ num_generations=3, # reduce the number of generations to reduce memory usage
295
+ max_completion_length=8, # reduce the completion length to reduce memory usage
296
+ gradient_checkpointing=True, # enable gradient checkpointing
297
+ report_to="none",
298
+ )
299
+ trainer = RLOOTrainer(
300
+ model=model,
301
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
302
+ args=training_args,
303
+ train_dataset=dataset,
304
+ peft_config=LoraConfig(),
305
+ )
306
+
307
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
308
+
309
+ trainer.train()
310
+
311
+ assert trainer.state.log_history[-1]["train_loss"] is not None
312
+
313
+ # Check that the peft params have changed and the base model params have not changed
314
+ for n, param in previous_trainable_params.items():
315
+ new_param = trainer.model.get_parameter(n)
316
+ if n in base_param_names: # We expect the base model params to be the same
317
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
318
+ elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
319
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
320
+
321
+ def test_train_different_reward_model(self):
322
+ # Use a reward model different from the model: different chat template, tokenization, etc.
323
+ dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train")
324
+ reward_model_id = "trl-internal-testing/tiny-LlamaForSequenceClassification-3.2"
325
+ reward_model = AutoModelForSequenceClassification.from_pretrained(reward_model_id)
326
+ reward_tokenizer = AutoTokenizer.from_pretrained(reward_model_id)
327
+ # By default, the trainer uses the eos token as the padding token. However, for Llama models, the eos token
328
+ # appears in the chat template. Using it as a pad token disrupts the reward calculation, as the calculation
329
+ # considers the score of the last token before the first pad token. To ensure correct reward calculations,
330
+ # we use a separate pad token instead.
331
+ reward_tokenizer.pad_token = "<|finetune_right_pad_id|>"
332
+
333
+ training_args = RLOOConfig(
334
+ output_dir=self.tmp_dir,
335
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
336
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
337
+ num_generations=3, # reduce the number of generations to reduce memory usage
338
+ max_completion_length=8, # reduce the completion length to reduce memory usage
339
+ report_to="none",
340
+ )
341
+ trainer = RLOOTrainer(
342
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
343
+ reward_funcs=reward_model,
344
+ args=training_args,
345
+ train_dataset=dataset,
346
+ reward_processing_classes=reward_tokenizer,
347
+ )
348
+
349
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
350
+
351
+ trainer.train()
352
+
353
+ assert trainer.state.log_history[-1]["train_loss"] is not None
354
+
355
+ # Check that the params have changed
356
+ for n, param in previous_trainable_params.items():
357
+ new_param = trainer.model.get_parameter(n)
358
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
359
+
360
+ def test_train_reward_func_standard(self):
361
+ # Test if trainer can handle reward function with standard format
362
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
363
+
364
+ def reward_func(completions, **kwargs):
365
+ """Reward function that rewards longer completions."""
366
+ return [float(len(completion)) for completion in completions]
367
+
368
+ training_args = RLOOConfig(
369
+ output_dir=self.tmp_dir,
370
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
371
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
372
+ num_generations=3, # reduce the number of generations to reduce memory usage
373
+ max_completion_length=8, # reduce the completion length to reduce memory usage
374
+ report_to="none",
375
+ )
376
+ trainer = RLOOTrainer(
377
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
378
+ reward_funcs=reward_func,
379
+ args=training_args,
380
+ train_dataset=dataset,
381
+ )
382
+
383
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
384
+
385
+ trainer.train()
386
+
387
+ assert trainer.state.log_history[-1]["train_loss"] is not None
388
+
389
+ # Check that the params have changed
390
+ for n, param in previous_trainable_params.items():
391
+ new_param = trainer.model.get_parameter(n)
392
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
393
+
394
+ def test_train_reward_func_conversational(self):
395
+ # Test if trainer can handle reward function with conversational format
396
+ dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train")
397
+
398
+ def reward_func(completions, **kwargs):
399
+ """Reward function that gives higher scores to longer completion content."""
400
+ completion_contents = [completion[0]["content"] for completion in completions]
401
+ return [float(len(content)) for content in completion_contents]
402
+
403
+ training_args = RLOOConfig(
404
+ output_dir=self.tmp_dir,
405
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
406
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
407
+ num_generations=3, # reduce the number of generations to reduce memory usage
408
+ max_completion_length=8, # reduce the completion length to reduce memory usage
409
+ report_to="none",
410
+ )
411
+ trainer = RLOOTrainer(
412
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
413
+ reward_funcs=reward_func,
414
+ args=training_args,
415
+ train_dataset=dataset,
416
+ )
417
+
418
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
419
+
420
+ trainer.train()
421
+
422
+ assert trainer.state.log_history[-1]["train_loss"] is not None
423
+
424
+ # Check that the params have changed
425
+ for n, param in previous_trainable_params.items():
426
+ new_param = trainer.model.get_parameter(n)
427
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
428
+
429
+ def test_train_multiple_reward_funcs(self):
430
+ # Test that RLOOTrainer can be instantiated with multiple reward functions
431
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
432
+
433
+ def reward_func1(completions, **kwargs):
434
+ """Reward function that rewards longer completions."""
435
+ return [float(len(completion)) for completion in completions]
436
+
437
+ def reward_func2(completions, **kwargs):
438
+ """Reward function that rewards completions with more unique letters."""
439
+ return [float(len(set(completion))) for completion in completions]
440
+
441
+ training_args = RLOOConfig(
442
+ output_dir=self.tmp_dir,
443
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
444
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
445
+ num_generations=3, # reduce the number of generations to reduce memory usage
446
+ max_completion_length=8, # reduce the completion length to reduce memory usage
447
+ report_to="none",
448
+ )
449
+ trainer = RLOOTrainer(
450
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
451
+ reward_funcs=[reward_func1, reward_func2],
452
+ args=training_args,
453
+ train_dataset=dataset,
454
+ )
455
+
456
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
457
+
458
+ trainer.train()
459
+
460
+ assert trainer.state.log_history[-1]["train_loss"] is not None
461
+
462
+ # Check that the params have changed
463
+ for n, param in previous_trainable_params.items():
464
+ new_param = trainer.model.get_parameter(n)
465
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
466
+
467
+ def test_train_sync_and_async_reward_funcs(self):
468
+ # Test that RLOOTrainer can be instantiated with multiple reward functions one of which is async
469
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
470
+
471
+ def sync_reward_func1(completions, **kwargs):
472
+ """Reward function that rewards longer completions."""
473
+ return [float(len(completion)) for completion in completions]
474
+
475
+ def sync_reward_func2(completions, **kwargs):
476
+ return [1 for _ in completions]
477
+
478
+ async def async_reward_func(completions, **kwargs):
479
+ """Async Reward function that rewards completions with more unique letters."""
480
+ return [float(len(set(completion))) for completion in completions]
481
+
482
+ training_args = RLOOConfig(
483
+ output_dir=self.tmp_dir,
484
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
485
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
486
+ num_generations=3, # reduce the number of generations to reduce memory usage
487
+ max_completion_length=8, # reduce the completion length to reduce memory usage
488
+ report_to="none",
489
+ )
490
+ trainer = RLOOTrainer(
491
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
492
+ reward_funcs=[sync_reward_func1, sync_reward_func2, async_reward_func],
493
+ args=training_args,
494
+ train_dataset=dataset,
495
+ )
496
+
497
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
498
+
499
+ trainer.train()
500
+
501
+ assert trainer.state.log_history[-1]["train_loss"] is not None
502
+
503
+ # Check that the params have changed
504
+ for n, param in previous_trainable_params.items():
505
+ new_param = trainer.model.get_parameter(n)
506
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
507
+
508
+ def test_train_multiple_reward_funcs_with_None_output(self):
509
+ """Test that a valid math reward function is processed correctly while the code reward function returns None."""
510
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
511
+
512
+ def applicable_reward_func(completions, **kwargs):
513
+ """A reward function that rewards longer completions."""
514
+ return [float(len(completion)) for completion in completions]
515
+
516
+ def non_applicable_reward_func(completions, **kwargs):
517
+ """A reward function that returns None for all inputs, as it is not applicable to this sample."""
518
+ return [None] * len(completions)
519
+
520
+ training_args = RLOOConfig(
521
+ output_dir=self.tmp_dir,
522
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
523
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
524
+ num_generations=3, # reduce the number of generations to reduce memory usage
525
+ max_completion_length=8, # reduce the completion length to reduce memory usage
526
+ report_to="none",
527
+ )
528
+
529
+ trainer = RLOOTrainer(
530
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
531
+ reward_funcs=[
532
+ applicable_reward_func,
533
+ non_applicable_reward_func,
534
+ ], # One applicable, one non applicable
535
+ args=training_args,
536
+ train_dataset=dataset,
537
+ )
538
+
539
+ previous_trainable_params = {
540
+ n: param.clone() for n, param in trainer.model.named_parameters() if param.requires_grad
541
+ }
542
+
543
+ trainer.train()
544
+
545
+ assert trainer.state.log_history[-1]["train_loss"] is not None
546
+
547
+ # Check that the params have changed
548
+ for n, param in previous_trainable_params.items():
549
+ new_param = trainer.model.get_parameter(n)
550
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
551
+
552
+ def test_train_multiple_reward_funcs_with_weights(self):
553
+ """Test that RLOOTrainer can handle multiple reward functions with weights."""
554
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
555
+
556
+ def reward_func1(completions, **kwargs):
557
+ """Reward function that rewards longer completions."""
558
+ return [float(len(completion)) for completion in completions]
559
+
560
+ def reward_func2(completions, **kwargs):
561
+ """Reward function that rewards completions with more unique letters."""
562
+ return [float(len(set(completion))) for completion in completions]
563
+
564
+ training_args = RLOOConfig(
565
+ output_dir=self.tmp_dir,
566
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
567
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
568
+ num_generations=3, # reduce the number of generations to reduce memory usage
569
+ max_completion_length=8, # reduce the completion length to reduce memory usage
570
+ report_to="none",
571
+ reward_weights=[0.7, 0.3], # weight of reward_func1 and reward_func2 respectively
572
+ )
573
+ trainer = RLOOTrainer(
574
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
575
+ reward_funcs=[reward_func1, reward_func2],
576
+ args=training_args,
577
+ train_dataset=dataset,
578
+ )
579
+
580
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
581
+
582
+ trainer.train()
583
+
584
+ # Check that training logs contain both reward metrics
585
+ assert trainer.state.log_history[-1]["train_loss"] is not None
586
+ assert "rewards/reward_func1/mean" in trainer.state.log_history[-1]
587
+ assert "rewards/reward_func1/std" in trainer.state.log_history[-1]
588
+ assert "rewards/reward_func2/mean" in trainer.state.log_history[-1]
589
+ assert "rewards/reward_func2/std" in trainer.state.log_history[-1]
590
+
591
+ # Check that the params have changed
592
+ for n, param in previous_trainable_params.items():
593
+ new_param = trainer.model.get_parameter(n)
594
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
595
+
596
+ def test_reward_metric_reflects_reward_weights(self):
597
+ """Test that the logged 'reward' metric uses reward_weights, not an unweighted sum."""
598
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
599
+
600
+ def constant_reward_1(completions, **kwargs):
601
+ return [1.0] * len(completions)
602
+
603
+ def constant_reward_0(completions, **kwargs):
604
+ return [0.0] * len(completions)
605
+
606
+ training_args = RLOOConfig(
607
+ output_dir=self.tmp_dir,
608
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
609
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
610
+ num_generations=3, # reduce the number of generations to reduce memory usage
611
+ max_completion_length=8, # reduce the completion length to reduce memory usage
612
+ report_to="none",
613
+ reward_weights=[0.7, 0.3],
614
+ )
615
+ trainer = RLOOTrainer(
616
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
617
+ reward_funcs=[constant_reward_1, constant_reward_0],
618
+ args=training_args,
619
+ train_dataset=dataset,
620
+ )
621
+
622
+ trainer.train()
623
+
624
+ log = trainer.state.log_history[-1]
625
+ # With reward_weights=[0.7, 0.3] and rewards [1.0, 0.0]:
626
+ # weighted reward = 0.7*1.0 + 0.3*0.0 = 0.7
627
+ # unweighted reward = 1.0 + 0.0 = 1.0
628
+ assert abs(log["reward"] - 0.7) < 1e-5, (
629
+ f"Expected logged reward to be ~0.7 (weighted), got {log['reward']}. "
630
+ "The reward metric should reflect reward_weights."
631
+ )
632
+
633
+ def test_train_multiple_mixed_reward_funcs(self):
634
+ # Test if the trainer can handle a mix of reward functions and reward models
635
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
636
+
637
+ def reward_func(completions, **kwargs):
638
+ """Reward function that rewards longer completions."""
639
+ return [float(len(completion)) for completion in completions]
640
+
641
+ training_args = RLOOConfig(
642
+ output_dir=self.tmp_dir,
643
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
644
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
645
+ num_generations=3, # reduce the number of generations to reduce memory usage
646
+ max_completion_length=8, # reduce the completion length to reduce memory usage
647
+ report_to="none",
648
+ )
649
+ trainer = RLOOTrainer(
650
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
651
+ reward_funcs=[reward_func, "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"],
652
+ args=training_args,
653
+ train_dataset=dataset,
654
+ )
655
+
656
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
657
+
658
+ trainer.train()
659
+
660
+ assert trainer.state.log_history[-1]["train_loss"] is not None
661
+
662
+ # Check that the params have changed
663
+ for n, param in previous_trainable_params.items():
664
+ new_param = trainer.model.get_parameter(n)
665
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
666
+
667
+ def test_train_reward_func_additional_column(self):
668
+ # Test if trainer can handle reward function that rely on additional columns in the dataset
669
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
670
+
671
+ # Add a column to the dataset (dummy example, the column could be anything)
672
+ some_values = list(range(len(dataset)))
673
+ dataset = dataset.add_column("some_values", some_values)
674
+
675
+ def reward_func(completions, some_values, **kwargs):
676
+ """Reward function that rewards completions with lengths closer to the values in some_values."""
677
+ return [
678
+ float(abs(len(completion) - value)) for completion, value in zip(completions, some_values, strict=True)
679
+ ]
680
+
681
+ training_args = RLOOConfig(
682
+ output_dir=self.tmp_dir,
683
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
684
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
685
+ num_generations=3, # reduce the number of generations to reduce memory usage
686
+ max_completion_length=8, # reduce the completion length to reduce memory usage
687
+ report_to="none",
688
+ )
689
+ trainer = RLOOTrainer(
690
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
691
+ reward_funcs=reward_func,
692
+ args=training_args,
693
+ train_dataset=dataset,
694
+ )
695
+
696
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
697
+
698
+ trainer.train()
699
+
700
+ assert trainer.state.log_history[-1]["train_loss"] is not None
701
+
702
+ # Check that the params have changed
703
+ for n, param in previous_trainable_params.items():
704
+ new_param = trainer.model.get_parameter(n)
705
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
706
+
707
+ def test_train_with_sync_ref_model(self):
708
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
709
+
710
+ training_args = RLOOConfig(
711
+ output_dir=self.tmp_dir,
712
+ beta=0.1, # ensure ref model is created so sync can update it
713
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
714
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
715
+ num_generations=3, # reduce the number of generations to reduce memory usage
716
+ max_completion_length=8, # reduce the completion length to reduce memory usage
717
+ sync_ref_model=True,
718
+ ref_model_sync_steps=2, # reduce sync steps to ensure a sync happens
719
+ report_to="none",
720
+ )
721
+ trainer = RLOOTrainer(
722
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
723
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
724
+ args=training_args,
725
+ train_dataset=dataset,
726
+ )
727
+
728
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
729
+ assert trainer.ref_model is not None
730
+ previous_ref_params = {n: param.clone() for n, param in trainer.ref_model.named_parameters()}
731
+
732
+ trainer.train()
733
+
734
+ assert trainer.state.log_history[-1]["train_loss"] is not None
735
+
736
+ # Check that the params have changed
737
+ for n, param in previous_trainable_params.items():
738
+ new_param = trainer.model.get_parameter(n)
739
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
740
+ new_ref_param = trainer.ref_model.get_parameter(n)
741
+ assert not torch.equal(previous_ref_params[n], new_ref_param), f"Ref Parameter {n} has not changed."
742
+
743
+ def test_train_beta_zero(self):
744
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
745
+ training_args = RLOOConfig(
746
+ output_dir=self.tmp_dir,
747
+ beta=0.0, # set beta to zero value to test the case where the reference model is not used
748
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
749
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
750
+ num_generations=3, # reduce the number of generations to reduce memory usage
751
+ max_completion_length=8, # reduce the completion length to reduce memory usage
752
+ report_to="none",
753
+ )
754
+ trainer = RLOOTrainer(
755
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
756
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
757
+ args=training_args,
758
+ train_dataset=dataset,
759
+ )
760
+
761
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
762
+
763
+ trainer.train()
764
+
765
+ assert trainer.state.log_history[-1]["train_loss"] is not None
766
+
767
+ # Check that the params have changed
768
+ for n, param in previous_trainable_params.items():
769
+ new_param = trainer.model.get_parameter(n)
770
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
771
+
772
+ def test_train_with_pad_to_multiple_of(self):
773
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
774
+
775
+ training_args = RLOOConfig(
776
+ output_dir=self.tmp_dir,
777
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
778
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
779
+ num_generations=3, # reduce the number of generations to reduce memory usage
780
+ max_completion_length=8, # reduce the completion length to reduce memory usage
781
+ pad_to_multiple_of=8,
782
+ report_to="none",
783
+ )
784
+ trainer = RLOOTrainer(
785
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
786
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
787
+ args=training_args,
788
+ train_dataset=dataset,
789
+ )
790
+
791
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
792
+
793
+ trainer.train()
794
+
795
+ assert trainer.state.log_history[-1]["train_loss"] is not None
796
+
797
+ # Check that the params have changed
798
+ for n, param in previous_trainable_params.items():
799
+ new_param = trainer.model.get_parameter(n)
800
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
801
+
802
+ @require_peft
803
+ @require_vllm
804
+ @pytest.mark.skip(reason="We should add a mock for the vLLM server.")
805
+ def test_train_vllm_and_peft(self):
806
+ """Test that training works with vLLM for generation."""
807
+ model = AutoModelForCausalLM.from_pretrained(
808
+ "Qwen/Qwen2.5-0.5B-Instruct", dtype="float32"
809
+ ) # tiny model is too small for vLLM
810
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
811
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
812
+
813
+ training_args = RLOOConfig(
814
+ output_dir=self.tmp_dir,
815
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
816
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
817
+ num_generations=3, # reduce the number of generations to reduce memory usage
818
+ max_completion_length=8, # reduce the completion length to reduce memory usage
819
+ report_to="none",
820
+ use_vllm=True,
821
+ )
822
+ lora_config = LoraConfig(
823
+ target_modules="all-linear",
824
+ # test with non-default modules as it adds extra keys in state_dict that we need to handle
825
+ modules_to_save=["embed_tokens", "lm_head"],
826
+ )
827
+ trainer = RLOOTrainer(
828
+ model=model,
829
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
830
+ args=training_args,
831
+ train_dataset=dataset,
832
+ peft_config=lora_config,
833
+ )
834
+
835
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
836
+
837
+ trainer.train()
838
+
839
+ assert trainer.state.log_history[-1]["train_loss"] is not None
840
+
841
+ # Check that the peft params have changed and the base model params have not changed
842
+ for n, param in previous_trainable_params.items():
843
+ new_param = trainer.model.get_parameter(n)
844
+ if n in base_param_names: # We expect the base model params to be the same
845
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
846
+ elif "base_layer" not in n and "original_module" not in n:
847
+ # We expect the peft params to be different (except for the base layer)
848
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
849
+
850
+ @require_vllm
851
+ @pytest.mark.skip(reason="We should add a mock for the vLLM server.")
852
+ def test_train_vllm_structured_outputs(self):
853
+ """Test that training works with vLLM for generation with structured outputs."""
854
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
855
+
856
+ training_args = RLOOConfig(
857
+ output_dir=self.tmp_dir,
858
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
859
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
860
+ num_generations=3, # reduce the number of generations to reduce memory usage
861
+ max_completion_length=8, # reduce the completion length to reduce memory usage
862
+ report_to="none",
863
+ use_vllm=True,
864
+ vllm_structured_outputs_regex=r"<reasoning>\n.*\n</reasoning>\n<answer>\n.*\n</answer>",
865
+ )
866
+ trainer = RLOOTrainer(
867
+ model="Qwen/Qwen2.5-0.5B-Instruct", # tiny model is too small for vLLM
868
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
869
+ args=training_args,
870
+ train_dataset=dataset,
871
+ )
872
+
873
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
874
+
875
+ trainer.train()
876
+
877
+ assert trainer.state.log_history[-1]["train_loss"] is not None
878
+
879
+ # Check that the params have changed
880
+ for n, param in previous_trainable_params.items():
881
+ new_param = trainer.model.get_parameter(n)
882
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
883
+
884
+ def test_train_with_additional_generation_kwargs(self):
885
+ """Test that training works with additional generation kwargs."""
886
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
887
+
888
+ training_args = RLOOConfig(
889
+ output_dir=self.tmp_dir,
890
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
891
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
892
+ num_generations=3, # reduce the number of generations to reduce memory usage
893
+ max_completion_length=8, # reduce the completion length to reduce memory usage
894
+ report_to="none",
895
+ top_p=0.9,
896
+ top_k=10,
897
+ min_p=0.01,
898
+ repetition_penalty=1.1,
899
+ )
900
+
901
+ trainer = RLOOTrainer(
902
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
903
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
904
+ args=training_args,
905
+ train_dataset=dataset,
906
+ )
907
+
908
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
909
+
910
+ trainer.train()
911
+
912
+ assert trainer.state.log_history[-1]["train_loss"] is not None
913
+
914
+ # Check that the params have changed
915
+ for n, param in previous_trainable_params.items():
916
+ new_param = trainer.model.get_parameter(n)
917
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
918
+
919
+ @require_vllm
920
+ @pytest.mark.skip(reason="We should add a mock for the vLLM server.")
921
+ def test_train_vllm_with_additional_generation_kwargs(self):
922
+ """Test that training works with vLLM and additional generation kwargs."""
923
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
924
+
925
+ training_args = RLOOConfig(
926
+ output_dir=self.tmp_dir,
927
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
928
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
929
+ num_generations=3, # reduce the number of generations to reduce memory usage
930
+ max_completion_length=8, # reduce the completion length to reduce memory usage
931
+ report_to="none",
932
+ use_vllm=True,
933
+ top_p=0.9,
934
+ top_k=10,
935
+ min_p=0.01,
936
+ repetition_penalty=1.1,
937
+ )
938
+
939
+ trainer = RLOOTrainer(
940
+ model="Qwen/Qwen2.5-0.5B-Instruct", # tiny model is too small for vLLM
941
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
942
+ args=training_args,
943
+ train_dataset=dataset,
944
+ )
945
+
946
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
947
+
948
+ trainer.train()
949
+
950
+ assert trainer.state.log_history[-1]["train_loss"] is not None
951
+
952
+ # Check that the params have changed
953
+ for n, param in previous_trainable_params.items():
954
+ new_param = trainer.model.get_parameter(n)
955
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
956
+
957
+ def test_train_with_normalized_advantages(self):
958
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
959
+
960
+ training_args = RLOOConfig(
961
+ output_dir=self.tmp_dir,
962
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
963
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
964
+ num_generations=3, # reduce the number of generations to reduce memory usage
965
+ max_completion_length=8, # reduce the completion length to reduce memory usage
966
+ normalize_advantages=True,
967
+ report_to="none",
968
+ )
969
+ trainer = RLOOTrainer(
970
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
971
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
972
+ args=training_args,
973
+ train_dataset=dataset,
974
+ )
975
+
976
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
977
+
978
+ trainer.train()
979
+
980
+ assert trainer.state.log_history[-1]["train_loss"] is not None
981
+
982
+ # Check that the params have changed
983
+ for n, param in previous_trainable_params.items():
984
+ new_param = trainer.model.get_parameter(n)
985
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
986
+
987
+ def test_train_with_clipped_rewards(self):
988
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
989
+
990
+ training_args = RLOOConfig(
991
+ output_dir=self.tmp_dir,
992
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
993
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
994
+ num_generations=3, # reduce the number of generations to reduce memory usage
995
+ max_completion_length=8, # reduce the completion length to reduce memory usage
996
+ reward_clip_range=(-1, 1),
997
+ report_to="none",
998
+ )
999
+ trainer = RLOOTrainer(
1000
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1001
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
1002
+ args=training_args,
1003
+ train_dataset=dataset,
1004
+ )
1005
+
1006
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1007
+
1008
+ trainer.train()
1009
+
1010
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1011
+
1012
+ # Check that the params have changed
1013
+ for n, param in previous_trainable_params.items():
1014
+ new_param = trainer.model.get_parameter(n)
1015
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
1016
+
1017
+ @patch("transformers.generation.utils.GenerationMixin.generate")
1018
+ def test_train_with_mask_truncated_completions(self, mock_generate):
1019
+ """Test that training works with mask_truncated_completions=True parameter."""
1020
+
1021
+ # We mock the generate method because the model's random weights make it extremely unlikely to produce a
1022
+ # sequence containing the EOS token within the allowed max_completion_length. As a result, all tokens are
1023
+ # masked in the loss, the model doesn't update, and the final check (which verifies the update) fails.
1024
+ def fake_generate(input_ids, **kwargs):
1025
+ # pad_token_id = 151643; eos_token_id = 151645
1026
+ completion_ids = torch.tensor(
1027
+ [
1028
+ [1, 2, 3, 4, 5, 6, 7, 8], # this one is truncated
1029
+ [9, 10, 11, 151645, 151643, 151643, 151643, 151643], # this one contains eos
1030
+ [12, 13, 14, 15, 16, 17, 18, 151645], # particular case, eos is generated just within the limit
1031
+ ],
1032
+ device=input_ids.device,
1033
+ )
1034
+ return torch.cat([input_ids, completion_ids], dim=1)
1035
+
1036
+ mock_generate.side_effect = fake_generate
1037
+
1038
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1039
+
1040
+ training_args = RLOOConfig(
1041
+ output_dir=self.tmp_dir,
1042
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1043
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
1044
+ num_generations=3, # reduce the number of generations to reduce memory usage
1045
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1046
+ mask_truncated_completions=True, # Enable masking of truncated completions
1047
+ report_to="none",
1048
+ )
1049
+ trainer = RLOOTrainer(
1050
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1051
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
1052
+ args=training_args,
1053
+ train_dataset=dataset,
1054
+ )
1055
+
1056
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1057
+
1058
+ trainer.train()
1059
+
1060
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1061
+
1062
+ # Check that the params have changed
1063
+ for n, param in previous_trainable_params.items():
1064
+ new_param = trainer.model.get_parameter(n)
1065
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
1066
+
1067
+ def test_train_with_mask_truncated_completions_all_masked(self):
1068
+ """
1069
+ Test that when all generated completions are truncated (i.e., none contain an EOS token), and
1070
+ mask_truncated_completions=True, the model receives no effective learning signal and therefore does not update
1071
+ its parameters.
1072
+
1073
+ Here, we don't mock the generate method, be we rely on the fact that the model the probability of generating
1074
+ the EOS token is extremely low, so all generated completions are truncated.
1075
+ """
1076
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1077
+
1078
+ training_args = RLOOConfig(
1079
+ output_dir=self.tmp_dir,
1080
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1081
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
1082
+ num_generations=3, # reduce the number of generations to reduce memory usage
1083
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1084
+ mask_truncated_completions=True, # Enable masking of truncated completions
1085
+ report_to="none",
1086
+ )
1087
+ trainer = RLOOTrainer(
1088
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1089
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
1090
+ args=training_args,
1091
+ train_dataset=dataset,
1092
+ )
1093
+
1094
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1095
+
1096
+ trainer.train()
1097
+
1098
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1099
+
1100
+ # Check that the params have changed
1101
+ for n, param in previous_trainable_params.items():
1102
+ new_param = trainer.model.get_parameter(n)
1103
+ assert torch.equal(param, new_param), f"Parameter {n} has changed."
1104
+
1105
+ def test_warning_raised_all_rewards_none(self, caplog):
1106
+ """Test that a proper warning is raised when all rewards are None."""
1107
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1108
+
1109
+ def always_none_reward_func(completions, **kwargs):
1110
+ """Reward function that always returns None."""
1111
+ return [None] * len(completions)
1112
+
1113
+ training_args = RLOOConfig(
1114
+ output_dir=self.tmp_dir,
1115
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1116
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
1117
+ num_generations=3, # reduce the number of generations to reduce memory usage
1118
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1119
+ report_to="none",
1120
+ )
1121
+ trainer = RLOOTrainer(
1122
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1123
+ reward_funcs=always_none_reward_func,
1124
+ args=training_args,
1125
+ train_dataset=dataset,
1126
+ )
1127
+
1128
+ with caplog.at_level("WARNING", logger="trl.trainer.rloo_trainer"):
1129
+ trainer.train()
1130
+
1131
+ expected_warning = "All reward functions returned None for the following kwargs:"
1132
+ assert expected_warning in caplog.text
1133
+
1134
+ def test_train_num_generations_larger_than_batch_size(self):
1135
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1136
+
1137
+ training_args = RLOOConfig(
1138
+ output_dir=self.tmp_dir,
1139
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1140
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
1141
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1142
+ num_generations=6, # the number of generations is larger than the batch size, but
1143
+ gradient_accumulation_steps=2, # gradient accumulation should allow that
1144
+ report_to="none",
1145
+ )
1146
+ trainer = RLOOTrainer(
1147
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1148
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
1149
+ args=training_args,
1150
+ train_dataset=dataset,
1151
+ )
1152
+
1153
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1154
+
1155
+ trainer.train()
1156
+
1157
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1158
+
1159
+ # Check that the params have changed
1160
+ for n, param in previous_trainable_params.items():
1161
+ new_param = trainer.model.get_parameter(n)
1162
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
1163
+
1164
+ def test_train_multiple_dataloader_workers(self):
1165
+ # Pytest/CI often starts background threads before tests run. With Python 3.12, using the default "fork" start
1166
+ # method in a multi-threaded process emits a DeprecationWarning and may deadlock.
1167
+ #
1168
+ # We force "spawn" here to make multiprocessing safe under pytest when DataLoader workers are enabled. This is
1169
+ # test-environment–specific and not required by the training logic itself.
1170
+ #
1171
+ # This means the test does not cover "fork". However, "spawn" is stricter (requires full picklability and clean
1172
+ # state) and avoids fork-after-threads issues that pytest cannot reliably test anyway. Fork-specific behavior,
1173
+ # if needed, should be tested in a clean process outside pytest.
1174
+ torch.multiprocessing.set_start_method("spawn", force=True)
1175
+
1176
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1177
+
1178
+ training_args = RLOOConfig(
1179
+ output_dir=self.tmp_dir,
1180
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1181
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
1182
+ num_generations=3, # reduce the number of generations to reduce memory usage
1183
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1184
+ dataloader_num_workers=2, # use multiple dataloader workers
1185
+ report_to="none",
1186
+ )
1187
+ trainer = RLOOTrainer(
1188
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1189
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
1190
+ args=training_args,
1191
+ train_dataset=dataset,
1192
+ )
1193
+
1194
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1195
+
1196
+ trainer.train()
1197
+
1198
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1199
+
1200
+ # Check that the params have changed
1201
+ for n, param in previous_trainable_params.items():
1202
+ new_param = trainer.model.get_parameter(n)
1203
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
1204
+
1205
+ def test_train_with_generation_kwargs(self):
1206
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1207
+
1208
+ training_args = RLOOConfig(
1209
+ output_dir=self.tmp_dir,
1210
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1211
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
1212
+ num_generations=3, # reduce the number of generations to reduce memory usage
1213
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1214
+ # Pass gen kwargs
1215
+ generation_kwargs={"do_sample": True, "top_k": 50, "num_beams": 2, "length_penalty": -0.1},
1216
+ report_to="none",
1217
+ )
1218
+ trainer = RLOOTrainer(
1219
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1220
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
1221
+ args=training_args,
1222
+ train_dataset=dataset,
1223
+ )
1224
+
1225
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1226
+
1227
+ trainer.train()
1228
+
1229
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1230
+
1231
+ # Check that the params have changed
1232
+ for n, param in previous_trainable_params.items():
1233
+ new_param = trainer.model.get_parameter(n)
1234
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
1235
+
1236
+ def test_train_with_reward_func_accessing_trainer_state(self):
1237
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1238
+
1239
+ def reward_func(completions, **kwargs):
1240
+ trainer_state = kwargs.get("trainer_state")
1241
+ assert trainer_state is not None
1242
+ # transformers.TrainerState instance should have a `global_step` property.
1243
+ assert hasattr(trainer_state, "global_step")
1244
+ return [float(len(set(completion))) for completion in completions]
1245
+
1246
+ training_args = RLOOConfig(
1247
+ output_dir=self.tmp_dir,
1248
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
1249
+ num_generations=3, # reduce the number of generations to reduce memory usage
1250
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1251
+ report_to="none",
1252
+ )
1253
+ trainer = RLOOTrainer(
1254
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1255
+ reward_funcs=reward_func,
1256
+ args=training_args,
1257
+ train_dataset=dataset,
1258
+ )
1259
+ trainer.train()
1260
+
1261
+ def test_train_reward_func_with_log_extra(self):
1262
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1263
+
1264
+ def reward_func(completions, **kwargs):
1265
+ log_extra = kwargs.get("log_extra")
1266
+ assert log_extra is not None
1267
+ log_extra("test_column", [completion[:5] for completion in completions])
1268
+ return [float(len(completion)) for completion in completions]
1269
+
1270
+ training_args = RLOOConfig(
1271
+ output_dir=self.tmp_dir,
1272
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
1273
+ num_generations=3, # reduce the number of generations to reduce memory usage
1274
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1275
+ report_to="none",
1276
+ log_completions=True,
1277
+ )
1278
+ trainer = RLOOTrainer(
1279
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1280
+ reward_funcs=reward_func,
1281
+ args=training_args,
1282
+ train_dataset=dataset,
1283
+ )
1284
+ trainer.train()
1285
+ assert "test_column" in trainer._logs["extra"]
1286
+
1287
+ def test_train_reward_func_with_log_metric(self):
1288
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1289
+
1290
+ def reward_func(completions, **kwargs):
1291
+ log_metric = kwargs.get("log_metric")
1292
+ assert log_metric is not None
1293
+ log_metric("custom_accuracy", 0.75)
1294
+ return [float(len(completion)) for completion in completions]
1295
+
1296
+ training_args = RLOOConfig(
1297
+ output_dir=self.tmp_dir,
1298
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
1299
+ num_generations=3, # reduce the number of generations to reduce memory usage
1300
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1301
+ report_to="none",
1302
+ )
1303
+ trainer = RLOOTrainer(
1304
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1305
+ reward_funcs=reward_func,
1306
+ args=training_args,
1307
+ train_dataset=dataset,
1308
+ )
1309
+ trainer.train()
1310
+ # log_metric appends to _metrics, which gets averaged and merged into log_history
1311
+ logged_keys = {k for entry in trainer.state.log_history for k in entry}
1312
+ assert "custom_accuracy" in logged_keys
1313
+
1314
+ def test_prepare_input_called_with_correct_data(self):
1315
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1316
+ training_args = RLOOConfig(
1317
+ output_dir=self.tmp_dir,
1318
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1319
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1320
+ gradient_accumulation_steps=3, # can be anything in this test
1321
+ # steps_per_generation*per_device_train_batch_size=24 is divisible by num_generations=4
1322
+ steps_per_generation=4,
1323
+ num_generations=4,
1324
+ per_device_train_batch_size=6, # reduce the batch size to reduce memory usage
1325
+ num_iterations=2,
1326
+ shuffle_dataset=False,
1327
+ report_to="none",
1328
+ )
1329
+ trainer = RLOOTrainer(
1330
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1331
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
1332
+ args=training_args,
1333
+ train_dataset=dataset,
1334
+ )
1335
+ # steps_per_generation=4, per_device_train_batch_size=6 and num_generations=4, so we expect a
1336
+ # generation batch of 24 samples (steps_per_generation * per_device_train_batch_size), containing 6
1337
+ # different prompts (steps_per_generation * per_device_train_batch_size // num_generations), each repeated
1338
+ # 4 times (num_generations).
1339
+ expected_first_generation_batch = (
1340
+ [{"prompt": "Beautiful is better than"}] * 4
1341
+ + [{"prompt": "Explicit is"}] * 4
1342
+ + [{"prompt": "Simple is better"}] * 4
1343
+ + [{"prompt": "Complex"}] * 4
1344
+ + [{"prompt": "Flat is better than"}] * 4
1345
+ + [{"prompt": "Sparse is better"}] * 4
1346
+ )
1347
+ expected_second_generation_batch = (
1348
+ [{"prompt": "Readability"}] * 4
1349
+ + [{"prompt": "Special cases aren't special"}] * 4
1350
+ + [{"prompt": "Although practicality beats"}] * 4
1351
+ + [{"prompt": "Errors should never"}] * 4
1352
+ + [{"prompt": "Unless explicitly"}] * 4
1353
+ + [{"prompt": "In the face of ambiguity, refuse"}] * 4
1354
+ )
1355
+
1356
+ with patch.object(RLOOTrainer, "training_step", wraps=trainer.training_step) as mock_prepare:
1357
+ trainer.train()
1358
+ # 3 epochs * 2 iterations * 2 generation batches to cover the dataset * 4 steps_per_generation
1359
+ assert mock_prepare.call_count == 48
1360
+ for i in range(0, 8): # Generation batch repeated 8 times (steps_per_generation*num_iterations)
1361
+ assert mock_prepare.call_args_list[i].args[1] == expected_first_generation_batch
1362
+ for i in range(8, 16):
1363
+ assert mock_prepare.call_args_list[i].args[1] == expected_second_generation_batch
1364
+
1365
+ def test_train_with_chat_template_kwargs(self):
1366
+ dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train")
1367
+
1368
+ training_args = RLOOConfig(
1369
+ output_dir=self.tmp_dir,
1370
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1371
+ per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
1372
+ num_generations=3, # reduce the number of generations to reduce memory usage
1373
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1374
+ report_to="none",
1375
+ chat_template_kwargs={"enable_thinking": False},
1376
+ )
1377
+ trainer = RLOOTrainer(
1378
+ model="trl-internal-testing/tiny-Qwen3ForCausalLM",
1379
+ reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
1380
+ args=training_args,
1381
+ train_dataset=dataset,
1382
+ )
1383
+
1384
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1385
+
1386
+ trainer.train()
1387
+
1388
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1389
+
1390
+ # Check that the params have changed
1391
+ for n, param in previous_trainable_params.items():
1392
+ new_param = trainer.model.get_parameter(n)
1393
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
1394
+
1395
+ def test_mismatched_reward_processing_classes_length(self):
1396
+ """Test that mismatched length between reward_funcs and reward_processing_classes raises error."""
1397
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1398
+
1399
+ # Use two reward models
1400
+ reward_models = [
1401
+ "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
1402
+ "trl-internal-testing/tiny-Qwen3ForSequenceClassification",
1403
+ ]
1404
+
1405
+ # Create a single processing class (tokenizer)
1406
+ single_processing_class = AutoTokenizer.from_pretrained(
1407
+ "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"
1408
+ )
1409
+
1410
+ training_args = RLOOConfig(output_dir=self.tmp_dir, report_to="none")
1411
+
1412
+ with pytest.raises(ValueError, match="must match"):
1413
+ RLOOTrainer(
1414
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1415
+ reward_funcs=reward_models,
1416
+ reward_processing_classes=single_processing_class, # only one, but need two
1417
+ args=training_args,
1418
+ train_dataset=dataset,
1419
+ )
1420
+
1421
+ def test_correct_reward_processing_classes_list(self):
1422
+ """Test that correct list of reward_processing_classes works properly."""
1423
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1424
+
1425
+ # Use two reward models
1426
+ reward_models = [
1427
+ "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
1428
+ "trl-internal-testing/tiny-Qwen3ForSequenceClassification",
1429
+ ]
1430
+
1431
+ # Create processing classes
1432
+ processing_class1 = AutoTokenizer.from_pretrained(
1433
+ "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"
1434
+ )
1435
+ processing_class2 = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3ForSequenceClassification")
1436
+
1437
+ training_args = RLOOConfig(output_dir=self.tmp_dir, report_to="none")
1438
+
1439
+ # Correct list length should work
1440
+ correct_processing_classes = [processing_class1, processing_class2]
1441
+
1442
+ trainer = RLOOTrainer(
1443
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1444
+ reward_funcs=reward_models,
1445
+ reward_processing_classes=correct_processing_classes,
1446
+ args=training_args,
1447
+ train_dataset=dataset,
1448
+ )
1449
+
1450
+ assert len(trainer.reward_processing_classes) == len(reward_models)
1451
+
1452
+ def test_single_reward_model_with_single_processing_class(self):
1453
+ """Test that single reward model with single processing class works."""
1454
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
1455
+
1456
+ # Use single reward model
1457
+ reward_model = "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"
1458
+
1459
+ # Create a single processing class (tokenizer)
1460
+ single_processing_class = AutoTokenizer.from_pretrained(
1461
+ "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"
1462
+ )
1463
+
1464
+ training_args = RLOOConfig(output_dir=self.tmp_dir, report_to="none")
1465
+
1466
+ trainer = RLOOTrainer(
1467
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1468
+ reward_funcs=reward_model,
1469
+ reward_processing_classes=single_processing_class, # single object for single reward model
1470
+ args=training_args,
1471
+ train_dataset=dataset,
1472
+ )
1473
+
1474
+ assert len(trainer.reward_processing_classes) == 1
1475
+ assert trainer.reward_processing_classes[0] == single_processing_class
1476
+
1477
+
1478
+ @require_vision
1479
+ class TestRLOOTrainerVLM(TrlTestCase):
1480
+ @pytest.mark.parametrize(
1481
+ "model_id",
1482
+ [
1483
+ "trl-internal-testing/tiny-Gemma3ForConditionalGeneration",
1484
+ pytest.param(
1485
+ "trl-internal-testing/tiny-Gemma4ForConditionalGeneration",
1486
+ marks=pytest.mark.skipif(
1487
+ Version(transformers.__version__) < Version("5.5.0"),
1488
+ reason="Gemma4 models were introduced in transformers-5.5.0",
1489
+ ),
1490
+ ),
1491
+ "trl-internal-testing/tiny-LlavaNextForConditionalGeneration",
1492
+ "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
1493
+ "trl-internal-testing/tiny-Qwen2VLForConditionalGeneration",
1494
+ pytest.param(
1495
+ "trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink",
1496
+ marks=pytest.mark.skipif(
1497
+ Version(transformers.__version__) < Version("5.2.0"),
1498
+ reason="Qwen3.5 models were introduced in transformers-5.2.0",
1499
+ ),
1500
+ ),
1501
+ pytest.param(
1502
+ "trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6",
1503
+ marks=pytest.mark.skipif(
1504
+ Version(transformers.__version__) < Version("5.2.0"),
1505
+ reason="Qwen3.5 models were introduced in transformers-5.2.0",
1506
+ ),
1507
+ ),
1508
+ # "trl-internal-testing/tiny-SmolVLMForConditionalGeneration", seems not to support bf16 properly
1509
+ ],
1510
+ )
1511
+ def test_train_vlm(self, model_id):
1512
+ dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train")
1513
+
1514
+ def reward_func(completions, **kwargs):
1515
+ """Reward function that rewards longer completions."""
1516
+ return [float(len(completion[0]["content"])) for completion in completions]
1517
+
1518
+ training_args = RLOOConfig(
1519
+ output_dir=self.tmp_dir,
1520
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1521
+ per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
1522
+ num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM
1523
+ # note: num_generations=2 is only suitable for CI testing; production training should use more generations
1524
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1525
+ report_to="none",
1526
+ )
1527
+ trainer = RLOOTrainer(
1528
+ model=model_id,
1529
+ reward_funcs=reward_func,
1530
+ args=training_args,
1531
+ train_dataset=dataset,
1532
+ )
1533
+
1534
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1535
+
1536
+ trainer.train()
1537
+
1538
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1539
+
1540
+ # Check that the params have changed
1541
+ for n, param in previous_trainable_params.items():
1542
+ new_param = trainer.model.get_parameter(n)
1543
+ # LLaVA & LLaVA-Next: vision_feature_layer=-2 leaves the last encoder layer (layers.1) and
1544
+ # post_layernorm (pooler-only path) without gradient by design. Assert they stay frozen — if they
1545
+ # ever start training, the feature-selection plumbing has likely regressed.
1546
+ if model_id in (
1547
+ "trl-internal-testing/tiny-LlavaForConditionalGeneration",
1548
+ "trl-internal-testing/tiny-LlavaNextForConditionalGeneration",
1549
+ ) and ("encoder.layers.1" in n or "post_layernorm" in n):
1550
+ assert torch.equal(param, new_param), f"Param {n} expected frozen by LLaVA design, but changed"
1551
+ else:
1552
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
1553
+
1554
+ def test_train_vlm_with_pad_to_multiple_of(self):
1555
+ # Models like Gemma3 use other forward keyword arguments like token_type_ids that also need to be padded when
1556
+ # using pad_to_multiple_of, so we test that the trainer correctly pads all the necessary inputs in this case.
1557
+ dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train")
1558
+
1559
+ def reward_func(completions, **kwargs):
1560
+ """Reward function that rewards longer completions."""
1561
+ return [float(len(completion[0]["content"])) for completion in completions]
1562
+
1563
+ training_args = RLOOConfig(
1564
+ output_dir=self.tmp_dir,
1565
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1566
+ per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
1567
+ num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM
1568
+ # note: num_generations=2 is only suitable for CI testing; production training should use more generations
1569
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1570
+ pad_to_multiple_of=7,
1571
+ report_to="none",
1572
+ )
1573
+ trainer = RLOOTrainer(
1574
+ model="trl-internal-testing/tiny-Gemma3ForConditionalGeneration",
1575
+ reward_funcs=reward_func,
1576
+ args=training_args,
1577
+ train_dataset=dataset,
1578
+ )
1579
+
1580
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1581
+
1582
+ trainer.train()
1583
+
1584
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1585
+
1586
+ # Check that the params have changed
1587
+ for n, param in previous_trainable_params.items():
1588
+ new_param = trainer.model.get_parameter(n)
1589
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
1590
+
1591
+ @pytest.mark.parametrize(
1592
+ "model_id",
1593
+ [
1594
+ "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
1595
+ ],
1596
+ )
1597
+ def test_train_vlm_beta_non_zero(self, model_id):
1598
+ dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train")
1599
+
1600
+ def reward_func(completions, **kwargs):
1601
+ """Reward function that rewards longer completions."""
1602
+ return [float(len(completion[0]["content"])) for completion in completions]
1603
+
1604
+ training_args = RLOOConfig(
1605
+ output_dir=self.tmp_dir,
1606
+ beta=0.1, # set beta to non-zero value to test the case where the reference model is used
1607
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1608
+ per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
1609
+ num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM
1610
+ # note: num_generations=2 is only suitable for CI testing; production training should use more generations
1611
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1612
+ report_to="none",
1613
+ )
1614
+ trainer = RLOOTrainer(
1615
+ model=model_id,
1616
+ reward_funcs=reward_func,
1617
+ args=training_args,
1618
+ train_dataset=dataset,
1619
+ )
1620
+
1621
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1622
+
1623
+ trainer.train()
1624
+
1625
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1626
+
1627
+ # Check that the params have changed
1628
+ for n, param in previous_trainable_params.items():
1629
+ new_param = trainer.model.get_parameter(n)
1630
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
1631
+
1632
+ @pytest.mark.parametrize(
1633
+ "model_id",
1634
+ [
1635
+ "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
1636
+ ],
1637
+ )
1638
+ @require_peft
1639
+ def test_train_vlm_peft(self, model_id):
1640
+ model = AutoModelForImageTextToText.from_pretrained(model_id, dtype="float32")
1641
+ base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
1642
+ dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train")
1643
+
1644
+ def reward_func(completions, **kwargs):
1645
+ """Reward function that rewards longer completions."""
1646
+ return [float(len(completion[0]["content"])) for completion in completions]
1647
+
1648
+ training_args = RLOOConfig(
1649
+ output_dir=self.tmp_dir,
1650
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1651
+ per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
1652
+ num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM
1653
+ # note: num_generations=2 is only suitable for CI testing; production training should use more generations
1654
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1655
+ report_to="none",
1656
+ )
1657
+ trainer = RLOOTrainer(
1658
+ model=model,
1659
+ reward_funcs=reward_func,
1660
+ args=training_args,
1661
+ train_dataset=dataset,
1662
+ peft_config=LoraConfig(target_modules=["q_proj", "v_proj"]),
1663
+ )
1664
+
1665
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1666
+
1667
+ trainer.train()
1668
+
1669
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1670
+
1671
+ # Check that the peft params have changed and the base model params have not changed
1672
+ for n, param in previous_trainable_params.items():
1673
+ new_param = trainer.model.get_parameter(n)
1674
+ if n in base_param_names: # We expect the base model params to be the same
1675
+ torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
1676
+ elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
1677
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
1678
+
1679
+ @pytest.mark.parametrize(
1680
+ "model_id",
1681
+ [
1682
+ "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
1683
+ "trl-internal-testing/tiny-Gemma3ForConditionalGeneration",
1684
+ pytest.param(
1685
+ "trl-internal-testing/tiny-Gemma4ForConditionalGeneration",
1686
+ marks=pytest.mark.skipif(
1687
+ Version(transformers.__version__) < Version("5.5.0"),
1688
+ reason="Gemma4 models were introduced in transformers-5.5.0",
1689
+ ),
1690
+ ),
1691
+ ],
1692
+ )
1693
+ @require_vllm
1694
+ @pytest.mark.skip(reason="We should add a mock for the vLLM server.")
1695
+ def test_train_vlm_and_vllm(self, model_id) -> None:
1696
+ dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train")
1697
+
1698
+ def reward_func(completions, **kwargs):
1699
+ """Reward function that rewards longer completions."""
1700
+ return [float(len(completion[0]["content"])) for completion in completions]
1701
+
1702
+ training_args = RLOOConfig(
1703
+ output_dir=self.tmp_dir,
1704
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1705
+ per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
1706
+ num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM
1707
+ # note: num_generations=2 is only suitable for CI testing; production training should use more generations
1708
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1709
+ report_to="none",
1710
+ use_vllm=True,
1711
+ vllm_mode="server",
1712
+ )
1713
+ trainer = RLOOTrainer(
1714
+ model=model_id,
1715
+ reward_funcs=reward_func,
1716
+ args=training_args,
1717
+ train_dataset=dataset,
1718
+ )
1719
+
1720
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1721
+
1722
+ trainer.train()
1723
+
1724
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1725
+
1726
+ for n, param in previous_trainable_params.items():
1727
+ new_param = trainer.model.get_parameter(n)
1728
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
1729
+
1730
+ @pytest.mark.parametrize(
1731
+ "model_id",
1732
+ [
1733
+ "trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
1734
+ ],
1735
+ )
1736
+ def test_train_vlm_multi_image(self, model_id):
1737
+ dataset = load_dataset("trl-internal-testing/zen-multi-image", "conversational_prompt_only", split="train")
1738
+
1739
+ def reward_func(completions, **kwargs):
1740
+ """Reward function that rewards longer completions."""
1741
+ return [float(len(completion[0]["content"])) for completion in completions]
1742
+
1743
+ training_args = RLOOConfig(
1744
+ output_dir=self.tmp_dir,
1745
+ learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
1746
+ per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
1747
+ num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM
1748
+ # note: num_generations=2 is only suitable for CI testing; production training should use more generations
1749
+ max_completion_length=8, # reduce the completion length to reduce memory usage
1750
+ report_to="none",
1751
+ )
1752
+ trainer = RLOOTrainer(
1753
+ model=model_id,
1754
+ reward_funcs=reward_func,
1755
+ args=training_args,
1756
+ train_dataset=dataset,
1757
+ )
1758
+
1759
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
1760
+
1761
+ trainer.train()
1762
+
1763
+ assert trainer.state.log_history[-1]["train_loss"] is not None
1764
+
1765
+ for n, param in previous_trainable_params.items():
1766
+ new_param = trainer.model.get_parameter(n)
1767
+ assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_sft_trainer.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_skills.py ADDED
@@ -0,0 +1,578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 pathlib import Path
16
+
17
+ import pytest
18
+
19
+ from trl.skills import install_skill, list_agent_names, list_skills, resolve_target_path, uninstall_skill
20
+ from trl.skills.skills import _get_trl_skills_dir
21
+
22
+
23
+ class TestGetTrlSkillsDir:
24
+ """Tests for _get_trl_skills_dir function."""
25
+
26
+ def test_returns_path_object(self):
27
+ """Test that returns a Path object."""
28
+ skills_dir = _get_trl_skills_dir()
29
+ assert isinstance(skills_dir, Path)
30
+
31
+ def test_directory_exists(self):
32
+ """Test that the returned directory exists."""
33
+ skills_dir = _get_trl_skills_dir()
34
+ assert skills_dir.exists(), f"Skills directory does not exist: {skills_dir}"
35
+
36
+ def test_is_directory(self):
37
+ """Test that the returned path is a directory."""
38
+ skills_dir = _get_trl_skills_dir()
39
+ assert skills_dir.is_dir(), f"Skills path is not a directory: {skills_dir}"
40
+
41
+ def test_contains_skills_module(self):
42
+ """Test that the path ends with 'skills' (the module name)."""
43
+ skills_dir = _get_trl_skills_dir()
44
+ assert skills_dir.name == "skills"
45
+
46
+
47
+ class TestListSkills:
48
+ """Tests for list_skills function."""
49
+
50
+ def test_returns_list(self):
51
+ """Test that list_skills returns a list."""
52
+ skills = list_skills()
53
+ assert isinstance(skills, list)
54
+
55
+ def test_contains_trl_training(self):
56
+ """Test that list_skills includes the trl-training skill."""
57
+ skills = list_skills()
58
+ assert "trl-training" in skills
59
+
60
+ def test_skills_are_sorted(self):
61
+ """Test that skills are returned in sorted order."""
62
+ skills = list_skills()
63
+ assert skills == sorted(skills)
64
+
65
+ def test_with_custom_directory(self, tmp_path):
66
+ """Test list_skills with a custom directory."""
67
+ # Create fake skills
68
+ (tmp_path / "skill1").mkdir()
69
+ (tmp_path / "skill1" / "SKILL.md").write_text("# Skill 1")
70
+ (tmp_path / "skill2").mkdir()
71
+ (tmp_path / "skill2" / "SKILL.md").write_text("# Skill 2")
72
+ (tmp_path / "not-a-skill").mkdir() # No SKILL.md
73
+
74
+ skills = list_skills(tmp_path)
75
+ assert skills == ["skill1", "skill2"]
76
+
77
+ def test_empty_directory(self, tmp_path):
78
+ """Test list_skills with an empty directory."""
79
+ skills = list_skills(tmp_path)
80
+ assert skills == []
81
+
82
+ def test_nonexistent_directory(self, tmp_path):
83
+ """Test list_skills with a non-existent directory."""
84
+ nonexistent = tmp_path / "nonexistent"
85
+ skills = list_skills(nonexistent)
86
+ assert skills == []
87
+
88
+ def test_ignores_files(self, tmp_path):
89
+ """Test that list_skills ignores files, only returns directories."""
90
+ (tmp_path / "skill1").mkdir()
91
+ (tmp_path / "skill1" / "SKILL.md").write_text("# Skill 1")
92
+ (tmp_path / "not-a-skill.txt").write_text("Not a skill")
93
+
94
+ skills = list_skills(tmp_path)
95
+ assert skills == ["skill1"]
96
+
97
+ def test_requires_skill_md(self, tmp_path):
98
+ """Test that directories without SKILL.md are ignored."""
99
+ (tmp_path / "has-skill-md").mkdir()
100
+ (tmp_path / "has-skill-md" / "SKILL.md").write_text("# Valid")
101
+ (tmp_path / "no-skill-md").mkdir()
102
+ (tmp_path / "no-skill-md" / "readme.md").write_text("# Invalid")
103
+
104
+ skills = list_skills(tmp_path)
105
+ assert skills == ["has-skill-md"]
106
+
107
+
108
+ class TestInstallSkill:
109
+ """Tests for install_skill function."""
110
+
111
+ def test_basic_installation(self, tmp_path):
112
+ """Test basic skill installation."""
113
+ target_dir = tmp_path / "target"
114
+
115
+ result = install_skill("trl-training", target_dir)
116
+
117
+ assert result is True
118
+ assert (target_dir / "trl-training").exists()
119
+ assert (target_dir / "trl-training" / "SKILL.md").exists()
120
+
121
+ def test_creates_target_directory(self, tmp_path):
122
+ """Test that install_skill creates the target directory if it doesn't exist."""
123
+ target_dir = tmp_path / "nested" / "target"
124
+
125
+ install_skill("trl-training", target_dir)
126
+
127
+ assert target_dir.exists()
128
+ assert (target_dir / "trl-training").exists()
129
+
130
+ def test_skill_not_found(self, tmp_path):
131
+ """Test that install_skill raises FileNotFoundError for non-existent skill."""
132
+ target_dir = tmp_path / "target"
133
+
134
+ with pytest.raises(FileNotFoundError, match="Skill 'nonexistent' not found"):
135
+ install_skill("nonexistent", target_dir)
136
+
137
+ def test_skill_already_exists_without_force(self, tmp_path):
138
+ """Test that install_skill raises FileExistsError if skill exists and force=False."""
139
+ target_dir = tmp_path / "target"
140
+
141
+ # Install once
142
+ install_skill("trl-training", target_dir)
143
+
144
+ # Try to install again without force
145
+ with pytest.raises(FileExistsError, match="already installed"):
146
+ install_skill("trl-training", target_dir, force=False)
147
+
148
+ def test_force_overwrites_existing(self, tmp_path):
149
+ """Test that install_skill with force=True overwrites existing skill."""
150
+ target_dir = tmp_path / "target"
151
+
152
+ # Install once
153
+ install_skill("trl-training", target_dir)
154
+
155
+ # Modify the installed skill
156
+ marker_file = target_dir / "trl-training" / "marker.txt"
157
+ marker_file.write_text("This should be removed")
158
+
159
+ # Install again with force
160
+ result = install_skill("trl-training", target_dir, force=True)
161
+
162
+ assert result is True
163
+ assert (target_dir / "trl-training").exists()
164
+ assert not marker_file.exists() # Marker should be gone
165
+
166
+ def test_force_overwrites_symlink(self, tmp_path):
167
+ """Test that install_skill with force=True can overwrite a symlink."""
168
+ target_dir = tmp_path / "target"
169
+ target_dir.mkdir()
170
+
171
+ # Create a symlink
172
+ symlink = target_dir / "trl-training"
173
+ symlink.symlink_to(_get_trl_skills_dir() / "trl-training")
174
+
175
+ # Install with force should replace symlink with copy
176
+ result = install_skill("trl-training", target_dir, force=True)
177
+
178
+ assert result is True
179
+ assert (target_dir / "trl-training").exists()
180
+ assert not (target_dir / "trl-training").is_symlink()
181
+
182
+ def test_skill_not_directory(self, tmp_path):
183
+ """Test that install_skill raises ValueError if skill is not a directory."""
184
+ source_dir = tmp_path / "source"
185
+ source_dir.mkdir()
186
+ target_dir = tmp_path / "target"
187
+
188
+ # Create a file instead of directory
189
+ (source_dir / "fake-skill").write_text("not a directory")
190
+
191
+ with pytest.raises(ValueError, match="is not a directory"):
192
+ install_skill("fake-skill", target_dir, source=source_dir)
193
+
194
+ def test_preserves_directory_structure(self, tmp_path):
195
+ """Test that install_skill preserves the skill's directory structure."""
196
+ source_dir = tmp_path / "source"
197
+ target_dir = tmp_path / "target"
198
+
199
+ # Create a skill with subdirectories
200
+ skill_dir = source_dir / "test-skill"
201
+ skill_dir.mkdir(parents=True)
202
+ (skill_dir / "SKILL.md").write_text("# Test")
203
+ (skill_dir / "subdir").mkdir()
204
+ (skill_dir / "subdir" / "file.txt").write_text("content")
205
+
206
+ install_skill("test-skill", target_dir, source=source_dir)
207
+
208
+ assert (target_dir / "test-skill" / "SKILL.md").exists()
209
+ assert (target_dir / "test-skill" / "subdir" / "file.txt").exists()
210
+ assert (target_dir / "test-skill" / "subdir" / "file.txt").read_text() == "content"
211
+
212
+ def test_install_to_same_directory_fails(self, tmp_path):
213
+ """Test that installing to the same directory as source is handled correctly."""
214
+ source_dir = tmp_path / "skills"
215
+ source_dir.mkdir()
216
+
217
+ # Create a skill
218
+ skill_dir = source_dir / "test-skill"
219
+ skill_dir.mkdir()
220
+ (skill_dir / "SKILL.md").write_text("# Test")
221
+
222
+ # Try to install to same directory (should fail with exists error)
223
+ with pytest.raises(FileExistsError):
224
+ install_skill("test-skill", source_dir, source=source_dir, force=False)
225
+
226
+
227
+ class TestUninstallSkill:
228
+ """Tests for uninstall_skill function."""
229
+
230
+ def test_basic_uninstallation(self, tmp_path):
231
+ """Test basic skill uninstallation."""
232
+ target_dir = tmp_path / "target"
233
+
234
+ # Install first
235
+ install_skill("trl-training", target_dir)
236
+ assert (target_dir / "trl-training").exists()
237
+
238
+ # Uninstall
239
+ result = uninstall_skill("trl-training", target_dir)
240
+
241
+ assert result is True
242
+ assert not (target_dir / "trl-training").exists()
243
+
244
+ def test_skill_not_installed(self, tmp_path):
245
+ """Test that uninstall_skill raises FileNotFoundError for non-existent skill."""
246
+ target_dir = tmp_path / "target"
247
+ target_dir.mkdir()
248
+
249
+ with pytest.raises(FileNotFoundError, match="not installed"):
250
+ uninstall_skill("nonexistent", target_dir)
251
+
252
+ def test_uninstall_from_nonexistent_directory(self, tmp_path):
253
+ """Test uninstall_skill when target directory doesn't exist."""
254
+ target_dir = tmp_path / "nonexistent"
255
+
256
+ with pytest.raises(FileNotFoundError, match="not installed"):
257
+ uninstall_skill("trl-training", target_dir)
258
+
259
+ def test_uninstall_removes_all_contents(self, tmp_path):
260
+ """Test that uninstall removes the entire skill directory."""
261
+ source_dir = tmp_path / "source"
262
+ target_dir = tmp_path / "target"
263
+
264
+ # Create a skill with multiple files
265
+ skill_dir = source_dir / "test-skill"
266
+ skill_dir.mkdir(parents=True)
267
+ (skill_dir / "SKILL.md").write_text("# Test")
268
+ (skill_dir / "file1.txt").write_text("content1")
269
+ (skill_dir / "subdir").mkdir()
270
+ (skill_dir / "subdir" / "file2.txt").write_text("content2")
271
+
272
+ # Install and uninstall
273
+ install_skill("test-skill", target_dir, source=source_dir)
274
+ uninstall_skill("test-skill", target_dir)
275
+
276
+ assert not (target_dir / "test-skill").exists()
277
+ # Target directory itself should still exist
278
+ assert target_dir.exists()
279
+
280
+ def test_uninstall_doesnt_affect_other_skills(self, tmp_path):
281
+ """Test that uninstalling one skill doesn't affect others."""
282
+ source_dir = tmp_path / "source"
283
+ target_dir = tmp_path / "target"
284
+
285
+ # Create two skills
286
+ for skill_name in ["skill1", "skill2"]:
287
+ skill_dir = source_dir / skill_name
288
+ skill_dir.mkdir(parents=True)
289
+ (skill_dir / "SKILL.md").write_text(f"# {skill_name}")
290
+
291
+ # Install both
292
+ install_skill("skill1", target_dir, source=source_dir)
293
+ install_skill("skill2", target_dir, source=source_dir)
294
+
295
+ # Uninstall one
296
+ uninstall_skill("skill1", target_dir)
297
+
298
+ # Check that only skill1 is removed
299
+ assert not (target_dir / "skill1").exists()
300
+ assert (target_dir / "skill2").exists()
301
+
302
+
303
+ class TestIntegration:
304
+ """Integration tests for skills functions."""
305
+
306
+ def test_full_workflow(self, tmp_path):
307
+ """Test complete install -> list -> uninstall workflow."""
308
+ source_dir = tmp_path / "source"
309
+ target_dir = tmp_path / "target"
310
+
311
+ # Create skills
312
+ for i in range(3):
313
+ skill_dir = source_dir / f"skill{i}"
314
+ skill_dir.mkdir(parents=True)
315
+ (skill_dir / "SKILL.md").write_text(f"# Skill {i}")
316
+
317
+ # List available skills
318
+ available = list_skills(target=source_dir)
319
+ assert available == ["skill0", "skill1", "skill2"]
320
+
321
+ # Install skills
322
+ for skill in available:
323
+ install_skill(skill, target_dir, source=source_dir)
324
+
325
+ # List installed skills
326
+ installed_dirs = [d.name for d in target_dir.iterdir() if d.is_dir()]
327
+ assert sorted(installed_dirs) == ["skill0", "skill1", "skill2"]
328
+
329
+ # Uninstall one skill
330
+ uninstall_skill("skill1", target_dir)
331
+
332
+ # Verify
333
+ installed_dirs = [d.name for d in target_dir.iterdir() if d.is_dir()]
334
+ assert sorted(installed_dirs) == ["skill0", "skill2"]
335
+
336
+ def test_install_uninstall_cycle(self, tmp_path):
337
+ """Test that we can install and uninstall the same skill multiple times."""
338
+ source_dir = tmp_path / "source"
339
+ target_dir = tmp_path / "target"
340
+
341
+ # Create skill
342
+ skill_dir = source_dir / "test-skill"
343
+ skill_dir.mkdir(parents=True)
344
+ (skill_dir / "SKILL.md").write_text("# Test")
345
+
346
+ # Install -> Uninstall -> Install -> Uninstall
347
+ for _ in range(2):
348
+ install_skill("test-skill", target_dir, source=source_dir)
349
+ assert (target_dir / "test-skill").exists()
350
+
351
+ uninstall_skill("test-skill", target_dir)
352
+ assert not (target_dir / "test-skill").exists()
353
+
354
+ def test_force_reinstall_workflow(self, tmp_path):
355
+ """Test the workflow of using force to update an installed skill."""
356
+ source_dir = tmp_path / "source"
357
+ target_dir = tmp_path / "target"
358
+
359
+ # Create initial skill version
360
+ skill_dir = source_dir / "test-skill"
361
+ skill_dir.mkdir(parents=True)
362
+ (skill_dir / "SKILL.md").write_text("# Version 1")
363
+
364
+ # Install
365
+ install_skill("test-skill", target_dir, source=source_dir)
366
+ assert (target_dir / "test-skill" / "SKILL.md").read_text() == "# Version 1"
367
+
368
+ # Update source skill
369
+ (skill_dir / "SKILL.md").write_text("# Version 2")
370
+
371
+ # Force reinstall
372
+ install_skill("test-skill", target_dir, source=source_dir, force=True)
373
+ assert (target_dir / "test-skill" / "SKILL.md").read_text() == "# Version 2"
374
+
375
+
376
+ class TestEdgeCases:
377
+ """Tests for edge cases and special scenarios."""
378
+
379
+ def test_skill_with_special_characters_in_name(self, tmp_path):
380
+ """Test handling skills with special characters in names."""
381
+ source_dir = tmp_path / "source"
382
+ target_dir = tmp_path / "target"
383
+
384
+ # Create skill with hyphens and underscores (common in skill names)
385
+ skill_name = "test-skill_v2"
386
+ skill_dir = source_dir / skill_name
387
+ skill_dir.mkdir(parents=True)
388
+ (skill_dir / "SKILL.md").write_text("# Test")
389
+
390
+ # Should work fine
391
+ install_skill(skill_name, target_dir, source=source_dir)
392
+ assert (target_dir / skill_name).exists()
393
+
394
+ uninstall_skill(skill_name, target_dir)
395
+ assert not (target_dir / skill_name).exists()
396
+
397
+ def test_empty_skill_directory(self, tmp_path):
398
+ """Test installing a skill with only SKILL.md (no other files)."""
399
+ source_dir = tmp_path / "source"
400
+ target_dir = tmp_path / "target"
401
+
402
+ skill_dir = source_dir / "minimal-skill"
403
+ skill_dir.mkdir(parents=True)
404
+ (skill_dir / "SKILL.md").write_text("# Minimal")
405
+
406
+ install_skill("minimal-skill", target_dir, source=source_dir)
407
+
408
+ assert (target_dir / "minimal-skill" / "SKILL.md").exists()
409
+ # Should only contain SKILL.md
410
+ files = list((target_dir / "minimal-skill").iterdir())
411
+ assert len(files) == 1
412
+ assert files[0].name == "SKILL.md"
413
+
414
+ def test_skill_with_hidden_files(self, tmp_path):
415
+ """Test that hidden files are preserved during installation."""
416
+ source_dir = tmp_path / "source"
417
+ target_dir = tmp_path / "target"
418
+
419
+ skill_dir = source_dir / "test-skill"
420
+ skill_dir.mkdir(parents=True)
421
+ (skill_dir / "SKILL.md").write_text("# Test")
422
+ (skill_dir / ".hidden").write_text("hidden content")
423
+
424
+ install_skill("test-skill", target_dir, source=source_dir)
425
+
426
+ assert (target_dir / "test-skill" / ".hidden").exists()
427
+ assert (target_dir / "test-skill" / ".hidden").read_text() == "hidden content"
428
+
429
+ def test_list_skills_with_symlinks(self, tmp_path):
430
+ """Test that list_skills handles symlinked skill directories."""
431
+ source_dir = tmp_path / "source"
432
+ skills_dir = tmp_path / "skills"
433
+ skills_dir.mkdir()
434
+
435
+ # Create a real skill
436
+ skill_dir = source_dir / "real-skill"
437
+ skill_dir.mkdir(parents=True)
438
+ (skill_dir / "SKILL.md").write_text("# Real")
439
+
440
+ # Create symlink to it
441
+ (skills_dir / "linked-skill").symlink_to(skill_dir)
442
+
443
+ # list_skills should include symlinked skills if they have SKILL.md
444
+ skills = list_skills(target=skills_dir)
445
+ assert "linked-skill" in skills
446
+
447
+
448
+ class TestListAgentNames:
449
+ """Tests for list_agent_names function."""
450
+
451
+ def test_returns_list(self):
452
+ """Test that list_agent_names returns a list."""
453
+ agents = list_agent_names()
454
+ assert isinstance(agents, list)
455
+
456
+ def test_contains_expected_agents(self):
457
+ """Test that list includes expected agent names."""
458
+ agents = list_agent_names()
459
+ assert "agents" in agents
460
+ assert "claude" in agents
461
+
462
+
463
+ class TestResolveTargetPath:
464
+ """Tests for resolve_target_path function."""
465
+
466
+ def test_resolve_agent_name_project_scope(self):
467
+ """Test resolving agent name with project scope."""
468
+ path = resolve_target_path("claude", "project")
469
+ assert path == Path("./.claude/skills").expanduser().resolve()
470
+
471
+ def test_resolve_agent_name_global_scope(self):
472
+ """Test resolving agent name with global scope."""
473
+ path = resolve_target_path("claude", "global")
474
+ assert path == Path("~/.claude/skills").expanduser().resolve()
475
+
476
+ def test_resolve_custom_path_string(self):
477
+ """Test resolving custom path as string."""
478
+ path = resolve_target_path("/custom/path", "project")
479
+ assert path == Path("/custom/path").resolve()
480
+
481
+ def test_resolve_custom_path_object(self):
482
+ """Test resolving Path object."""
483
+ custom = Path("/custom/path")
484
+ path = resolve_target_path(custom, "project")
485
+ assert path == Path("/custom/path").resolve()
486
+
487
+ def test_resolve_path_with_tilde(self):
488
+ """Test that tilde expansion works."""
489
+ path = resolve_target_path("~/my/skills", "project")
490
+ assert path == Path("~/my/skills").expanduser().resolve()
491
+ assert "~" not in str(path)
492
+
493
+ def test_all_predefined_agents(self):
494
+ """Test that all predefined agents can be resolved."""
495
+ for agent in list_agent_names():
496
+ for scope in ["project", "global"]:
497
+ path = resolve_target_path(agent, scope)
498
+ assert isinstance(path, Path)
499
+ assert path.is_absolute()
500
+
501
+ def test_invalid_scope_for_predefined_agent(self):
502
+ """Test invalid scope raises ValueError for predefined agents."""
503
+ with pytest.raises(ValueError, match="Invalid scope"):
504
+ resolve_target_path("claude", "invalid")
505
+
506
+
507
+ class TestHighLevelAPI:
508
+ """Tests for the new high-level API (target/scope instead of Path)."""
509
+
510
+ def test_list_skills_with_target_string(self, tmp_path):
511
+ """Test list_skills with target as string (custom path)."""
512
+ # Create skills in target
513
+ (tmp_path / "skill1").mkdir()
514
+ (tmp_path / "skill1" / "SKILL.md").write_text("# Skill 1")
515
+
516
+ skills = list_skills(target=str(tmp_path), scope="project")
517
+ assert skills == ["skill1"]
518
+
519
+ def test_list_skills_with_target_path(self, tmp_path):
520
+ """Test list_skills with target as Path object."""
521
+ (tmp_path / "skill1").mkdir()
522
+ (tmp_path / "skill1" / "SKILL.md").write_text("# Skill 1")
523
+
524
+ skills = list_skills(target=tmp_path, scope="project")
525
+ assert skills == ["skill1"]
526
+
527
+ def test_list_skills_without_target(self):
528
+ """Test list_skills without target lists TRL's built-in skills."""
529
+ skills = list_skills()
530
+ assert isinstance(skills, list)
531
+ assert "trl-training" in skills
532
+
533
+ def test_install_skill_with_target_string(self, tmp_path):
534
+ """Test install_skill with target as string."""
535
+ result = install_skill("trl-training", target=str(tmp_path), scope="project")
536
+ assert result is True
537
+ assert (tmp_path / "trl-training").exists()
538
+
539
+ def test_install_skill_with_target_path(self, tmp_path):
540
+ """Test install_skill with target as Path object."""
541
+ result = install_skill("trl-training", target=tmp_path, scope="project")
542
+ assert result is True
543
+ assert (tmp_path / "trl-training").exists()
544
+
545
+ def test_install_skill_with_force(self, tmp_path):
546
+ """Test install_skill with force parameter."""
547
+ install_skill("trl-training", target=tmp_path)
548
+ # Install again with force
549
+ result = install_skill("trl-training", target=tmp_path, force=True)
550
+ assert result is True
551
+
552
+ def test_uninstall_skill_with_target_string(self, tmp_path):
553
+ """Test uninstall_skill with target as string."""
554
+ install_skill("trl-training", target=tmp_path)
555
+ result = uninstall_skill("trl-training", target=str(tmp_path), scope="project")
556
+ assert result is True
557
+ assert not (tmp_path / "trl-training").exists()
558
+
559
+ def test_uninstall_skill_with_target_path(self, tmp_path):
560
+ """Test uninstall_skill with target as Path object."""
561
+ install_skill("trl-training", target=tmp_path)
562
+ result = uninstall_skill("trl-training", target=tmp_path, scope="project")
563
+ assert result is True
564
+ assert not (tmp_path / "trl-training").exists()
565
+
566
+ def test_install_with_custom_source(self, tmp_path):
567
+ """Test install_skill with custom source parameter."""
568
+ source_dir = tmp_path / "source"
569
+ target_dir = tmp_path / "target"
570
+
571
+ # Create custom skill
572
+ skill_dir = source_dir / "custom-skill"
573
+ skill_dir.mkdir(parents=True)
574
+ (skill_dir / "SKILL.md").write_text("# Custom")
575
+
576
+ result = install_skill("custom-skill", target=target_dir, source=source_dir)
577
+ assert result is True
578
+ assert (target_dir / "custom-skill").exists()
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_skills_cli.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse
16
+
17
+ import pytest
18
+
19
+ from trl.skills import install_skill
20
+ from trl.skills.cli import add_skills_subcommands, cmd_install, cmd_list, cmd_uninstall
21
+
22
+
23
+ class TestCLICommands:
24
+ """Tests for CLI command handlers."""
25
+
26
+ def test_cmd_list_without_target(self, capsys):
27
+ """Test cmd_list without target (lists TRL skills)."""
28
+ args = argparse.Namespace(target=None, scope="project")
29
+
30
+ result = cmd_list(args)
31
+
32
+ captured = capsys.readouterr()
33
+ assert result == 0
34
+ assert "TRL (available for installation)" in captured.out
35
+ assert "trl-training" in captured.out
36
+ assert "Use 'trl skills install" in captured.out
37
+
38
+ def test_cmd_list_with_target(self, tmp_path, capsys):
39
+ """Test cmd_list with target (lists installed skills)."""
40
+ # Install a skill
41
+ install_skill("trl-training", target=tmp_path)
42
+
43
+ args = argparse.Namespace(target=str(tmp_path), scope="project")
44
+ result = cmd_list(args)
45
+
46
+ captured = capsys.readouterr()
47
+ assert result == 0
48
+ assert "trl-training" in captured.out
49
+ assert str(tmp_path) in captured.out
50
+
51
+ def test_cmd_list_empty_target(self, tmp_path, capsys):
52
+ """Test cmd_list with empty target directory."""
53
+ args = argparse.Namespace(target=str(tmp_path), scope="project")
54
+
55
+ result = cmd_list(args)
56
+
57
+ captured = capsys.readouterr()
58
+ assert result == 0
59
+ assert "No skills installed" in captured.out
60
+
61
+ def test_cmd_install_single_skill(self, tmp_path, capsys):
62
+ """Test cmd_install with single skill."""
63
+ args = argparse.Namespace(skill="trl-training", all=False, target=str(tmp_path), scope="project", force=False)
64
+
65
+ result = cmd_install(args)
66
+
67
+ captured = capsys.readouterr()
68
+ assert result == 0
69
+ assert "✓" in captured.out
70
+ assert "1/1 skills installed" in captured.out
71
+ assert (tmp_path / "trl-training").exists()
72
+
73
+ def test_cmd_install_all_skills(self, tmp_path, capsys):
74
+ """Test cmd_install with --all flag."""
75
+ args = argparse.Namespace(skill=None, all=True, target=str(tmp_path), scope="project", force=False)
76
+
77
+ result = cmd_install(args)
78
+
79
+ captured = capsys.readouterr()
80
+ assert result == 0
81
+ assert "✓" in captured.out
82
+ assert "installed successfully" in captured.out
83
+ assert (tmp_path / "trl-training").exists()
84
+
85
+ def test_cmd_install_no_skill_or_all(self, capsys):
86
+ """Test cmd_install without skill name or --all flag."""
87
+ args = argparse.Namespace(skill=None, all=False, target="/tmp/test", scope="project", force=False)
88
+
89
+ result = cmd_install(args)
90
+
91
+ captured = capsys.readouterr()
92
+ assert result == 1
93
+ assert "Error: Either provide a skill name or use --all" in captured.out
94
+
95
+ def test_cmd_install_both_skill_and_all(self, capsys):
96
+ """Test cmd_install with both skill name and --all (error)."""
97
+ args = argparse.Namespace(skill="trl-training", all=True, target="/tmp/test", scope="project", force=False)
98
+
99
+ result = cmd_install(args)
100
+
101
+ captured = capsys.readouterr()
102
+ assert result == 1
103
+ assert "Cannot specify both" in captured.out
104
+
105
+ def test_cmd_install_nonexistent_skill(self, tmp_path, capsys):
106
+ """Test cmd_install with non-existent skill."""
107
+ args = argparse.Namespace(skill="nonexistent", all=False, target=str(tmp_path), scope="project", force=False)
108
+
109
+ result = cmd_install(args)
110
+
111
+ captured = capsys.readouterr()
112
+ assert result == 1
113
+ assert "✗" in captured.out
114
+ assert "0/1 skills installed" in captured.out
115
+
116
+ def test_cmd_install_already_exists(self, tmp_path, capsys):
117
+ """Test cmd_install when skill already exists without force."""
118
+ # Install once
119
+ install_skill("trl-training", target=tmp_path)
120
+
121
+ args = argparse.Namespace(skill="trl-training", all=False, target=str(tmp_path), scope="project", force=False)
122
+
123
+ result = cmd_install(args)
124
+
125
+ captured = capsys.readouterr()
126
+ assert result == 1
127
+ assert "✗" in captured.out
128
+ assert "Use --force to overwrite" in captured.out
129
+
130
+ def test_cmd_install_with_force(self, tmp_path, capsys):
131
+ """Test cmd_install with --force to overwrite."""
132
+ # Install once
133
+ install_skill("trl-training", target=tmp_path)
134
+
135
+ args = argparse.Namespace(skill="trl-training", all=False, target=str(tmp_path), scope="project", force=True)
136
+
137
+ result = cmd_install(args)
138
+
139
+ captured = capsys.readouterr()
140
+ assert result == 0
141
+ assert "✓" in captured.out
142
+ assert "1/1 skills installed" in captured.out
143
+
144
+ def test_cmd_uninstall_success(self, tmp_path, capsys):
145
+ """Test cmd_uninstall with installed skill."""
146
+ # Install first
147
+ install_skill("trl-training", target=tmp_path)
148
+
149
+ args = argparse.Namespace(skill="trl-training", target=str(tmp_path), scope="project")
150
+
151
+ result = cmd_uninstall(args)
152
+
153
+ captured = capsys.readouterr()
154
+ assert result == 0
155
+ assert "✓" in captured.out
156
+ assert "has been removed" in captured.out
157
+ assert not (tmp_path / "trl-training").exists()
158
+
159
+ def test_cmd_uninstall_not_installed(self, tmp_path, capsys):
160
+ """Test cmd_uninstall when skill is not installed."""
161
+ args = argparse.Namespace(skill="nonexistent", target=str(tmp_path), scope="project")
162
+
163
+ result = cmd_uninstall(args)
164
+
165
+ captured = capsys.readouterr()
166
+ assert result == 1
167
+ assert "✗" in captured.out
168
+ assert "Error:" in captured.out
169
+
170
+ def test_cmd_install_creates_target_directory(self, tmp_path, capsys):
171
+ """Test cmd_install creates target directory if it doesn't exist."""
172
+ # Custom path that doesn't exist yet
173
+ target_path = tmp_path / "new_directory"
174
+ assert not target_path.exists()
175
+
176
+ args = argparse.Namespace(
177
+ skill="trl-training", all=False, target=str(target_path), scope="project", force=False
178
+ )
179
+
180
+ result = cmd_install(args)
181
+
182
+ captured = capsys.readouterr()
183
+ assert result == 0
184
+ assert "✓" in captured.out
185
+ assert target_path.exists()
186
+
187
+ def test_cmd_uninstall_invalid_target(self, capsys):
188
+ """Test cmd_uninstall with non-existent path."""
189
+ args = argparse.Namespace(skill="trl-training", target="/nonexistent/invalid/path", scope="project")
190
+
191
+ result = cmd_uninstall(args)
192
+
193
+ captured = capsys.readouterr()
194
+ assert result == 1
195
+ assert "✗" in captured.out
196
+
197
+
198
+ class TestCLIArgumentParsing:
199
+ """Tests for CLI argument parsing setup."""
200
+
201
+ def test_add_skills_subcommands_creates_parsers(self):
202
+ """Test that add_skills_subcommands creates the expected subparsers."""
203
+ parser = argparse.ArgumentParser()
204
+ subparsers = parser.add_subparsers(dest="command")
205
+
206
+ add_skills_subcommands(subparsers)
207
+
208
+ # Test that we can parse expected commands
209
+ args = parser.parse_args(["list"])
210
+ assert args.command == "list"
211
+ assert hasattr(args, "func")
212
+
213
+ args = parser.parse_args(["install", "trl-training", "--target", "claude"])
214
+ assert args.command == "install"
215
+ assert args.skill == "trl-training"
216
+ assert args.target == "claude"
217
+
218
+ args = parser.parse_args(["uninstall", "trl-training", "--target", "claude"])
219
+ assert args.command == "uninstall"
220
+ assert args.skill == "trl-training"
221
+
222
+ def test_list_command_optional_target(self):
223
+ """Test that list command has optional target."""
224
+ parser = argparse.ArgumentParser()
225
+ subparsers = parser.add_subparsers(dest="command")
226
+ add_skills_subcommands(subparsers)
227
+
228
+ # Should work without target
229
+ args = parser.parse_args(["list"])
230
+ assert args.target is None
231
+
232
+ # Should work with target
233
+ args = parser.parse_args(["list", "--target", "claude"])
234
+ assert args.target == "claude"
235
+
236
+ def test_default_target_is_agents(self):
237
+ """Test that default target is 'agents'."""
238
+ parser = argparse.ArgumentParser()
239
+ subparsers = parser.add_subparsers(dest="command")
240
+ add_skills_subcommands(subparsers)
241
+
242
+ args = parser.parse_args(["install", "trl-training"])
243
+ assert args.target == "agents"
244
+
245
+ def test_scope_choices(self):
246
+ """Test that scope parameter accepts valid choices."""
247
+ parser = argparse.ArgumentParser()
248
+ subparsers = parser.add_subparsers(dest="command")
249
+ add_skills_subcommands(subparsers)
250
+
251
+ # Valid scopes
252
+ args = parser.parse_args(["install", "trl-training", "--target", "claude", "--scope", "project"])
253
+ assert args.scope == "project"
254
+
255
+ args = parser.parse_args(["install", "trl-training", "--target", "claude", "--scope", "global"])
256
+ assert args.scope == "global"
257
+
258
+ # Invalid scope should fail
259
+ with pytest.raises(SystemExit):
260
+ parser.parse_args(["install", "trl-training", "--target", "claude", "--scope", "invalid"])
261
+
262
+ def test_install_all_flag(self):
263
+ """Test install --all flag."""
264
+ parser = argparse.ArgumentParser()
265
+ subparsers = parser.add_subparsers(dest="command")
266
+ add_skills_subcommands(subparsers)
267
+
268
+ args = parser.parse_args(["install", "--all", "--target", "claude"])
269
+ assert args.all is True
270
+ assert args.skill is None
271
+
272
+ def test_install_force_flag(self):
273
+ """Test install --force flag."""
274
+ parser = argparse.ArgumentParser()
275
+ subparsers = parser.add_subparsers(dest="command")
276
+ add_skills_subcommands(subparsers)
277
+
278
+ args = parser.parse_args(["install", "trl-training", "--target", "claude", "--force"])
279
+ assert args.force is True
280
+
281
+ def test_default_scope_is_project(self):
282
+ """Test that default scope is 'project'."""
283
+ parser = argparse.ArgumentParser()
284
+ subparsers = parser.add_subparsers(dest="command")
285
+ add_skills_subcommands(subparsers)
286
+
287
+ args = parser.parse_args(["install", "trl-training", "--target", "claude"])
288
+ assert args.scope == "project"
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_utils.py ADDED
@@ -0,0 +1,1380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 copy
16
+ import textwrap
17
+ from io import StringIO
18
+ from unittest.mock import patch
19
+
20
+ import pytest
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+ import transformers
25
+ from packaging.version import Version
26
+ from transformers import AutoConfig, AutoModelForCausalLM
27
+ from transformers.testing_utils import torch_device
28
+ from transformers.utils import is_peft_available
29
+
30
+ from trl import ModelConfig
31
+ from trl.trainer.utils import (
32
+ RepeatSampler,
33
+ _ChunkedLogProbFunction,
34
+ adjusted_mfu,
35
+ compute_flops_per_token,
36
+ compute_mfu,
37
+ entropy_from_logits,
38
+ flush_left,
39
+ generate_model_card,
40
+ get_peft_config,
41
+ hash_module,
42
+ nanstd,
43
+ pad,
44
+ patch_chunked_lm_head,
45
+ print_prompt_completions_sample,
46
+ selective_log_softmax,
47
+ shuffle_sequence_dict,
48
+ split_pixel_values_by_grid,
49
+ split_tensor_dict,
50
+ unsplit_pixel_values_by_grid,
51
+ use_adapter,
52
+ )
53
+
54
+ from .testing_utils import TrlTestCase, require_peft, require_rich, require_torch_accelerator
55
+
56
+
57
+ if is_peft_available():
58
+ from peft import AutoPeftModelForCausalLM, LoraConfig
59
+
60
+
61
+ @require_peft
62
+ class TestUseAdapter(TrlTestCase):
63
+ def test_disables_on_none(self):
64
+ model = AutoPeftModelForCausalLM.from_pretrained(
65
+ "trl-internal-testing/tiny-PeftModel", adapter_name="my_adapter"
66
+ )
67
+ input_ids = torch.tensor([[1, 2, 3], [4, 5, 6]])
68
+ with model.disable_adapter():
69
+ expected = model(input_ids).logits
70
+
71
+ with use_adapter(model, None):
72
+ output = model(input_ids).logits
73
+
74
+ assert torch.equal(output, expected)
75
+
76
+ def test_restores_previous_adapter(self):
77
+ model = AutoPeftModelForCausalLM.from_pretrained(
78
+ "trl-internal-testing/tiny-PeftModel", adapter_name="my_adapter"
79
+ )
80
+ input_ids = torch.tensor([[1, 2, 3], [4, 5, 6]])
81
+ expected = model(input_ids).logits
82
+ with use_adapter(model, "my_adapter"):
83
+ pass
84
+ output = model(input_ids).logits
85
+ assert torch.equal(output, expected)
86
+
87
+ with use_adapter(model, None):
88
+ pass
89
+ output = model(input_ids).logits
90
+ assert torch.equal(output, expected)
91
+
92
+ def test_with_multiple_adapters(self):
93
+ model = AutoPeftModelForCausalLM.from_pretrained(
94
+ "trl-internal-testing/tiny-PeftModel", adapter_name="my_adapter_1"
95
+ )
96
+ model.load_adapter("trl-internal-testing/tiny-PeftModel-2", "my_adapter_2")
97
+ input_ids = torch.tensor([[1, 2, 3], [4, 5, 6]])
98
+
99
+ model.set_adapter("my_adapter_1") # should be a no-op, but let's keep it for clarity
100
+ expected_1 = model(input_ids).logits
101
+ model.set_adapter("my_adapter_2")
102
+ expected_2 = model(input_ids).logits
103
+
104
+ with use_adapter(model, "my_adapter_1"):
105
+ output_1 = model(input_ids).logits
106
+
107
+ with use_adapter(model, "my_adapter_2"):
108
+ output_2 = model(input_ids).logits
109
+
110
+ assert torch.equal(output_1, expected_1)
111
+ assert torch.equal(output_2, expected_2)
112
+
113
+
114
+ class TestPad(TrlTestCase):
115
+ def test_pad_1_dim_left(self):
116
+ x = torch.tensor([1, 2, 3])
117
+ y = torch.tensor([4, 5])
118
+ output = pad((x, y), padding_value=0, padding_side="left")
119
+ expected = torch.tensor([[1, 2, 3], [0, 4, 5]])
120
+ assert torch.equal(output, expected)
121
+
122
+ def test_pad_1_dim_right(self):
123
+ x = torch.tensor([1, 2, 3])
124
+ y = torch.tensor([4, 5])
125
+ output = pad((x, y), padding_value=0, padding_side="right")
126
+ expected = torch.tensor([[1, 2, 3], [4, 5, 0]])
127
+ assert torch.equal(output, expected)
128
+
129
+ def test_pad_2_dim_left(self):
130
+ x = torch.tensor([[1, 2], [3, 4]])
131
+ y = torch.tensor([[5, 6]])
132
+ output = pad((x, y), padding_value=0, padding_side="left")
133
+ expected = torch.tensor(
134
+ [
135
+ [[1, 2], [3, 4]],
136
+ [[0, 0], [5, 6]],
137
+ ]
138
+ )
139
+ assert torch.equal(output, expected)
140
+
141
+ def test_pad_2_dim_right(self):
142
+ x = torch.tensor([[1, 2], [3, 4]])
143
+ y = torch.tensor([[5, 6]])
144
+ output = pad((x, y), padding_value=0, padding_side="right")
145
+ expected = torch.tensor(
146
+ [
147
+ [[1, 2], [3, 4]],
148
+ [[5, 6], [0, 0]],
149
+ ]
150
+ )
151
+ assert torch.equal(output, expected)
152
+
153
+ def test_pad_2_dim_right_multidim(self):
154
+ x = torch.tensor([[1, 2], [3, 4]])
155
+ y = torch.tensor([[5]])
156
+ output = pad((x, y), padding_value=0, padding_side="right")
157
+ expected = torch.tensor(
158
+ [
159
+ [[1, 2], [3, 4]],
160
+ [[5, 0], [0, 0]],
161
+ ]
162
+ )
163
+ assert torch.equal(output, expected)
164
+
165
+ def test_pad_to_multiple_of_1(self):
166
+ x = torch.tensor([1, 2, 3])
167
+ y = torch.tensor([4, 5])
168
+ # Max length is 3, pad to multiple of 4
169
+ output = pad((x, y), padding_value=0, padding_side="right", pad_to_multiple_of=4)
170
+ expected = torch.tensor([[1, 2, 3, 0], [4, 5, 0, 0]])
171
+ assert torch.equal(output, expected)
172
+
173
+ def test_pad_to_multiple_of_2(self):
174
+ x = torch.tensor([1, 2, 3, 4, 5])
175
+ y = torch.tensor([6, 7, 8])
176
+ # Max length is 3, pad to multiple of 4
177
+ output = pad((x, y), padding_value=0, padding_side="right", pad_to_multiple_of=4)
178
+ expected = torch.tensor([[1, 2, 3, 4, 5, 0, 0, 0], [6, 7, 8, 0, 0, 0, 0, 0]])
179
+ assert torch.equal(output, expected)
180
+
181
+ def test_pad_to_multiple_of_side_left(self):
182
+ x = torch.tensor([1, 2, 3, 4, 5])
183
+ y = torch.tensor([6, 7, 8])
184
+ # Max length is 3, pad to multiple of 4
185
+ output = pad((x, y), padding_value=0, padding_side="left", pad_to_multiple_of=4)
186
+ expected = torch.tensor([[0, 0, 0, 1, 2, 3, 4, 5], [0, 0, 0, 0, 0, 6, 7, 8]])
187
+ assert torch.equal(output, expected)
188
+
189
+ def test_pad_to_multiple_of_no_extra_padding(self):
190
+ x = torch.tensor([1, 2, 3, 4])
191
+ y = torch.tensor([5, 6, 7, 8])
192
+ # Already multiple of 4
193
+ output = pad((x, y), padding_value=0, padding_side="left", pad_to_multiple_of=4)
194
+ expected = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]])
195
+ assert torch.equal(output, expected)
196
+
197
+
198
+ class TestHashModule(TrlTestCase):
199
+ def test_hash_module_deterministic_across_order(self):
200
+ class ModAB(torch.nn.Module):
201
+ def __init__(self, a: torch.Tensor, b: torch.Tensor):
202
+ super().__init__()
203
+ self.a = torch.nn.Parameter(a)
204
+ self.b = torch.nn.Parameter(b)
205
+
206
+ class ModBA(torch.nn.Module):
207
+ def __init__(self, a: torch.Tensor, b: torch.Tensor):
208
+ super().__init__()
209
+ self.b = torch.nn.Parameter(b)
210
+ self.a = torch.nn.Parameter(a)
211
+
212
+ a = torch.tensor([[1.0, 2.0]])
213
+ b = torch.tensor([3.0])
214
+ assert hash_module(ModAB(a, b)) == hash_module(ModBA(a, b))
215
+
216
+ def test_hash_module_changes_with_value(self):
217
+ class Mod(torch.nn.Module):
218
+ def __init__(self, value: float):
219
+ super().__init__()
220
+ self.weight = torch.nn.Parameter(torch.tensor([value, 2.0]))
221
+
222
+ assert hash_module(Mod(1.0)) != hash_module(Mod(1.5))
223
+
224
+ def test_hash_module_includes_dtype(self):
225
+ class Mod(torch.nn.Module):
226
+ def __init__(self, dtype: torch.dtype):
227
+ super().__init__()
228
+ self.weight = torch.nn.Parameter(torch.tensor([1.0, 2.0], dtype=dtype))
229
+
230
+ assert hash_module(Mod(torch.float32)) != hash_module(Mod(torch.float16))
231
+
232
+ def test_hash_module_tiny_model_twice(self):
233
+ model_id = "trl-internal-testing/tiny-GptOssForCausalLM"
234
+ model_a = AutoModelForCausalLM.from_pretrained(model_id)
235
+ model_b = AutoModelForCausalLM.from_pretrained(model_id)
236
+ assert hash_module(model_a) == hash_module(model_b)
237
+
238
+ def test_hash_module_tiny_model_change_layer(self):
239
+ model_id = "trl-internal-testing/tiny-GptOssForCausalLM"
240
+ model = AutoModelForCausalLM.from_pretrained(model_id)
241
+ h1 = hash_module(model)
242
+ with torch.no_grad():
243
+ model.lm_head.weight.add_(0.01)
244
+ h2 = hash_module(model)
245
+ assert h1 != h2
246
+
247
+
248
+ @require_peft
249
+ class TestGetPEFTConfig(TrlTestCase):
250
+ def test_create_peft_config_use_peft_false(self):
251
+ """Test that when use_peft is False, the function returns None."""
252
+ model_args = ModelConfig(use_peft=False)
253
+ peft_config = get_peft_config(model_args)
254
+ assert peft_config is None
255
+
256
+ def test_create_peft_config_use_peft_true(self):
257
+ """Test that when use_peft is True, the function returns a LoraConfig object."""
258
+ # Provide non-default values to the model config for testing
259
+ peft_kwargs = {
260
+ "lora_r": 8,
261
+ "lora_alpha": 16,
262
+ "lora_dropout": 0.1,
263
+ "lora_task_type": "SEQ_CLS",
264
+ "use_rslora": True,
265
+ "lora_target_modules": ["up_proj", "down_proj"],
266
+ "lora_modules_to_save": ["up_proj"],
267
+ }
268
+ model_args = ModelConfig(use_peft=True, **peft_kwargs)
269
+ peft_config = get_peft_config(model_args)
270
+ assert isinstance(peft_config, LoraConfig)
271
+ for arg, value in peft_kwargs.items():
272
+ # Test that lists of modules are converted to sets
273
+ if arg == "lora_target_modules":
274
+ value = set(value)
275
+ # Rename the argument to match the LoraConfig attribute name
276
+ if arg in ["lora_r", "lora_task_type", "lora_target_modules", "lora_modules_to_save"]:
277
+ arg = arg[len("lora_") :] if arg.startswith("lora_") else arg
278
+
279
+ assert getattr(peft_config, arg) == value
280
+
281
+
282
+ class TestNanStd(TrlTestCase):
283
+ def test_nanstd_ignores_nans(self):
284
+ x = torch.tensor([1.0, 2.0, 3.0, float("nan")])
285
+ result = nanstd(x)
286
+ torch.testing.assert_close(result, torch.tensor(1.0))
287
+
288
+ def test_nanstd_dim_and_keepdim(self):
289
+ x = torch.tensor([[1.0, float("nan")], [3.0, 5.0]])
290
+ result = nanstd(x, dim=1, keepdim=True)
291
+ assert torch.isnan(result[0, 0])
292
+ torch.testing.assert_close(result[1, 0], torch.tensor(1.4142135), rtol=1e-5, atol=1e-6)
293
+
294
+ def test_nanstd_all_nan(self):
295
+ x = torch.tensor([float("nan"), float("nan")])
296
+ result = nanstd(x)
297
+ assert torch.isnan(result)
298
+
299
+
300
+ class TestGenerateModelCard(TrlTestCase):
301
+ def test_full(self):
302
+ model_card = generate_model_card(
303
+ base_model="username/my_base_model",
304
+ model_name="my_model",
305
+ hub_model_id="username/my_hub_model",
306
+ dataset_name="username/my_dataset",
307
+ tags=["trl", "trainer-tag"],
308
+ wandb_url="https://wandb.ai/username/project_id/runs/abcd1234",
309
+ trackio_url="https://huggingface.co/spaces/username/space_id",
310
+ comet_url="https://www.comet.com/username/project_id/experiment_id",
311
+ trainer_name="My Trainer",
312
+ trainer_citation="@article{my_trainer, ...}",
313
+ paper_title="My Paper",
314
+ paper_id="1234.56789",
315
+ )
316
+ card_text = str(model_card)
317
+ assert "[username/my_base_model](https://huggingface.co/username/my_base_model)" in card_text
318
+ assert "my_model" in card_text
319
+ assert 'pipeline("text-generation", model="username/my_hub_model", device="cuda")' in card_text
320
+ assert "datasets: username/my_dataset" in card_text
321
+ assert "](https://wandb.ai/username/project_id/runs/abcd1234)" in card_text
322
+ assert "](https://huggingface.co/spaces/username/space_id)" in card_text
323
+ assert "](https://www.comet.com/username/project_id/experiment_id" in card_text
324
+ assert "My Trainer" in card_text
325
+ assert "```bibtex\n@article{my_trainer, ...}\n```" in card_text
326
+ assert "[My Paper](https://huggingface.co/papers/1234.56789)" in card_text
327
+
328
+ def test_val_none(self):
329
+ model_card = generate_model_card(
330
+ base_model=None,
331
+ model_name="my_model",
332
+ hub_model_id="username/my_hub_model",
333
+ dataset_name=None,
334
+ tags=[],
335
+ wandb_url=None,
336
+ trackio_url=None,
337
+ comet_url=None,
338
+ trainer_name="My Trainer",
339
+ trainer_citation=None,
340
+ paper_title=None,
341
+ paper_id=None,
342
+ )
343
+ card_text = str(model_card)
344
+ assert "my_model" in card_text
345
+ assert 'pipeline("text-generation", model="username/my_hub_model", device="cuda")' in card_text
346
+ assert "My Trainer" in card_text
347
+
348
+
349
+ class TestFlushLeft(TrlTestCase):
350
+ def test_basic_case(self):
351
+ mask = torch.tensor([[0, 0, 1, 1, 1], [0, 1, 1, 0, 0]])
352
+ tensor1 = torch.tensor([[0, 0, 2, 3, 4], [0, 5, 6, 0, 0]])
353
+ tensor2 = torch.tensor([[0, 0, 7, 8, 9], [0, 10, 11, 0, 0]])
354
+ new_mask, new_tensor1, new_tensor2 = flush_left(mask, tensor1, tensor2)
355
+
356
+ expected_mask = torch.tensor([[1, 1, 1], [1, 1, 0]])
357
+ expected_tensor1 = torch.tensor([[2, 3, 4], [5, 6, 0]])
358
+ expected_tensor2 = torch.tensor([[7, 8, 9], [10, 11, 0]])
359
+
360
+ assert torch.equal(new_mask, expected_mask)
361
+ assert torch.equal(new_tensor1, expected_tensor1)
362
+ assert torch.equal(new_tensor2, expected_tensor2)
363
+
364
+ def test_single_row(self):
365
+ mask = torch.tensor([[0, 0, 1, 1]])
366
+ tensor1 = torch.tensor([[0, 0, 2, 3]])
367
+ new_mask, new_tensor1 = flush_left(mask, tensor1)
368
+
369
+ expected_mask = torch.tensor([[1, 1]])
370
+ expected_tensor1 = torch.tensor([[2, 3]])
371
+
372
+ assert torch.equal(new_mask, expected_mask)
373
+ assert torch.equal(new_tensor1, expected_tensor1)
374
+
375
+ def test_no_shift_needed(self):
376
+ mask = torch.tensor([[1, 1, 0, 0], [1, 0, 0, 0]])
377
+ tensor1 = torch.tensor([[5, 6, 0, 0], [7, 0, 0, 0]])
378
+ new_mask, new_tensor1 = flush_left(mask, tensor1)
379
+
380
+ expected_mask = torch.tensor([[1, 1], [1, 0]])
381
+ expected_tensor1 = torch.tensor([[5, 6], [7, 0]])
382
+
383
+ assert torch.equal(new_mask, expected_mask)
384
+ assert torch.equal(new_tensor1, expected_tensor1)
385
+
386
+ def test_no_tensors(self):
387
+ mask = torch.tensor([[0, 0, 1, 1, 1], [0, 1, 1, 0, 0]])
388
+ new_mask = flush_left(mask)
389
+ expected_mask = torch.tensor([[1, 1, 1], [1, 1, 0]])
390
+ assert torch.equal(new_mask, expected_mask)
391
+
392
+
393
+ class TestRepeatRandomSampler(TrlTestCase):
394
+ def test_sampler(self):
395
+ dataset = ["a", "b", "c", "d", "e", "f", "g"]
396
+ sampler = RepeatSampler(dataset, mini_repeat_count=2)
397
+ # Should output something like [4, 4, 3, 3, 0, 0, 1, 1, 2, 2, 6, 6, 5, 5]
398
+ sampled = list(sampler)
399
+ # Check that the length is doubled
400
+ assert len(sampled) == 2 * len(dataset)
401
+ # Check that all indexes are present
402
+ assert set(sampled) == set(range(len(dataset)))
403
+ # Check that each element is repeated twice
404
+ assert all(sampled[i] == sampled[i + 1] for i in range(0, len(sampled), 2))
405
+
406
+ def test_sampler_no_shuffle(self):
407
+ dataset = ["a", "b", "c", "d", "e", "f", "g"]
408
+ sampler = RepeatSampler(dataset, mini_repeat_count=2, shuffle=False)
409
+ sampled = list(sampler)
410
+ expected = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]
411
+ assert sampled == expected
412
+
413
+ def test_sampler_no_repeat(self):
414
+ dataset = ["a", "b", "c", "d", "e", "f", "g"]
415
+ sampler = RepeatSampler(dataset, mini_repeat_count=1)
416
+ # Should output something like [4, 3, 0, 1, 2, 6, 5]
417
+ sampled = list(sampler)
418
+ # Check that the length is the same
419
+ assert len(sampled) == len(dataset)
420
+ # Check that all indexes are present
421
+ assert set(sampled) == set(range(len(dataset)))
422
+
423
+ def test_sampler_with_batch_size(self):
424
+ dataset = ["a", "b", "c", "d", "e", "f", "g", "h"]
425
+ sampler = RepeatSampler(dataset, mini_repeat_count=1, batch_size=2, repeat_count=2)
426
+ # Should output something like [4, 3, 4, 3, 0, 1, 0, 1, 2, 6, 2, 6, 5, 7, 5, 7]
427
+ sampled = list(sampler)
428
+ # Check that the length is doubled
429
+ assert len(sampled) == 2 * len(dataset)
430
+ # Check that all indexes are present
431
+ assert set(sampled) == set(range(len(dataset)))
432
+ # Check that each element is repeated as expected
433
+ assert all(sampled[i : i + 1] == sampled[i + 2 : i + 3] for i in range(0, len(sampled), 4))
434
+
435
+ def test_sampler_with_batch_size_and_drop(self):
436
+ dataset = ["a", "b", "c", "d", "e", "f", "g"]
437
+ sampler = RepeatSampler(dataset, mini_repeat_count=1, batch_size=2, repeat_count=2)
438
+ # Should output something like [4, 3, 4, 3, 0, 1, 0, 1, 2, 6, 2, 6]
439
+ sampled = list(sampler)
440
+ # Check that the length is doubled
441
+ assert len(sampled) == 2 * (
442
+ len(dataset) - 1
443
+ ) # one element is dropped, because it's not enough to form a batch
444
+ assert len(sampler) == len(sampled) # the length should be the same as the sampled length
445
+ # Check that the sampled indexes are a subset of the dataset indexes
446
+ assert set(sampled).issubset(set(range(len(dataset))))
447
+ # Check that each element is repeated as expected
448
+ assert all(sampled[i : i + 1] == sampled[i + 2 : i + 3] for i in range(0, len(sampled), 4))
449
+
450
+ def test_sampler_with_mini_repeat_count_and_batch_size_1(self):
451
+ dataset = ["a", "b", "c", "d", "e", "f", "g"]
452
+ sampler = RepeatSampler(dataset, mini_repeat_count=2, batch_size=3, repeat_count=2)
453
+ # Should output something like [4, 4, 3, 3, 0, 0, 4, 4, 3, 3, 0, 0,
454
+ # 1, 1, 2, 2, 6, 6, 1, 1, 2, 2, 6, 6]
455
+ sampled = list(sampler)
456
+ # Check that the length is quadrupled
457
+ assert len(sampled) == 4 * (len(dataset) - 1) # 1 element is dropped, because it's not enough to form a batch
458
+ assert len(sampler) == len(sampled) # the length should be the same as the sampled length
459
+ # Check that the sampled indexes are a subset of the dataset indexes
460
+ assert set(sampled).issubset(set(range(len(dataset))))
461
+ # Check that each element is repeated as expected
462
+ assert all(sampled[i] == sampled[i + 1] for i in range(0, len(sampled), 2))
463
+ # Check that the batch is repeated as expected
464
+ assert sampled[0:6] == sampled[6:12]
465
+ assert sampled[12:18] == sampled[18:24]
466
+
467
+ def test_sampler_with_mini_repeat_count_and_batch_size_2(self):
468
+ dataset = ["a", "b", "c", "d", "e", "f", "g"]
469
+ sampler = RepeatSampler(dataset, mini_repeat_count=3, batch_size=2, repeat_count=2)
470
+ # Should output something like [4, 4, 4, 3, 3, 3, 4, 4, 4, 3, 3, 3,
471
+ # 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1,
472
+ # 2, 2, 2, 6, 6, 6, 2, 2, 2, 6, 6, 6]
473
+ sampled = list(sampler)
474
+ # Check that the length is sextupled
475
+ assert len(sampled) == 6 * (len(dataset) - 1) # 1 element is dropped, because it's not enough to form a batch
476
+ assert len(sampler) == len(sampled) # the length should be the same as the sampled length
477
+ # Check that the sampled indexes are a subset of the dataset indexes
478
+ assert set(sampled).issubset(set(range(len(dataset))))
479
+ # Check that each element is repeated as expected
480
+ assert all(sampled[i] == sampled[i + 1] == sampled[i + 2] for i in range(0, len(sampled), 3))
481
+ # Check that the batch is repeated as expected
482
+ assert sampled[0:6] == sampled[6:12]
483
+ assert sampled[12:18] == sampled[18:24]
484
+ assert sampled[24:30] == sampled[30:36]
485
+
486
+ def test_sampler_with_mini_repeat_count_and_batch_size_3(self):
487
+ dataset = ["a", "b", "c", "d", "e", "f", "g"]
488
+ sampler = RepeatSampler(dataset, mini_repeat_count=2, batch_size=2, repeat_count=3)
489
+ # Should output something like [4, 4, 3, 3, 4, 4, 3, 3, 4, 4, 3, 3,
490
+ # 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1,
491
+ # 2, 2, 6, 6, 2, 2, 6, 6, 2, 2, 6, 6]
492
+ sampled = list(sampler)
493
+ # Check that the length is sextupled
494
+ assert len(sampled) == 6 * (len(dataset) - 1) # 1 element is dropped, because it's not enough to form a batch
495
+ # Check that the sampled indexes are a subset of the dataset indexes
496
+ assert set(sampled).issubset(set(range(len(dataset))))
497
+ # Check that each element is repeated as expected
498
+ assert all(sampled[i] == sampled[i + 1] for i in range(0, len(sampled), 2))
499
+ # Check that the batch is repeated as expected
500
+ assert sampled[0:4] == sampled[4:8] == sampled[8:12]
501
+ assert sampled[12:16] == sampled[16:20] == sampled[20:24]
502
+ assert sampled[24:28] == sampled[28:32] == sampled[32:36]
503
+
504
+
505
+ class TestEntropyFromLogits(TrlTestCase):
506
+ @pytest.mark.parametrize("shape", [(768,), (32, 768), (8, 16, 768), (2, 4, 8, 768)])
507
+ @pytest.mark.parametrize("chunk_size", [1, 16])
508
+ @pytest.mark.parametrize("dtype", [torch.float64, torch.float32, torch.float16, torch.bfloat16])
509
+ def test_entropy_from_logits_2_dims(self, dtype, chunk_size, shape):
510
+ logits = torch.randn(*shape, dtype=dtype)
511
+ if dtype in (torch.float64, torch.float32):
512
+ p = logits.softmax(-1)
513
+ entropy = -torch.sum(p * p.log(), dim=-1)
514
+ else:
515
+ logps = logits.log_softmax(dim=-1)
516
+ entropy = -(torch.exp(logps) * logps).sum(-1)
517
+ predicted_entropy = entropy_from_logits(logits, chunk_size=chunk_size)
518
+ torch.testing.assert_close(predicted_entropy, entropy, rtol=1e-5, atol=1e-5)
519
+
520
+
521
+ @require_rich
522
+ class TestPrintPromptCompletionsSample(TrlTestCase):
523
+ @patch("sys.stdout", new_callable=StringIO)
524
+ def test_print_output(self, mock_stdout):
525
+ prompts = ["The sky is", "The sun is"]
526
+ completions = [" blue.", " in the sky."]
527
+ rewards = {"Correctness": [0.123, 0.456], "Format": [0.789, 0.101]}
528
+ advantages = [0.987, 0.654]
529
+ step = 42
530
+
531
+ print_prompt_completions_sample(prompts, completions, rewards, advantages, step)
532
+
533
+ output = mock_stdout.getvalue()
534
+
535
+ # docstyle-ignore
536
+ expected_output = textwrap.dedent("""\
537
+ ╭──────────────────────────── Step 42 ─────────────────────────────╮
538
+ │ ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┓ │
539
+ │ ┃ Prompt ┃ Completion ┃ Correctness ┃ Format ┃ Advantage ┃ │
540
+ │ ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━┩ │
541
+ │ │ The sky is │ blue. │ 0.12 │ 0.79 │ 0.99 │ │
542
+ │ ├────────────┼──────────────┼─────────────┼────────┼───────────┤ │
543
+ │ │ The sun is │ in the sky. │ 0.46 │ 0.10 │ 0.65 │ │
544
+ │ └────────────┴──────────────┴─────────────┴────────┴───────────┘ │
545
+ ╰──────────────────────────────────────────────────────────────────╯
546
+ """)
547
+
548
+ assert output == expected_output
549
+
550
+ @patch("sys.stdout", new_callable=StringIO)
551
+ def test_extra_columns(self, mock_stdout):
552
+ prompts = ["The sky is", "The sun is"]
553
+ completions = [" blue.", " in the sky."]
554
+ rewards = {"Correctness": [0.123, 0.456], "Format": [0.789, 0.101]}
555
+ advantages = [0.987, 0.654]
556
+ extra = {"source": ["dataset_A", "dataset_B"]}
557
+ step = 42
558
+
559
+ print_prompt_completions_sample(prompts, completions, rewards, advantages, step, extra=extra)
560
+
561
+ output = mock_stdout.getvalue()
562
+
563
+ # docstyle-ignore
564
+ expected_output = textwrap.dedent("""\
565
+ ╭────────────────────────────────── Step 42 ───────────────────────────────────╮
566
+ │ ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┓ │
567
+ │ ┃ Prompt ┃ Completion ┃ Correctness ┃ Format ┃ Advantage ┃ source ┃ │
568
+ │ ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━┩ │
569
+ │ │ The sky is │ blue. │ 0.12 │ 0.79 │ 0.99 │ dataset_A │ │
570
+ │ ├────────────┼──────────────┼─────────────┼────────┼───────────┼───────────┤ │
571
+ │ │ The sun is │ in the sky. │ 0.46 │ 0.10 │ 0.65 │ dataset_B │ │
572
+ │ └────────────┴──────────────┴─────────────┴────────┴───────────┴───────────┘ │
573
+ ╰──────────────────────────────────────────────────────────────────────────────╯
574
+ """)
575
+
576
+ assert output == expected_output
577
+
578
+ @patch("sys.stdout", new_callable=StringIO)
579
+ def test_num_samples(self, mock_stdout):
580
+ prompts = ["A", "B"]
581
+ completions = ["1", "2"]
582
+ rewards = {"Score": [0.1, 0.2]}
583
+ advantages = [0.3, 0.4]
584
+ step = 10
585
+
586
+ print_prompt_completions_sample(prompts, completions, rewards, advantages, step, num_samples=1)
587
+ output = mock_stdout.getvalue()
588
+
589
+ # docstyle-ignore
590
+ possible_outputs = [
591
+ textwrap.dedent("""\
592
+ ╭────────────────── Step 10 ──────────────────╮
593
+ │ ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┓ │
594
+ │ ┃ Prompt ┃ Completion ┃ Score ┃ Advantage ┃ │
595
+ │ ┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━┩ │
596
+ │ │ A │ 1 │ 0.10 │ 0.30 │ │
597
+ │ └────────┴────────────┴───────┴───────────┘ │
598
+ ╰─────────────────────────────────────────────╯
599
+ """),
600
+ # docstyle-ignore
601
+ textwrap.dedent("""\
602
+ ╭────────────────── Step 10 ──────────────────╮
603
+ │ ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┓ │
604
+ │ ┃ Prompt ┃ Completion ┃ Score ┃ Advantage ┃ │
605
+ │ ┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━┩ │
606
+ │ │ B │ 2 │ 0.20 │ 0.40 │ │
607
+ │ └────────┴────────────┴───────┴───────────┘ │
608
+ ╰─────────────────────────────────────────────╯
609
+ """),
610
+ ]
611
+ assert output in possible_outputs
612
+
613
+ @patch("sys.stdout", new_callable=StringIO)
614
+ def test_print_messages(self, mock_stdout):
615
+ prompts = [
616
+ [
617
+ {"role": "system", "content": "You are an helpful assistant."},
618
+ {"role": "user", "content": "What color is the sky?"},
619
+ ],
620
+ [
621
+ {"role": "system", "content": "You are an helpful assistant."},
622
+ {"role": "user", "content": "Where is the sun?"},
623
+ ],
624
+ ]
625
+ completions = [
626
+ [{"role": "assistant", "content": "It is blue."}],
627
+ [{"role": "assistant", "content": "In the sky."}],
628
+ ]
629
+ rewards = {"Correctness": [0.123, 0.456], "Format": [0.789, 0.101]}
630
+ advantages = [0.987, 0.654]
631
+ step = 42
632
+
633
+ print_prompt_completions_sample(prompts, completions, rewards, advantages, step)
634
+
635
+ output = mock_stdout.getvalue()
636
+
637
+ # docstyle-ignore
638
+ expected_output = textwrap.dedent("""\
639
+ ╭────────────────────────────────── Step 42 ───────────────────────────────────╮
640
+ │ ┏━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┓ │
641
+ │ ┃ Prompt ┃ Completion ┃ Correctness ┃ Format ┃ Advantage ┃ │
642
+ │ ┡━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━┩ │
643
+ │ │ SYSTEM │ ASSISTANT │ 0.12 │ 0.79 │ 0.99 │ │
644
+ │ │ You are an helpful │ It is blue. │ │ │ │ │
645
+ │ │ assistant. │ │ │ │ │ │
646
+ │ │ │ │ │ │ │ │
647
+ │ │ USER │ │ │ │ │ │
648
+ │ │ What color is the sky? │ │ │ │ │ │
649
+ │ ├─────────────────────────┼─────────────┼─────────────┼────────┼───────────┤ │
650
+ │ │ SYSTEM │ ASSISTANT │ 0.46 │ 0.10 │ 0.65 │ │
651
+ │ │ You are an helpful │ In the sky. │ │ │ │ │
652
+ │ │ assistant. │ │ │ │ │ │
653
+ │ │ │ │ │ │ │ │
654
+ │ │ USER │ │ │ │ │ │
655
+ │ │ Where is the sun? │ │ │ │ │ │
656
+ │ └─────────────────────────┴─────────────┴─────────────┴────────┴───────────┘ │
657
+ ╰──────────────────────────────────────────────────────────────────────────────╯
658
+ """)
659
+
660
+ assert output == expected_output
661
+
662
+ @patch("sys.stdout", new_callable=StringIO)
663
+ def test_print_messages_with_tools(self, mock_stdout):
664
+ prompts = [
665
+ [{"role": "user", "content": "What is the temperature in Paris?"}],
666
+ [{"role": "user", "content": "What is the weather in London?"}],
667
+ ]
668
+ completions = [
669
+ [{"role": "tool", "name": "get_temperature", "args": {"location": "Paris"}}],
670
+ [{"role": "tool", "name": "get_weather", "args": {"location": "London"}}],
671
+ ]
672
+ rewards = {"Correctness": [0.123, 0.456], "Format": [0.789, 0.101]}
673
+ advantages = [0.987, 0.654]
674
+ step = 42
675
+
676
+ print_prompt_completions_sample(prompts, completions, rewards, advantages, step)
677
+
678
+ output = mock_stdout.getvalue()
679
+
680
+ # docstyle-ignore
681
+ expected_output = textwrap.dedent("""\
682
+ ╭────────────────────────────────── Step 42 ───────────────────────────────────╮
683
+ │ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┓ │
684
+ │ ┃ Prompt ┃ Completion ┃ Correctness ┃ Format ┃ Advantage ┃ │
685
+ │ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━┩ │
686
+ │ │ USER │ TOOL │ 0.12 │ 0.79 │ 0.99 │ │
687
+ │ │ What is the │ get_temperature(… │ │ │ │ │
688
+ │ │ temperature in │ 'Paris'}) │ │ │ │ │
689
+ │ │ Paris? │ │ │ │ │ │
690
+ │ ├───────────────────┼───────────────────┼─────────────┼────────┼───────────┤ │
691
+ │ │ USER │ TOOL │ 0.46 │ 0.10 │ 0.65 │ │
692
+ │ │ What is the │ get_weather({'lo… │ │ │ │ │
693
+ │ │ weather in │ 'London'}) │ │ │ │ │
694
+ │ │ London? │ │ │ │ │ │
695
+ │ └───────────────────┴───────────────────┴─────────────┴────────┴───────────┘ │
696
+ ╰──────────────────────────────────────────────────────────────────────────────╯
697
+ """)
698
+
699
+ assert output == expected_output
700
+
701
+ @patch("sys.stdout", new_callable=StringIO)
702
+ def test_print_messages_with_reasoning_content(self, mock_stdout):
703
+ prompts = [[{"role": "user", "content": "What color is the sky?"}]]
704
+ completions = [[{"role": "assistant", "reasoning_content": "I think it is blue.", "content": "It is blue."}]]
705
+ rewards = {"Score": [0.5]}
706
+ advantages = [0.9]
707
+ step = 1
708
+
709
+ print_prompt_completions_sample(prompts, completions, rewards, advantages, step)
710
+
711
+ output = mock_stdout.getvalue()
712
+
713
+ # docstyle-ignore
714
+ expected_output = textwrap.dedent("""\
715
+ ╭─────────────────────────────── Step 1 ───────────────────────────────╮
716
+ │ ┏━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┓ │
717
+ │ ┃ Prompt ┃ Completion ┃ Score ┃ Advantage ┃ │
718
+ │ ┡━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━┩ │
719
+ │ │ USER │ ASSISTANT │ 0.50 │ 0.90 │ │
720
+ │ │ What color is the sky? │ I think it is blue. │ │ │ │
721
+ │ │ │ It is blue. │ │ │ │
722
+ │ └────────────────────────┴─────────────────────┴───────┴───────────┘ │
723
+ ╰──────────────────────────────────────────────────────────────────────╯
724
+ """)
725
+
726
+ assert output == expected_output
727
+
728
+ @patch("sys.stdout", new_callable=StringIO)
729
+ def test_print_messages_with_thinking(self, mock_stdout):
730
+ prompts = [[{"role": "user", "content": "What color is the sky?"}]]
731
+ completions = [[{"role": "assistant", "thinking": "I think it is blue.", "content": "It is blue."}]]
732
+ rewards = {"Score": [0.5]}
733
+ advantages = [0.9]
734
+ step = 1
735
+
736
+ print_prompt_completions_sample(prompts, completions, rewards, advantages, step)
737
+
738
+ output = mock_stdout.getvalue()
739
+
740
+ # docstyle-ignore
741
+ expected_output = textwrap.dedent("""\
742
+ ╭─────────────────────────────── Step 1 ───────────────────────────────╮
743
+ │ ┏━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┓ │
744
+ │ ┃ Prompt ┃ Completion ┃ Score ┃ Advantage ┃ │
745
+ │ ┡━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━┩ │
746
+ │ │ USER │ ASSISTANT │ 0.50 │ 0.90 │ │
747
+ │ │ What color is the sky? │ I think it is blue. │ │ │ │
748
+ │ │ │ It is blue. │ │ │ │
749
+ │ └────��───────────────────┴─────────────────────┴───────┴───────────┘ │
750
+ ╰──────────────────────────────────────────────────────────────────────╯
751
+ """)
752
+
753
+ assert output == expected_output
754
+
755
+
756
+ class TestSelectiveLogSoftmax(TrlTestCase):
757
+ @pytest.mark.parametrize("dtype", [torch.float64, torch.float32, torch.float16, torch.bfloat16])
758
+ def test_selective_log_softmax(self, dtype):
759
+ """Test selective_log_softmax with logits of different dtypes"""
760
+ vocab_size = 1024
761
+ batch_size = 4
762
+ seq_len = 32
763
+
764
+ input_ids = torch.randint(low=0, high=vocab_size, size=(batch_size, seq_len))
765
+ logits = torch.randn(batch_size, seq_len, vocab_size, dtype=dtype)
766
+
767
+ expected_output = torch.gather(logits.log_softmax(-1), dim=-1, index=input_ids.unsqueeze(-1)).squeeze(-1)
768
+ actual_output = selective_log_softmax(logits, input_ids)
769
+
770
+ if dtype in [torch.float16, torch.bfloat16]:
771
+ # half-precision dtypes fall back to an exact method
772
+ assert torch.equal(actual_output, expected_output)
773
+ else:
774
+ torch.testing.assert_close(actual_output, expected_output, rtol=1e-5, atol=1e-5)
775
+
776
+ @pytest.mark.parametrize("dtype", [torch.float64, torch.float32, torch.float16, torch.bfloat16])
777
+ @pytest.mark.parametrize("k", [1, 8])
778
+ def test_selective_log_softmax_multi_index(self, dtype, k):
779
+ """Test selective_log_softmax with logits of different dtypes and index widths"""
780
+ vocab_size = 1024
781
+ batch_size = 4
782
+ seq_len = 32
783
+
784
+ index = torch.randint(low=0, high=vocab_size, size=(batch_size, seq_len, k))
785
+ logits = torch.randn(batch_size, seq_len, vocab_size, dtype=dtype)
786
+
787
+ expected_output = torch.gather(logits.log_softmax(-1), dim=-1, index=index)
788
+ actual_output = selective_log_softmax(logits, index)
789
+
790
+ assert actual_output.shape == (batch_size, seq_len, k)
791
+ if dtype in [torch.float16, torch.bfloat16]:
792
+ # half-precision dtypes fall back to an exact method
793
+ assert torch.equal(actual_output, expected_output)
794
+ else:
795
+ torch.testing.assert_close(actual_output, expected_output, rtol=1e-5, atol=1e-5)
796
+
797
+
798
+ class TestShuffleSequenceDict(TrlTestCase):
799
+ def test_shuffle_preserves_shape(self):
800
+ x = torch.arange(6).reshape(3, 2)
801
+ y = torch.arange(3).reshape(3, 1)
802
+ tensor_dict = {"x": x.clone(), "y": y.clone()}
803
+
804
+ shuffled = shuffle_sequence_dict(tensor_dict)
805
+
806
+ assert shuffled["x"].shape == x.shape
807
+ assert shuffled["y"].shape == y.shape
808
+
809
+ def test_shuffle_consistent_across_tensors(self):
810
+ # Use known patterns to check alignment
811
+ x = torch.tensor([[10, 11], [20, 21], [30, 31]])
812
+ y = torch.tensor([[1], [2], [3]])
813
+ tensor_dict = {"x": x.clone(), "y": y.clone()}
814
+
815
+ shuffled = shuffle_sequence_dict(tensor_dict)
816
+
817
+ # Build a reverse map from shuffled x rows to y values
818
+ for i in range(3):
819
+ x_row = shuffled["x"][i]
820
+ y_val = shuffled["y"][i].item()
821
+
822
+ if torch.equal(x_row, torch.tensor([10, 11])):
823
+ assert y_val == 1
824
+ elif torch.equal(x_row, torch.tensor([20, 21])):
825
+ assert y_val == 2
826
+ elif torch.equal(x_row, torch.tensor([30, 31])):
827
+ assert y_val == 3
828
+ else:
829
+ pytest.fail("Unexpected x row in shuffled output.")
830
+
831
+ def test_none_tensor_remains_none(self):
832
+ x = torch.arange(6).reshape(3, 2)
833
+ tensor_dict = {"x": x.clone(), "y": None}
834
+
835
+ shuffled = shuffle_sequence_dict(tensor_dict)
836
+
837
+ assert shuffled["y"] is None
838
+ assert shuffled["x"].shape == x.shape
839
+
840
+ def test_shuffle_with_list(self):
841
+ x = torch.tensor([[10, 11], [20, 21], [30, 31]])
842
+ y = ["a", "b", "c"]
843
+
844
+ sequence_dict = {"x": x.clone(), "y": y}
845
+
846
+ shuffled = shuffle_sequence_dict(sequence_dict)
847
+
848
+ # Check that the list y is shuffled in the same order as x
849
+ for i in range(3):
850
+ x_row = shuffled["x"][i]
851
+ y_val = shuffled["y"][i]
852
+
853
+ if torch.equal(x_row, torch.tensor([10, 11])):
854
+ assert y_val == "a"
855
+ elif torch.equal(x_row, torch.tensor([20, 21])):
856
+ assert y_val == "b"
857
+ elif torch.equal(x_row, torch.tensor([30, 31])):
858
+ assert y_val == "c"
859
+ else:
860
+ pytest.fail("Unexpected x row in shuffled output.")
861
+
862
+
863
+ class TestSplitTensorDict(TrlTestCase):
864
+ def test_split_equal_chunks(self):
865
+ x = torch.arange(12).reshape(6, 2)
866
+ y = torch.arange(6).reshape(6, 1)
867
+ tensor_dict = {"x": x, "y": y}
868
+
869
+ result = split_tensor_dict(tensor_dict, 3)
870
+
871
+ expected_x_chunks = torch.chunk(x, 3, dim=0)
872
+ expected_y_chunks = torch.chunk(y, 3, dim=0)
873
+ assert len(result) == 3
874
+ for i in range(3):
875
+ assert torch.equal(result[i]["x"], expected_x_chunks[i])
876
+ assert torch.equal(result[i]["y"], expected_y_chunks[i])
877
+
878
+ def test_with_none_tensor(self):
879
+ x = torch.arange(12).reshape(6, 2)
880
+ tensor_dict = {"x": x, "y": None}
881
+
882
+ result = split_tensor_dict(tensor_dict, 2)
883
+
884
+ expected_x_chunks = torch.chunk(x, 2, dim=0)
885
+ assert len(result) == 2
886
+ for i in range(2):
887
+ assert torch.equal(result[i]["x"], expected_x_chunks[i])
888
+ assert result[i]["y"] is None
889
+
890
+ def test_with_scalar(self):
891
+ x = torch.arange(12).reshape(6, 2)
892
+ tensor_dict = {"x": x, "y": torch.tensor(1)}
893
+
894
+ result = split_tensor_dict(tensor_dict, 2)
895
+
896
+ expected_x_chunks = torch.chunk(x, 2, dim=0)
897
+ assert len(result) == 2
898
+ for i in range(2):
899
+ assert torch.equal(result[i]["x"], expected_x_chunks[i])
900
+ assert torch.equal(result[i]["y"], torch.tensor(1))
901
+
902
+
903
+ class TestSplitPixelValuesByGrid(TrlTestCase):
904
+ def test_split_correctly_0(self):
905
+ batch = {
906
+ "image_grid_thw": torch.tensor([[1, 2, 2], [1, 2, 2]]),
907
+ "num_images": [1, 1],
908
+ "pixel_values": torch.arange(8 * 3).reshape(8, 3), # Shape: [8, 3]
909
+ }
910
+ result = split_pixel_values_by_grid(batch)
911
+ assert isinstance(result["pixel_values"], list)
912
+ assert len(result["pixel_values"]) == 2
913
+ assert torch.equal(result["pixel_values"][0], batch["pixel_values"][:4])
914
+ assert torch.equal(result["pixel_values"][1], batch["pixel_values"][4:])
915
+ assert isinstance(result["image_grid_thw"], list)
916
+ assert len(result["image_grid_thw"]) == 2
917
+ assert torch.equal(result["image_grid_thw"][0], torch.tensor([[1, 2, 2]]))
918
+ assert torch.equal(result["image_grid_thw"][1], torch.tensor([[1, 2, 2]]))
919
+
920
+ def test_split_correctly_1(self):
921
+ batch = {
922
+ "image_grid_thw": torch.tensor([[1, 2, 2], [1, 2, 4]]),
923
+ "num_images": [1, 1],
924
+ "pixel_values": torch.arange(12 * 3).reshape(12, 3), # Shape: [12, 3]
925
+ }
926
+ result = split_pixel_values_by_grid(batch)
927
+ assert isinstance(result["pixel_values"], list)
928
+ assert len(result["pixel_values"]) == 2
929
+ assert torch.equal(result["pixel_values"][0], batch["pixel_values"][:4])
930
+ assert torch.equal(result["pixel_values"][1], batch["pixel_values"][4:12])
931
+ assert isinstance(result["image_grid_thw"], list)
932
+ assert len(result["image_grid_thw"]) == 2
933
+ assert torch.equal(result["image_grid_thw"][0], torch.tensor([[1, 2, 2]]))
934
+ assert torch.equal(result["image_grid_thw"][1], torch.tensor([[1, 2, 4]]))
935
+
936
+ def test_missing_keys(self):
937
+ batch = {"pixel_values": torch.tensor([1.0])}
938
+ result = split_pixel_values_by_grid(batch)
939
+ assert result == batch
940
+
941
+ def test_mismatched_length(self):
942
+ batch = {
943
+ "image_grid_thw": torch.tensor([[1, 1, 2], [1, 2, 1]]), # Total = 8
944
+ "num_images": [1, 1],
945
+ "pixel_values": torch.randn(3, 5), # Only 3 rows
946
+ }
947
+ with pytest.raises(ValueError):
948
+ split_pixel_values_by_grid(batch)
949
+
950
+ def test_multi_images(self):
951
+ batch = {
952
+ "image_grid_thw": torch.tensor([[1, 1, 2], [1, 2, 2], [1, 2, 1]]), # Total = 8
953
+ "num_images": [1, 2],
954
+ "pixel_values": torch.arange(8 * 3).reshape(8, 3), # Shape: [8, 3]
955
+ }
956
+ result = split_pixel_values_by_grid(batch)
957
+ assert isinstance(result["pixel_values"], list)
958
+ assert len(result["pixel_values"]) == 2
959
+ assert torch.equal(result["pixel_values"][0], batch["pixel_values"][:2])
960
+ assert torch.equal(result["pixel_values"][1], batch["pixel_values"][2:])
961
+ assert isinstance(result["image_grid_thw"], list)
962
+ assert len(result["image_grid_thw"]) == 2
963
+ assert torch.equal(result["image_grid_thw"][0], torch.tensor([[1, 1, 2]]))
964
+ assert torch.equal(result["image_grid_thw"][1], torch.tensor([[1, 2, 2], [1, 2, 1]]))
965
+
966
+ def test_split_by_image_position_ids(self):
967
+ # Gemma-style: no image_grid_thw, split by num_images using image_position_ids
968
+ batch = {
969
+ "num_images": [1, 2],
970
+ "pixel_values": torch.arange(3 * 4).reshape(3, 4),
971
+ "image_position_ids": torch.tensor([[0, 1], [2, 3], [4, 5]]),
972
+ }
973
+ result = split_pixel_values_by_grid(batch)
974
+ assert isinstance(result["pixel_values"], list)
975
+ assert len(result["pixel_values"]) == 2
976
+ assert torch.equal(result["pixel_values"][0], batch["pixel_values"][:1])
977
+ assert torch.equal(result["pixel_values"][1], batch["pixel_values"][1:])
978
+ assert isinstance(result["image_position_ids"], list)
979
+ assert len(result["image_position_ids"]) == 2
980
+ assert torch.equal(result["image_position_ids"][0], batch["image_position_ids"][:1])
981
+ assert torch.equal(result["image_position_ids"][1], batch["image_position_ids"][1:])
982
+
983
+
984
+ class TestUnsplitPixelValuesByGrid(TrlTestCase):
985
+ def test_unsplit_correctly(self):
986
+ pixel_values = [torch.randn(4, 5), torch.randn(2, 5)]
987
+ pixel_values_merged = torch.cat(pixel_values, dim=0)
988
+ image_grid_thw = [torch.tensor([[1, 2, 2]]), torch.tensor([[1, 2, 1]])]
989
+ image_grid_thw_merged = torch.cat(image_grid_thw, dim=0)
990
+ batch = {"pixel_values": pixel_values, "image_grid_thw": image_grid_thw, "other_key": torch.tensor([1])}
991
+ result = unsplit_pixel_values_by_grid(batch)
992
+ assert isinstance(result["pixel_values"], torch.Tensor)
993
+ torch.testing.assert_close(result["pixel_values"], pixel_values_merged)
994
+ assert isinstance(result["image_grid_thw"], torch.Tensor)
995
+ assert torch.equal(result["image_grid_thw"], image_grid_thw_merged)
996
+ assert "other_key" in result
997
+
998
+ def test_unsplit_image_position_ids(self):
999
+ image_position_ids = [torch.tensor([[0, 1]]), torch.tensor([[2, 3], [4, 5]])]
1000
+ image_position_ids_merged = torch.cat(image_position_ids, dim=0)
1001
+ pixel_values = [torch.randn(1, 4), torch.randn(2, 4)]
1002
+ batch = {"pixel_values": pixel_values, "image_position_ids": image_position_ids}
1003
+ result = unsplit_pixel_values_by_grid(batch)
1004
+ assert isinstance(result["image_position_ids"], torch.Tensor)
1005
+ assert torch.equal(result["image_position_ids"], image_position_ids_merged)
1006
+
1007
+ def test_no_op_if_not_list(self):
1008
+ original = torch.randn(5, 3)
1009
+ batch = {"pixel_values": original}
1010
+ result = unsplit_pixel_values_by_grid(batch)
1011
+ assert torch.equal(result["pixel_values"], original)
1012
+
1013
+
1014
+ class TestChunkedLogProbFunction:
1015
+ N, H, V = 64, 32, 128
1016
+ CHUNK_SIZE = 32
1017
+
1018
+ def _reference_logprobs_and_entropy(self, hidden, weight, labels, temperature):
1019
+ logits = (hidden @ weight.t()).to(torch.float32) / temperature # [N, V]
1020
+ log_p = F.log_softmax(logits, dim=-1)
1021
+ logprobs = log_p.gather(-1, labels.unsqueeze(-1)).squeeze(-1)
1022
+ p = torch.softmax(logits, dim=-1)
1023
+ entropy = -(p * log_p).sum(dim=-1)
1024
+ return logprobs, entropy
1025
+
1026
+ @pytest.mark.parametrize("temperature", [1.0, 0.7])
1027
+ def test_forward(self, temperature):
1028
+ torch.manual_seed(42)
1029
+ hidden = torch.randn(self.N, self.H)
1030
+ weight = torch.randn(self.V, self.H)
1031
+ labels = torch.randint(0, self.V, (self.N,))
1032
+
1033
+ logprobs_chunked, entropy_chunked = _ChunkedLogProbFunction.apply(
1034
+ hidden, weight, labels, temperature, self.CHUNK_SIZE
1035
+ )
1036
+ logprobs_ref, entropy_ref = self._reference_logprobs_and_entropy(hidden, weight, labels, temperature)
1037
+
1038
+ torch.testing.assert_close(logprobs_chunked, logprobs_ref, atol=1e-5, rtol=1e-5)
1039
+ torch.testing.assert_close(entropy_chunked, entropy_ref, atol=1e-5, rtol=1e-5)
1040
+
1041
+ @pytest.mark.parametrize("temperature", [1.0, 0.7])
1042
+ def test_backward(self, temperature):
1043
+ torch.manual_seed(42)
1044
+ hidden = torch.randn(self.N, self.H, requires_grad=True)
1045
+ weight = torch.randn(self.V, self.H, requires_grad=True)
1046
+ labels = torch.randint(0, self.V, (self.N,))
1047
+
1048
+ # Chunked backward
1049
+ logprobs_chunked, _ = _ChunkedLogProbFunction.apply(hidden, weight, labels, temperature, self.CHUNK_SIZE)
1050
+ logprobs_chunked.sum().backward()
1051
+ grad_hidden_chunked = hidden.grad.clone()
1052
+ grad_weight_chunked = weight.grad.clone()
1053
+
1054
+ hidden.grad = None
1055
+ weight.grad = None
1056
+
1057
+ # Reference backward
1058
+ logprobs_ref, _ = self._reference_logprobs_and_entropy(hidden, weight, labels, temperature)
1059
+ logprobs_ref.sum().backward()
1060
+
1061
+ torch.testing.assert_close(grad_hidden_chunked, hidden.grad, atol=1e-5, rtol=1e-5)
1062
+ torch.testing.assert_close(grad_weight_chunked, weight.grad, atol=1e-5, rtol=1e-5)
1063
+
1064
+ @pytest.mark.parametrize("temperature", [1.0, 0.7])
1065
+ def test_backward_bfloat16(self, temperature):
1066
+ torch.manual_seed(42)
1067
+ hidden = torch.randn(self.N, self.H, dtype=torch.bfloat16, requires_grad=True)
1068
+ weight = torch.randn(self.V, self.H, dtype=torch.bfloat16, requires_grad=True)
1069
+ labels = torch.randint(0, self.V, (self.N,))
1070
+
1071
+ # Chunked backward
1072
+ logprobs_chunked, _ = _ChunkedLogProbFunction.apply(hidden, weight, labels, temperature, self.CHUNK_SIZE)
1073
+ logprobs_chunked.sum().backward()
1074
+ grad_hidden_chunked = hidden.grad.clone()
1075
+ grad_weight_chunked = weight.grad.clone()
1076
+
1077
+ hidden.grad = None
1078
+ weight.grad = None
1079
+
1080
+ # Reference backward
1081
+ logprobs_ref, _ = self._reference_logprobs_and_entropy(hidden, weight, labels, temperature)
1082
+ logprobs_ref.sum().backward()
1083
+
1084
+ torch.testing.assert_close(grad_hidden_chunked, hidden.grad, atol=1e-2, rtol=1e-2)
1085
+ torch.testing.assert_close(grad_weight_chunked, weight.grad, atol=1e-2, rtol=1e-2)
1086
+
1087
+
1088
+ class _FakeTransformerModel(nn.Module):
1089
+ """Minimal stand-in for a transformer body: returns random hidden states of the right shape."""
1090
+
1091
+ def __init__(self, hidden_size):
1092
+ super().__init__()
1093
+ self.hidden_size = hidden_size
1094
+ self._hidden = None
1095
+
1096
+ def forward(self, input_ids, attention_mask=None, use_cache=False, **kwargs):
1097
+ b, s = input_ids.shape
1098
+ if self._hidden is None or self._hidden.shape[:2] != (b, s):
1099
+ torch.manual_seed(123)
1100
+ self._hidden = torch.randn(b, s, self.hidden_size, requires_grad=True)
1101
+ return type("Out", (), {"last_hidden_state": self._hidden})()
1102
+
1103
+
1104
+ class _FakeCausalLM(nn.Module):
1105
+ """Minimal CausalLM with .model and .lm_head, enough for patch_chunked_lm_head."""
1106
+
1107
+ def __init__(self, hidden_size, vocab_size):
1108
+ super().__init__()
1109
+ self.config = type("Config", (), {})()
1110
+ self.model = _FakeTransformerModel(hidden_size)
1111
+ self.lm_head = nn.Linear(hidden_size, vocab_size, bias=False)
1112
+
1113
+ def forward(self, input_ids, attention_mask=None, labels=None, **kwargs):
1114
+ raise NotImplementedError("should be monkey-patched")
1115
+
1116
+
1117
+ _CHUNKED_LM_HEAD_MODEL_IDS = [
1118
+ "trl-internal-testing/tiny-CohereForCausalLM",
1119
+ "trl-internal-testing/tiny-Cohere2ForCausalLM",
1120
+ pytest.param(
1121
+ "trl-internal-testing/tiny-DeepseekV3ForCausalLM",
1122
+ marks=pytest.mark.skipif(
1123
+ Version(transformers.__version__) < Version("5.0.0"),
1124
+ reason="DeepseekV3 SDPA attention is broken in transformers < 5.0.0",
1125
+ ),
1126
+ ),
1127
+ pytest.param(
1128
+ "trl-internal-testing/tiny-DeepseekV3ForCausalLM-0528",
1129
+ marks=pytest.mark.skipif(
1130
+ Version(transformers.__version__) < Version("5.0.0"),
1131
+ reason="DeepseekV3 SDPA attention is broken in transformers < 5.0.0",
1132
+ ),
1133
+ ),
1134
+ "trl-internal-testing/tiny-Gemma2ForCausalLM",
1135
+ "trl-internal-testing/tiny-GemmaForCausalLM",
1136
+ "trl-internal-testing/tiny-Glm4MoeForCausalLM",
1137
+ "trl-internal-testing/tiny-GptOssForCausalLM",
1138
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.1",
1139
+ "trl-internal-testing/tiny-LlamaForCausalLM-3.2",
1140
+ "trl-internal-testing/tiny-LlamaForCausalLM-3",
1141
+ "trl-internal-testing/tiny-MistralForCausalLM-0.1",
1142
+ "trl-internal-testing/tiny-MistralForCausalLM-0.2",
1143
+ pytest.param(
1144
+ "trl-internal-testing/tiny-NemotronHForCausalLM-nano",
1145
+ marks=pytest.mark.skipif(
1146
+ Version(transformers.__version__) < Version("5.3.0"),
1147
+ reason="Nemotron 3 was introduced in transformers>=5.3.0",
1148
+ ),
1149
+ ),
1150
+ pytest.param(
1151
+ "trl-internal-testing/tiny-Olmo3ForCausalLM",
1152
+ marks=pytest.mark.skipif(
1153
+ Version(transformers.__version__) < Version("4.57.0"),
1154
+ reason="Olmo 3 was introduced in transformers>=4.57.0",
1155
+ ),
1156
+ ),
1157
+ "trl-internal-testing/tiny-Phi3ForCausalLM-3",
1158
+ "trl-internal-testing/tiny-Phi3ForCausalLM-3.5",
1159
+ "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
1160
+ "trl-internal-testing/tiny-Qwen3ForCausalLM",
1161
+ "trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507",
1162
+ ]
1163
+
1164
+
1165
+ @require_torch_accelerator
1166
+ class TestPatchChunkedLMHead:
1167
+ B, S = 4, 16 # batch size, sequence length (including prompt + completion)
1168
+ H, V = 32, 128
1169
+ CHUNK_SIZE = 32
1170
+
1171
+ def _build_model_and_inputs(self, temperature=1.0):
1172
+ torch.manual_seed(42)
1173
+ model = _FakeCausalLM(self.H, self.V)
1174
+ patch_chunked_lm_head(model, self.CHUNK_SIZE, temperature)
1175
+
1176
+ input_ids = torch.randint(0, self.V, (self.B, self.S))
1177
+ attention_mask = torch.ones(self.B, self.S, dtype=torch.long)
1178
+ # First half of each sequence is prompt (0), second half is completion (1)
1179
+ completion_mask = torch.zeros(self.B, self.S, dtype=torch.float32)
1180
+ completion_mask[:, self.S // 2 :] = 1.0
1181
+ return model, input_ids, attention_mask, completion_mask
1182
+
1183
+ @pytest.mark.parametrize("temperature", [1.0, 0.7])
1184
+ def test_dummy_model_chunked_forward_with_completion_mask(self, temperature):
1185
+ """Masked forward matches unmasked forward at completion positions and is zero at prompt positions."""
1186
+ model, input_ids, attention_mask, completion_mask = self._build_model_and_inputs(temperature)
1187
+
1188
+ # Run WITHOUT completion_mask (baseline — computes all positions)
1189
+ out_full = model(input_ids=input_ids, attention_mask=attention_mask, labels=input_ids)
1190
+
1191
+ # Reset hidden state cache so both runs use the same hidden states
1192
+ model.model._hidden = None
1193
+
1194
+ # Run WITH completion_mask
1195
+ out_masked = model(
1196
+ input_ids=input_ids, attention_mask=attention_mask, labels=input_ids, completion_mask=completion_mask
1197
+ )
1198
+
1199
+ # shifted completion_mask (matching the shift in _chunked_forward)
1200
+ shifted_mask = completion_mask[:, 1:].bool()
1201
+
1202
+ # At completion positions, values should match
1203
+ torch.testing.assert_close(
1204
+ out_masked["log_probs"][shifted_mask],
1205
+ out_full["log_probs"][shifted_mask],
1206
+ atol=1e-5,
1207
+ rtol=1e-5,
1208
+ )
1209
+ torch.testing.assert_close(
1210
+ out_masked["entropy"][shifted_mask],
1211
+ out_full["entropy"][shifted_mask],
1212
+ atol=1e-5,
1213
+ rtol=1e-5,
1214
+ )
1215
+
1216
+ # At prompt positions, values should be zero
1217
+ prompt_mask = ~shifted_mask
1218
+ assert (out_masked["log_probs"][prompt_mask] == 0).all()
1219
+ assert (out_masked["entropy"][prompt_mask] == 0).all()
1220
+
1221
+ @pytest.mark.parametrize("temperature", [1.0, 0.7])
1222
+ def test_dummy_model_chunked_forward_completion_mask_backward(self, temperature):
1223
+ model, input_ids, attention_mask, completion_mask = self._build_model_and_inputs(temperature)
1224
+
1225
+ # Full forward + backward (mask applied after, as the trainer does)
1226
+ out_full = model(input_ids=input_ids, attention_mask=attention_mask, labels=input_ids)
1227
+ shifted_mask = completion_mask[:, 1:]
1228
+ loss_full = (out_full["log_probs"] * shifted_mask).sum()
1229
+ loss_full.backward()
1230
+ grad_weight_full = model.lm_head.weight.grad.clone()
1231
+
1232
+ model.lm_head.weight.grad = None
1233
+ model.model._hidden = None
1234
+
1235
+ # Masked forward + backward
1236
+ out_masked = model(
1237
+ input_ids=input_ids, attention_mask=attention_mask, labels=input_ids, completion_mask=completion_mask
1238
+ )
1239
+ loss_masked = (out_masked["log_probs"] * shifted_mask).sum()
1240
+ loss_masked.backward()
1241
+ grad_weight_masked = model.lm_head.weight.grad.clone()
1242
+
1243
+ torch.testing.assert_close(grad_weight_masked, grad_weight_full, atol=1e-5, rtol=1e-5)
1244
+
1245
+ @pytest.mark.parametrize("model_id", _CHUNKED_LM_HEAD_MODEL_IDS)
1246
+ @pytest.mark.parametrize("temperature", [1.0, 0.7])
1247
+ def test_forward(self, model_id, temperature):
1248
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16).to(torch_device)
1249
+ model.eval()
1250
+
1251
+ B, S, chunk_size = 2, 8, 32
1252
+ torch.manual_seed(42)
1253
+ input_ids = torch.randint(0, model.config.vocab_size, (B, S), device=torch_device)
1254
+ labels = input_ids.clone()
1255
+
1256
+ # Reference: standard forward → shifted logits → logprobs & entropy
1257
+ with torch.no_grad():
1258
+ ref_logits = model(input_ids=input_ids).logits[:, :-1, :].float() / temperature
1259
+ shifted_labels = labels[:, 1:]
1260
+ ref_log_p = F.log_softmax(ref_logits, dim=-1)
1261
+ ref_logprobs = ref_log_p.gather(-1, shifted_labels.unsqueeze(-1)).squeeze(-1)
1262
+ ref_p = ref_logits.softmax(dim=-1)
1263
+ ref_entropy = -(ref_p * ref_log_p).sum(dim=-1)
1264
+
1265
+ # Chunked forward
1266
+ patch_chunked_lm_head(model, chunk_size, temperature)
1267
+ with torch.no_grad():
1268
+ out = model(input_ids=input_ids, labels=labels)
1269
+
1270
+ torch.testing.assert_close(out["log_probs"], ref_logprobs, atol=5e-3, rtol=5e-3)
1271
+ torch.testing.assert_close(out["entropy"], ref_entropy, atol=5e-3, rtol=5e-3)
1272
+
1273
+ @pytest.mark.parametrize("model_id", _CHUNKED_LM_HEAD_MODEL_IDS)
1274
+ @pytest.mark.parametrize("temperature", [1.0, 0.7])
1275
+ def test_backward(self, model_id, temperature):
1276
+ model_ref = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16).to(torch_device)
1277
+ model_chunked = copy.deepcopy(model_ref)
1278
+
1279
+ B, S, chunk_size = 2, 8, 32
1280
+ torch.manual_seed(42)
1281
+ input_ids = torch.randint(0, model_ref.config.vocab_size, (B, S), device=torch_device)
1282
+ labels = input_ids.clone()
1283
+ shifted_labels = labels[:, 1:]
1284
+
1285
+ # Reference backward: standard logits → logprobs → backward
1286
+ ref_logits = model_ref(input_ids=input_ids).logits[:, :-1, :].float() / temperature
1287
+ ref_log_p = F.log_softmax(ref_logits, dim=-1)
1288
+ ref_logprobs = ref_log_p.gather(-1, shifted_labels.unsqueeze(-1)).squeeze(-1)
1289
+ ref_logprobs.sum().backward()
1290
+ ref_grad = model_ref.lm_head.weight.grad.clone()
1291
+
1292
+ # Chunked backward
1293
+ patch_chunked_lm_head(model_chunked, chunk_size, temperature)
1294
+ out = model_chunked(input_ids=input_ids, labels=labels)
1295
+ out["log_probs"].sum().backward()
1296
+ chunked_grad = model_chunked.lm_head.weight.grad.clone()
1297
+
1298
+ torch.testing.assert_close(chunked_grad, ref_grad, atol=5e-2, rtol=5e-2)
1299
+
1300
+
1301
+ class TestComputeFlopsPerToken(TrlTestCase):
1302
+ DENSE_MODEL_ID = "trl-internal-testing/tiny-Qwen3ForCausalLM"
1303
+ MOE_MODEL_ID = "trl-internal-testing/tiny-Qwen3MoeForCausalLM"
1304
+
1305
+ def test_seq_scaling_linear(self):
1306
+ # Attention-score FLOPs per token scale linearly with seq_len; everything else
1307
+ # is seq-len-independent. Doubling seq_len should double the seq-dependent delta,
1308
+ # which differences cancel out from. `F(32k) - F(16k) == 2 * (F(16k) - F(8k))`.
1309
+ cfg = AutoConfig.from_pretrained(self.DENSE_MODEL_ID)
1310
+ f_8k = compute_flops_per_token(cfg, 8192)
1311
+ f_16k = compute_flops_per_token(cfg, 16384)
1312
+ f_32k = compute_flops_per_token(cfg, 32768)
1313
+ assert f_32k - f_16k == 2 * (f_16k - f_8k)
1314
+
1315
+ def test_tied_vs_untied_lm_head(self):
1316
+ # Untied lm_head adds `2 * V * h` forward FLOPs, ×3 for fwd+bwd.
1317
+ cfg = AutoConfig.from_pretrained(self.DENSE_MODEL_ID)
1318
+ cfg.tie_word_embeddings = True
1319
+ f_tied = compute_flops_per_token(cfg, 16384)
1320
+ cfg.tie_word_embeddings = False
1321
+ f_untied = compute_flops_per_token(cfg, 16384)
1322
+ expected_delta = 3 * 2 * cfg.vocab_size * cfg.hidden_size
1323
+ assert f_untied - f_tied == expected_delta
1324
+
1325
+ def test_moe_active_vs_total_experts(self):
1326
+ # Doubling `num_experts_per_tok` (active experts) changes FLOPs by exactly the
1327
+ # routed-experts contribution: `num_experts_per_tok × 3 matmuls × 2 × h × moe_intermediate`
1328
+ # per MoE layer, ×3 for fwd+bwd. Holding `num_local_experts` constant pins the
1329
+ # router term so the delta is purely the active-expert math.
1330
+ cfg = AutoConfig.from_pretrained(self.MOE_MODEL_ID)
1331
+ cfg.num_experts_per_tok = 1
1332
+ f_lo = compute_flops_per_token(cfg, 16384)
1333
+ cfg.num_experts_per_tok = 2
1334
+ f_hi = compute_flops_per_token(cfg, 16384)
1335
+ moe_layers = sum(1 for i in range(cfg.num_hidden_layers) if i % cfg.decoder_sparse_step == 0)
1336
+ per_expert_per_layer = 2 * 3 * cfg.hidden_size * cfg.moe_intermediate_size
1337
+ expected_delta = 3 * moe_layers * (2 - 1) * per_expert_per_layer
1338
+ assert f_hi - f_lo == expected_delta
1339
+
1340
+
1341
+ class TestComputeMfu(TrlTestCase):
1342
+ def test_perfect_utilization(self):
1343
+ # If aggregate TPS is exactly `peak * world_size / flops_per_token`, MFU is 100%.
1344
+ flops = 100e9
1345
+ peak = 989.5e12
1346
+ world_size = 8
1347
+ tps = peak * world_size / flops
1348
+ assert compute_mfu(flops, tps, world_size, peak_flops_per_device=peak) == pytest.approx(100.0)
1349
+
1350
+
1351
+ class TestAdjustedMfu(TrlTestCase):
1352
+ MOE_MODEL_ID = "trl-internal-testing/tiny-Qwen3MoeForCausalLM"
1353
+
1354
+ def test_consistent_with_formula(self):
1355
+ # `adjusted_mfu(mfu, cfg, seq_len) == mfu * (full - half_attn) / full`, with
1356
+ # `full = compute_flops_per_token(cfg, seq_len)` and
1357
+ # `half_attn = L * 3 * 2 * n_heads * head_dim * seq_len`. Cross-check the two helpers.
1358
+ cfg = AutoConfig.from_pretrained(self.MOE_MODEL_ID)
1359
+ seq_len = 16384
1360
+ flops_full = compute_flops_per_token(cfg, seq_len)
1361
+ half_attn = cfg.num_hidden_layers * 3 * 2 * cfg.num_attention_heads * cfg.head_dim * seq_len
1362
+ expected = 100.0 * (flops_full - half_attn) / flops_full
1363
+ assert adjusted_mfu(100.0, cfg, seq_len) == pytest.approx(expected)
1364
+
1365
+ def test_proportional_to_input(self):
1366
+ # The correction is purely multiplicative in `mfu`. `adjusted_mfu(2*x, ...)` should
1367
+ # equal `2 * adjusted_mfu(x, ...)`.
1368
+ cfg = AutoConfig.from_pretrained(self.MOE_MODEL_ID)
1369
+ a = adjusted_mfu(50.0, cfg, 16384)
1370
+ b = adjusted_mfu(100.0, cfg, 16384)
1371
+ assert b == pytest.approx(2 * a)
1372
+
1373
+ def test_decreases_with_seq_len(self):
1374
+ # Longer sequences → attention takes a larger share of total compute → causal
1375
+ # correction subtracts a larger absolute amount → factor strictly decreases.
1376
+ cfg = AutoConfig.from_pretrained(self.MOE_MODEL_ID)
1377
+ f_short = adjusted_mfu(100.0, cfg, 4096)
1378
+ f_med = adjusted_mfu(100.0, cfg, 16384)
1379
+ f_long = adjusted_mfu(100.0, cfg, 65536)
1380
+ assert f_short > f_med > f_long
tasks/tasksmith-5b4f21a2a450/tests/source/tests/test_vllm_client_server.py ADDED
@@ -0,0 +1,1036 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 subprocess
17
+ from types import SimpleNamespace
18
+
19
+ import pytest
20
+ from packaging.version import Version
21
+ from transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer
22
+ from transformers.testing_utils import torch_device
23
+
24
+ from trl.generation.vllm_client import VLLMClient
25
+ from trl.generation.vllm_generation import extract_logprobs
26
+ from trl.import_utils import is_vllm_available
27
+ from trl.scripts.vllm_serve import chunk_list
28
+
29
+ from .testing_utils import (
30
+ TrlTestCase,
31
+ kill_process,
32
+ require_3_accelerators,
33
+ require_torch_multi_accelerator,
34
+ require_vision,
35
+ require_vllm,
36
+ )
37
+
38
+
39
+ if is_vllm_available():
40
+ import vllm
41
+ from vllm import LLM, SamplingParams
42
+
43
+ _is_vllm_ge_014 = Version(vllm.__version__) >= Version("0.14.0")
44
+ else:
45
+ _is_vllm_ge_014 = False
46
+
47
+
48
+ class TestChunkList(TrlTestCase):
49
+ def test_even_split(self):
50
+ assert chunk_list([1, 2, 3, 4, 5, 6], 2) == [[1, 2, 3], [4, 5, 6]]
51
+
52
+ def test_uneven_split(self):
53
+ assert chunk_list([1, 2, 3, 4, 5, 6], 4) == [[1, 2], [3, 4], [5], [6]]
54
+
55
+ def test_more_chunks_than_elements(self):
56
+ assert chunk_list([1, 2, 3, 4, 5, 6], 8) == [[1], [2], [3], [4], [5], [6], [], []]
57
+
58
+ def test_n_equals_len(self):
59
+ assert chunk_list([1, 2, 3], 3) == [[1], [2], [3]]
60
+
61
+ def test_n_is_1(self):
62
+ assert chunk_list([1, 2, 3], 1) == [[1, 2, 3]]
63
+
64
+ def test_single_element_list(self):
65
+ assert chunk_list([42], 2) == [[42], []]
66
+
67
+ def test_any_dtype(self):
68
+ assert chunk_list([1, "two", 3.0, {"four": 4}, ["f", "i", "v", "e"]], 2) == [
69
+ [1, "two", 3.0],
70
+ [{"four": 4}, ["f", "i", "v", "e"]],
71
+ ]
72
+
73
+
74
+ class TestExtractLogprobs(TrlTestCase):
75
+ def test_extract_logprobs_sorts_by_rank_and_replaces_nan(self):
76
+ all_outputs = [
77
+ SimpleNamespace(
78
+ outputs=[
79
+ SimpleNamespace(
80
+ logprobs=[
81
+ {
82
+ 11: SimpleNamespace(rank=1, logprob=-0.2),
83
+ 99: SimpleNamespace(rank=0, logprob=-0.1),
84
+ 42: SimpleNamespace(rank=2, logprob=float("nan")),
85
+ },
86
+ {
87
+ 5: SimpleNamespace(rank=0, logprob=-1.1),
88
+ },
89
+ ]
90
+ )
91
+ ]
92
+ ),
93
+ SimpleNamespace(
94
+ outputs=[
95
+ SimpleNamespace(
96
+ logprobs=[
97
+ {
98
+ 3: SimpleNamespace(rank=1, logprob=-0.5),
99
+ 7: SimpleNamespace(rank=0, logprob=-0.4),
100
+ }
101
+ ]
102
+ )
103
+ ]
104
+ ),
105
+ ]
106
+
107
+ all_logprobs, all_token_ids = extract_logprobs(all_outputs)
108
+
109
+ assert all_token_ids == [
110
+ [[99, 11, 42], [5]],
111
+ [[7, 3]],
112
+ ]
113
+ assert all_logprobs == [
114
+ [[-0.1, -0.2, None], [-1.1]],
115
+ [[-0.4, -0.5]],
116
+ ]
117
+
118
+ def test_extract_logprobs_returns_none_token_ids_when_logprobs_missing(self):
119
+ all_outputs = [SimpleNamespace(outputs=[SimpleNamespace(logprobs=None)])]
120
+
121
+ all_logprobs, all_token_ids = extract_logprobs(all_outputs)
122
+
123
+ assert all_logprobs is None
124
+ assert all_token_ids is None
125
+
126
+
127
+ @pytest.mark.slow
128
+ @require_torch_multi_accelerator
129
+ @require_vllm
130
+ class TestVLLMClientServer(TrlTestCase):
131
+ model_id = "Qwen/Qwen2.5-1.5B"
132
+
133
+ @classmethod
134
+ def setup_class(cls):
135
+ # We want the server to run on accelerator 1, so we set VISIBLE_DEVICES to "1"
136
+ env = os.environ.copy()
137
+ VISIBLE_DEVICES = "ZE_AFFINITY_MASK" if torch_device == "xpu" else "CUDA_VISIBLE_DEVICES"
138
+ env[VISIBLE_DEVICES] = "1" # Restrict to accelerator 1
139
+
140
+ # Start the server process
141
+ cls.server_process = subprocess.Popen(
142
+ ["trl", "vllm-serve", "--model", cls.model_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env
143
+ )
144
+
145
+ # Initialize the client
146
+ cls.client = VLLMClient(connection_timeout=240, host="localhost")
147
+ cls.client.init_communicator()
148
+
149
+ def test_generate(self):
150
+ prompts = ["Hello, AI!", "Tell me a joke"]
151
+ outputs = self.client.generate(prompts)
152
+ prompt_ids = outputs["prompt_ids"]
153
+ completion_ids = outputs["completion_ids"]
154
+
155
+ # Check that the outputs are lists
156
+ assert isinstance(prompt_ids, list)
157
+ assert isinstance(completion_ids, list)
158
+
159
+ # Check that the number of sequences are equal to the number of prompts
160
+ assert len(prompt_ids) == len(prompts)
161
+ assert len(completion_ids) == len(prompts)
162
+
163
+ # Check that the sequences are lists of integers
164
+ for seq in prompt_ids:
165
+ assert all(isinstance(tok, int) for tok in seq)
166
+ for seq in completion_ids:
167
+ assert all(isinstance(tok, int) for tok in seq)
168
+
169
+ def test_generate_with_logprobs_none(self):
170
+ outputs = self.client.generate(["Hello, AI!"], logprobs=None)
171
+
172
+ assert isinstance(outputs["prompt_ids"], list)
173
+ assert isinstance(outputs["completion_ids"], list)
174
+ assert outputs["logprobs"] is None
175
+ assert outputs["logprob_token_ids"] is None
176
+
177
+ def test_chat(self):
178
+ messages = [[{"role": "user", "content": "Hello, AI!"}], [{"role": "user", "content": "Tell me a joke"}]]
179
+ outputs = self.client.chat(messages)
180
+ prompt_ids = outputs["prompt_ids"]
181
+ completion_ids = outputs["completion_ids"]
182
+
183
+ # Check that the outputs are lists
184
+ assert isinstance(prompt_ids, list)
185
+ assert isinstance(completion_ids, list)
186
+
187
+ # Check that the number of sequences are equal to the number of messages
188
+ assert len(prompt_ids) == len(messages)
189
+ assert len(completion_ids) == len(messages)
190
+
191
+ # Check that the sequences are lists of integers
192
+ for seq in prompt_ids:
193
+ assert all(isinstance(tok, int) for tok in seq)
194
+ for seq in completion_ids:
195
+ assert all(isinstance(tok, int) for tok in seq)
196
+
197
+ def test_chat_with_logprobs_none(self):
198
+ outputs = self.client.chat([[{"role": "user", "content": "Hello, AI!"}]], logprobs=None)
199
+
200
+ assert isinstance(outputs["prompt_ids"], list)
201
+ assert isinstance(outputs["completion_ids"], list)
202
+ assert outputs["logprobs"] is None
203
+ assert outputs["logprob_token_ids"] is None
204
+
205
+ def test_chat_with_tools(self):
206
+ def multiply(a: int, b: int) -> int:
207
+ """
208
+ Multiplies two integers.
209
+
210
+ Args:
211
+ a: The first integer.
212
+ b: The second integer.
213
+
214
+ Returns:
215
+ The product of the two integers.
216
+ """
217
+ return a * b
218
+
219
+ messages = [[{"role": "user", "content": "What is 3 multiplied by 4?"}]]
220
+ outputs = self.client.chat(messages, tools=[multiply])
221
+
222
+ # Decode prompt and check that "Multiplies two integers." is in the prompt.
223
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id)
224
+ decoded_prompt = tokenizer.decode(outputs["prompt_ids"][0])
225
+ assert "Multiplies two integers." in decoded_prompt
226
+
227
+ def test_generate_with_token_ids(self):
228
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id)
229
+ prompts = ["Hello, AI!", "Tell me a joke"]
230
+ prompt_token_ids = tokenizer(prompts)["input_ids"]
231
+ outputs = self.client.generate(prompt_token_ids)
232
+ prompt_ids = outputs["prompt_ids"]
233
+ completion_ids = outputs["completion_ids"]
234
+
235
+ # Check that the outputs are lists
236
+ assert isinstance(prompt_ids, list)
237
+ assert isinstance(completion_ids, list)
238
+
239
+ # Check that the number of sequences are equal to the number of prompts
240
+ assert len(prompt_ids) == len(prompts)
241
+ assert len(completion_ids) == len(prompts)
242
+
243
+ # Check that prompt_ids match the input token IDs
244
+ assert prompt_ids == prompt_token_ids
245
+
246
+ # Check that the sequences are lists of integers
247
+ for seq in prompt_ids:
248
+ assert all(isinstance(tok, int) for tok in seq)
249
+ for seq in completion_ids:
250
+ assert all(isinstance(tok, int) for tok in seq)
251
+
252
+ def test_generate_with_params(self):
253
+ prompts = ["Hello, AI!", "Tell me a joke"]
254
+ completion_ids = self.client.generate(prompts, n=2, repetition_penalty=0.9, temperature=0.8, max_tokens=32)[
255
+ "completion_ids"
256
+ ]
257
+
258
+ # Check that the output is a list
259
+ assert isinstance(completion_ids, list)
260
+
261
+ # Check that the number of generated sequences is 2 times the number of prompts
262
+ assert len(completion_ids) == 2 * len(prompts)
263
+
264
+ # Check that the generated sequences are lists of integers
265
+ for seq in completion_ids:
266
+ assert all(isinstance(tok, int) for tok in seq)
267
+
268
+ # Check that the length of the generated sequences is less than or equal to 32
269
+ for seq in completion_ids:
270
+ assert len(seq) <= 32
271
+
272
+ def test_update_model_params(self):
273
+ model = AutoModelForCausalLM.from_pretrained(self.model_id, device_map=torch_device)
274
+ self.client.update_model_params(model)
275
+
276
+ def test_reset_prefix_cache(self):
277
+ # Test resetting the prefix cache
278
+ self.client.reset_prefix_cache()
279
+
280
+ @pytest.mark.xfail(reason="Importing `bitsandbytes` causes issues, see vllm-project/vllm#32793")
281
+ def test_logprobs_match_with_non_default_sampling(self):
282
+ prompts = ["Hello, AI!", "Tell me a joke"]
283
+ # Use non-default sampling parameters (especially temperature) to ensure vLLM applies logprob processing. With
284
+ # default sampling, raw and processed logprobs are identical, so mismatches would not be detected.
285
+ temperature = 0.7
286
+ repetition_penalty = 1.05
287
+ top_p = 0.9
288
+ max_tokens = 8
289
+ seed = 1234
290
+ num_logprobs = 5
291
+
292
+ server_outputs = self.client.generate(
293
+ prompts,
294
+ temperature=temperature,
295
+ repetition_penalty=repetition_penalty,
296
+ top_p=top_p,
297
+ max_tokens=max_tokens,
298
+ logprobs=num_logprobs,
299
+ generation_kwargs={"seed": seed},
300
+ )
301
+ os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
302
+ llm = LLM(
303
+ model=self.model_id,
304
+ tensor_parallel_size=1,
305
+ gpu_memory_utilization=0.2,
306
+ max_model_len=128,
307
+ logprobs_mode="processed_logprobs",
308
+ )
309
+
310
+ sampling_params = SamplingParams(
311
+ temperature=temperature,
312
+ repetition_penalty=repetition_penalty,
313
+ top_p=top_p,
314
+ max_tokens=max_tokens,
315
+ logprobs=num_logprobs,
316
+ seed=seed,
317
+ )
318
+ colocate_outputs = llm.generate(prompts, sampling_params=sampling_params, use_tqdm=False)
319
+ colocate_prompt_ids = [output.prompt_token_ids for output in colocate_outputs]
320
+ colocate_completion_ids = [
321
+ list(output.token_ids) for outputs in colocate_outputs for output in outputs.outputs
322
+ ]
323
+ colocate_logprobs, colocate_logprob_token_ids = extract_logprobs(colocate_outputs)
324
+
325
+ # Generation correctness: prompt and completion IDs match between server and colocate
326
+ assert server_outputs["prompt_ids"] == colocate_prompt_ids
327
+ assert server_outputs["completion_ids"] == colocate_completion_ids
328
+
329
+ server_logprobs = server_outputs["logprobs"]
330
+ server_logprob_token_ids = server_outputs["logprob_token_ids"]
331
+
332
+ # Shape: both should be (num_sequences, seq_len, num_logprobs) with multiple logprobs per token
333
+ assert len(server_logprobs) == len(prompts)
334
+ assert len(server_logprob_token_ids) == len(prompts)
335
+ for seq_lps in server_logprobs:
336
+ for token_lps in seq_lps:
337
+ assert len(token_lps) > 1, "Expected multiple logprobs per token when logprobs > 0"
338
+
339
+ # Value correctness: server extraction matches colocate extraction via extract_logprobs
340
+ assert server_logprob_token_ids == colocate_logprob_token_ids
341
+ for server_seq, colocate_seq in zip(server_logprobs, colocate_logprobs, strict=True):
342
+ assert len(server_seq) == len(colocate_seq)
343
+ for server_token_lps, colocate_token_lps in zip(server_seq, colocate_seq, strict=True):
344
+ assert server_token_lps == pytest.approx(colocate_token_lps, rel=1e-6, abs=1e-6)
345
+
346
+ # Ordering: logprobs at each position should be sorted descending
347
+ for seq_lps in server_logprobs:
348
+ for token_lps in seq_lps:
349
+ assert token_lps == sorted(token_lps, reverse=True), "Logprobs should be sorted descending"
350
+
351
+ # Sampled token presence: the actual completion token should appear in the logprob token IDs
352
+ for seq_idx, (completion_seq, token_ids_seq) in enumerate(
353
+ zip(server_outputs["completion_ids"], server_logprob_token_ids, strict=True)
354
+ ):
355
+ for pos, (sampled_id, lp_ids) in enumerate(zip(completion_seq, token_ids_seq, strict=True)):
356
+ assert sampled_id in lp_ids, (
357
+ f"Sampled token {sampled_id} not found in logprob token IDs {lp_ids} "
358
+ f"at sequence {seq_idx}, position {pos}"
359
+ )
360
+
361
+ @classmethod
362
+ def teardown_class(cls):
363
+ # Close the client
364
+ cls.client.close_communicator()
365
+
366
+ # vLLM x pytest (or Popen) seems not to handle process termination well. To avoid zombie processes, we need to
367
+ # kill the server process and its children explicitly.
368
+ kill_process(cls.server_process)
369
+
370
+
371
+ # Same as above but using base_url to instantiate the client.
372
+ @pytest.mark.slow
373
+ @require_torch_multi_accelerator
374
+ @require_vllm
375
+ class TestVLLMClientServerBaseURL(TrlTestCase):
376
+ model_id = "Qwen/Qwen2.5-1.5B"
377
+
378
+ @classmethod
379
+ def setup_class(cls):
380
+ # We want the server to run on accelerator 1, so we set VISIBLE_DEVICES to "1"
381
+ env = os.environ.copy()
382
+ VISIBLE_DEVICES = "ZE_AFFINITY_MASK" if torch_device == "xpu" else "CUDA_VISIBLE_DEVICES"
383
+ env[VISIBLE_DEVICES] = "1" # Restrict to accelerator 1
384
+
385
+ # Start the server process
386
+ cls.server_process = subprocess.Popen(
387
+ ["trl", "vllm-serve", "--model", cls.model_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env
388
+ )
389
+
390
+ # Initialize the client
391
+ cls.client = VLLMClient(base_url="http://localhost:8000", connection_timeout=240)
392
+ cls.client.init_communicator()
393
+
394
+ def test_generate(self):
395
+ prompts = ["Hello, AI!", "Tell me a joke"]
396
+ outputs = self.client.generate(prompts)
397
+ prompt_ids = outputs["prompt_ids"]
398
+ completion_ids = outputs["completion_ids"]
399
+
400
+ # Check that the outputs are lists
401
+ assert isinstance(prompt_ids, list)
402
+ assert isinstance(completion_ids, list)
403
+
404
+ # Check that the number of sequences are equal to the number of prompts
405
+ assert len(prompt_ids) == len(prompts)
406
+ assert len(completion_ids) == len(prompts)
407
+
408
+ # Check that the sequences are lists of integers
409
+ for seq in prompt_ids:
410
+ assert all(isinstance(tok, int) for tok in seq)
411
+ for seq in completion_ids:
412
+ assert all(isinstance(tok, int) for tok in seq)
413
+
414
+ def test_generate_with_logprobs_none(self):
415
+ outputs = self.client.generate(["Hello, AI!"], logprobs=None)
416
+
417
+ assert isinstance(outputs["prompt_ids"], list)
418
+ assert isinstance(outputs["completion_ids"], list)
419
+ assert outputs["logprobs"] is None
420
+ assert outputs["logprob_token_ids"] is None
421
+
422
+ def test_chat(self):
423
+ messages = [[{"role": "user", "content": "Hello, AI!"}], [{"role": "user", "content": "Tell me a joke"}]]
424
+ outputs = self.client.chat(messages)
425
+ prompt_ids = outputs["prompt_ids"]
426
+ completion_ids = outputs["completion_ids"]
427
+
428
+ # Check that the outputs are lists
429
+ assert isinstance(prompt_ids, list)
430
+ assert isinstance(completion_ids, list)
431
+
432
+ # Check that the number of sequences are equal to the number of messages
433
+ assert len(prompt_ids) == len(messages)
434
+ assert len(completion_ids) == len(messages)
435
+
436
+ # Check that the sequences are lists of integers
437
+ for seq in prompt_ids:
438
+ assert all(isinstance(tok, int) for tok in seq)
439
+ for seq in completion_ids:
440
+ assert all(isinstance(tok, int) for tok in seq)
441
+
442
+ def test_chat_with_logprobs_none(self):
443
+ outputs = self.client.chat([[{"role": "user", "content": "Hello, AI!"}]], logprobs=None)
444
+
445
+ assert isinstance(outputs["prompt_ids"], list)
446
+ assert isinstance(outputs["completion_ids"], list)
447
+ assert outputs["logprobs"] is None
448
+ assert outputs["logprob_token_ids"] is None
449
+
450
+ def test_chat_with_tools(self):
451
+ def multiply(a: int, b: int) -> int:
452
+ """
453
+ Multiplies two integers.
454
+
455
+ Args:
456
+ a: The first integer.
457
+ b: The second integer.
458
+
459
+ Returns:
460
+ The product of the two integers.
461
+ """
462
+ return a * b
463
+
464
+ messages = [[{"role": "user", "content": "What is 3 multiplied by 4?"}]]
465
+ outputs = self.client.chat(messages, tools=[multiply])
466
+
467
+ # Decode prompt and check that "Multiplies two integers." is in the prompt.
468
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id)
469
+ decoded_prompt = tokenizer.decode(outputs["prompt_ids"][0])
470
+ assert "Multiplies two integers." in decoded_prompt
471
+
472
+ def test_generate_with_token_ids(self):
473
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id)
474
+ prompts = ["Hello, AI!", "Tell me a joke"]
475
+ prompt_token_ids = tokenizer(prompts)["input_ids"]
476
+ outputs = self.client.generate(prompt_token_ids)
477
+ prompt_ids = outputs["prompt_ids"]
478
+ completion_ids = outputs["completion_ids"]
479
+
480
+ # Check that the outputs are lists
481
+ assert isinstance(prompt_ids, list)
482
+ assert isinstance(completion_ids, list)
483
+
484
+ # Check that the number of sequences are equal to the number of prompts
485
+ assert len(prompt_ids) == len(prompts)
486
+ assert len(completion_ids) == len(prompts)
487
+
488
+ # Check that prompt_ids match the input token IDs
489
+ assert prompt_ids == prompt_token_ids
490
+
491
+ # Check that the sequences are lists of integers
492
+ for seq in prompt_ids:
493
+ assert all(isinstance(tok, int) for tok in seq)
494
+ for seq in completion_ids:
495
+ assert all(isinstance(tok, int) for tok in seq)
496
+
497
+ def test_generate_with_params(self):
498
+ prompts = ["Hello, AI!", "Tell me a joke"]
499
+ completion_ids = self.client.generate(prompts, n=2, repetition_penalty=0.9, temperature=0.8, max_tokens=32)[
500
+ "completion_ids"
501
+ ]
502
+
503
+ # Check that the output is a list
504
+ assert isinstance(completion_ids, list)
505
+
506
+ # Check that the number of generated sequences is 2 times the number of prompts
507
+ assert len(completion_ids) == 2 * len(prompts)
508
+
509
+ # Check that the generated sequences are lists of integers
510
+ for seq in completion_ids:
511
+ assert all(isinstance(tok, int) for tok in seq)
512
+
513
+ # Check that the length of the generated sequences is less than or equal to 32
514
+ for seq in completion_ids:
515
+ assert len(seq) <= 32
516
+
517
+ def test_update_model_params(self):
518
+ model = AutoModelForCausalLM.from_pretrained(self.model_id, device_map=torch_device)
519
+ self.client.update_model_params(model)
520
+
521
+ def test_reset_prefix_cache(self):
522
+ # Test resetting the prefix cache
523
+ self.client.reset_prefix_cache()
524
+
525
+ @classmethod
526
+ def teardown_class(cls):
527
+ # Close the client
528
+ cls.client.close_communicator()
529
+
530
+ # vLLM x pytest (or Popen) seems not to handle process termination well. To avoid zombie processes, we need to
531
+ # kill the server process and its children explicitly.
532
+ kill_process(cls.server_process)
533
+
534
+
535
+ @pytest.mark.slow
536
+ @require_3_accelerators
537
+ @require_vllm
538
+ class TestVLLMClientServerTP(TrlTestCase):
539
+ model_id = "Qwen/Qwen2.5-1.5B"
540
+
541
+ @classmethod
542
+ def setup_class(cls):
543
+ # We want the server to run on accelerator 1 and 2, so we set VISIBLE_DEVICES to "1,2"
544
+ env = os.environ.copy()
545
+ VISIBLE_DEVICES = "ZE_AFFINITY_MASK" if torch_device == "xpu" else "CUDA_VISIBLE_DEVICES"
546
+ env[VISIBLE_DEVICES] = "1,2" # Restrict to accelerator 1 and 2
547
+
548
+ # Start the server process
549
+ cls.server_process = subprocess.Popen(
550
+ ["trl", "vllm-serve", "--model", cls.model_id, "--tensor_parallel_size", "2"],
551
+ stdout=subprocess.PIPE,
552
+ stderr=subprocess.PIPE,
553
+ env=env,
554
+ )
555
+
556
+ # Initialize the client
557
+ cls.client = VLLMClient(connection_timeout=240, host="localhost")
558
+ cls.client.init_communicator()
559
+
560
+ def test_generate(self):
561
+ prompts = ["Hello, AI!", "Tell me a joke"]
562
+ outputs = self.client.generate(prompts)
563
+ prompt_ids = outputs["prompt_ids"]
564
+ completion_ids = outputs["completion_ids"]
565
+
566
+ # Check that the outputs are lists
567
+ assert isinstance(prompt_ids, list)
568
+ assert isinstance(completion_ids, list)
569
+
570
+ # Check that the number of sequences are equal to the number of prompts
571
+ assert len(prompt_ids) == len(prompts)
572
+ assert len(completion_ids) == len(prompts)
573
+
574
+ # Check that the sequences are lists of integers
575
+ for seq in prompt_ids:
576
+ assert all(isinstance(tok, int) for tok in seq)
577
+ for seq in completion_ids:
578
+ assert all(isinstance(tok, int) for tok in seq)
579
+
580
+ def test_generate_with_logprobs_none(self):
581
+ outputs = self.client.generate(["Hello, AI!"], logprobs=None)
582
+
583
+ assert isinstance(outputs["prompt_ids"], list)
584
+ assert isinstance(outputs["completion_ids"], list)
585
+ assert outputs["logprobs"] is None
586
+ assert outputs["logprob_token_ids"] is None
587
+
588
+ def test_chat(self):
589
+ messages = [[{"role": "user", "content": "Hello, AI!"}], [{"role": "user", "content": "Tell me a joke"}]]
590
+ outputs = self.client.chat(messages)
591
+ prompt_ids = outputs["prompt_ids"]
592
+ completion_ids = outputs["completion_ids"]
593
+
594
+ # Check that the outputs are lists
595
+ assert isinstance(prompt_ids, list)
596
+ assert isinstance(completion_ids, list)
597
+
598
+ # Check that the number of sequences are equal to the number of messages
599
+ assert len(prompt_ids) == len(messages)
600
+ assert len(completion_ids) == len(messages)
601
+
602
+ # Check that the sequences are lists of integers
603
+ for seq in prompt_ids:
604
+ assert all(isinstance(tok, int) for tok in seq)
605
+ for seq in completion_ids:
606
+ assert all(isinstance(tok, int) for tok in seq)
607
+
608
+ def test_chat_with_logprobs_none(self):
609
+ outputs = self.client.chat([[{"role": "user", "content": "Hello, AI!"}]], logprobs=None)
610
+
611
+ assert isinstance(outputs["prompt_ids"], list)
612
+ assert isinstance(outputs["completion_ids"], list)
613
+ assert outputs["logprobs"] is None
614
+ assert outputs["logprob_token_ids"] is None
615
+
616
+ def test_chat_with_tools(self):
617
+ def multiply(a: int, b: int) -> int:
618
+ """
619
+ Multiplies two integers.
620
+
621
+ Args:
622
+ a: The first integer.
623
+ b: The second integer.
624
+
625
+ Returns:
626
+ The product of the two integers.
627
+ """
628
+ return a * b
629
+
630
+ messages = [[{"role": "user", "content": "What is 3 multiplied by 4?"}]]
631
+ outputs = self.client.chat(messages, tools=[multiply])
632
+
633
+ # Decode prompt and check that "Multiplies two integers." is in the prompt.
634
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id)
635
+ decoded_prompt = tokenizer.decode(outputs["prompt_ids"][0])
636
+ assert "Multiplies two integers." in decoded_prompt
637
+
638
+ def test_generate_with_token_ids(self):
639
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id)
640
+ prompts = ["Hello, AI!", "Tell me a joke"]
641
+ prompt_token_ids = tokenizer(prompts)["input_ids"]
642
+ outputs = self.client.generate(prompt_token_ids)
643
+ prompt_ids = outputs["prompt_ids"]
644
+ completion_ids = outputs["completion_ids"]
645
+
646
+ # Check that the outputs are lists
647
+ assert isinstance(prompt_ids, list)
648
+ assert isinstance(completion_ids, list)
649
+
650
+ # Check that the number of sequences are equal to the number of prompts
651
+ assert len(prompt_ids) == len(prompts)
652
+ assert len(completion_ids) == len(prompts)
653
+
654
+ # Check that prompt_ids match the input token IDs
655
+ assert prompt_ids == prompt_token_ids
656
+
657
+ # Check that the sequences are lists of integers
658
+ for seq in prompt_ids:
659
+ assert all(isinstance(tok, int) for tok in seq)
660
+ for seq in completion_ids:
661
+ assert all(isinstance(tok, int) for tok in seq)
662
+
663
+ def test_generate_with_params(self):
664
+ prompts = ["Hello, AI!", "Tell me a joke"]
665
+ completion_ids = self.client.generate(prompts, n=2, repetition_penalty=0.9, temperature=0.8, max_tokens=32)[
666
+ "completion_ids"
667
+ ]
668
+
669
+ # Check that the output is a list
670
+ assert isinstance(completion_ids, list)
671
+
672
+ # Check that the number of generated sequences is 2 times the number of prompts
673
+ assert len(completion_ids) == 2 * len(prompts)
674
+
675
+ # Check that the generated sequences are lists of integers
676
+ for seq in completion_ids:
677
+ assert all(isinstance(tok, int) for tok in seq)
678
+
679
+ # Check that the length of the generated sequences is less than or equal to 32
680
+ for seq in completion_ids:
681
+ assert len(seq) <= 32
682
+
683
+ def test_update_model_params(self):
684
+ model = AutoModelForCausalLM.from_pretrained(self.model_id, device_map=torch_device)
685
+ self.client.update_model_params(model)
686
+
687
+ def test_reset_prefix_cache(self):
688
+ # Test resetting the prefix cache
689
+ self.client.reset_prefix_cache()
690
+
691
+ @classmethod
692
+ def teardown_class(cls):
693
+ # Close the client
694
+ cls.client.close_communicator()
695
+
696
+ # vLLM x pytest (or Popen) seems not to handle process termination well. To avoid zombie processes, we need to
697
+ # kill the server process and its children explicitly.
698
+ kill_process(cls.server_process)
699
+
700
+
701
+ @pytest.mark.slow
702
+ @pytest.mark.skipif(
703
+ _is_vllm_ge_014,
704
+ reason="Skipping DP server test for vLLM>=0.14.0 (PR vllm#30739: DP for non-MoE/dense models no longer supported).",
705
+ )
706
+ @require_3_accelerators
707
+ @require_vllm
708
+ class TestVLLMClientServerDP(TrlTestCase):
709
+ model_id = "Qwen/Qwen2.5-1.5B"
710
+
711
+ @classmethod
712
+ def setup_class(cls):
713
+ # We want the server to run on accelerator 1 and 2, so we set VISIBLE_DEVICES to "1,2"
714
+ env = os.environ.copy()
715
+ VISIBLE_DEVICES = "ZE_AFFINITY_MASK" if torch_device == "xpu" else "CUDA_VISIBLE_DEVICES"
716
+ env[VISIBLE_DEVICES] = "1,2" # Restrict to accelerator 1 and 2
717
+
718
+ # Start the server process
719
+ cls.server_process = subprocess.Popen(
720
+ ["trl", "vllm-serve", "--model", cls.model_id, "--data_parallel_size", "2"],
721
+ stdout=subprocess.PIPE,
722
+ stderr=subprocess.PIPE,
723
+ env=env,
724
+ )
725
+
726
+ # Initialize the client
727
+ cls.client = VLLMClient(connection_timeout=240, host="localhost")
728
+ cls.client.init_communicator()
729
+
730
+ def test_generate(self):
731
+ prompts = ["Hello, AI!", "Tell me a joke"]
732
+ outputs = self.client.generate(prompts)
733
+ prompt_ids = outputs["prompt_ids"]
734
+ completion_ids = outputs["completion_ids"]
735
+
736
+ # Check that the outputs are lists
737
+ assert isinstance(prompt_ids, list)
738
+ assert isinstance(completion_ids, list)
739
+
740
+ # Check that the number of sequences are equal to the number of prompts
741
+ assert len(prompt_ids) == len(prompts)
742
+ assert len(completion_ids) == len(prompts)
743
+
744
+ # Check that the sequences are lists of integers
745
+ for seq in prompt_ids:
746
+ assert all(isinstance(tok, int) for tok in seq)
747
+ for seq in completion_ids:
748
+ assert all(isinstance(tok, int) for tok in seq)
749
+
750
+ def test_generate_with_logprobs_none(self):
751
+ outputs = self.client.generate(["Hello, AI!"], logprobs=None)
752
+
753
+ assert isinstance(outputs["prompt_ids"], list)
754
+ assert isinstance(outputs["completion_ids"], list)
755
+ assert outputs["logprobs"] is None
756
+ assert outputs["logprob_token_ids"] is None
757
+
758
+ def test_chat(self):
759
+ messages = [[{"role": "user", "content": "Hello, AI!"}], [{"role": "user", "content": "Tell me a joke"}]]
760
+ outputs = self.client.chat(messages)
761
+ prompt_ids = outputs["prompt_ids"]
762
+ completion_ids = outputs["completion_ids"]
763
+
764
+ # Check that the outputs are lists
765
+ assert isinstance(prompt_ids, list)
766
+ assert isinstance(completion_ids, list)
767
+
768
+ # Check that the number of sequences are equal to the number of messages
769
+ assert len(prompt_ids) == len(messages)
770
+ assert len(completion_ids) == len(messages)
771
+
772
+ # Check that the sequences are lists of integers
773
+ for seq in prompt_ids:
774
+ assert all(isinstance(tok, int) for tok in seq)
775
+ for seq in completion_ids:
776
+ assert all(isinstance(tok, int) for tok in seq)
777
+
778
+ def test_chat_with_logprobs_none(self):
779
+ outputs = self.client.chat([[{"role": "user", "content": "Hello, AI!"}]], logprobs=None)
780
+
781
+ assert isinstance(outputs["prompt_ids"], list)
782
+ assert isinstance(outputs["completion_ids"], list)
783
+ assert outputs["logprobs"] is None
784
+ assert outputs["logprob_token_ids"] is None
785
+
786
+ def test_chat_with_tools(self):
787
+ def multiply(a: int, b: int) -> int:
788
+ """
789
+ Multiplies two integers.
790
+
791
+ Args:
792
+ a: The first integer.
793
+ b: The second integer.
794
+
795
+ Returns:
796
+ The product of the two integers.
797
+ """
798
+ return a * b
799
+
800
+ messages = [[{"role": "user", "content": "What is 3 multiplied by 4?"}]]
801
+ outputs = self.client.chat(messages, tools=[multiply])
802
+
803
+ # Decode prompt and check that "Multiplies two integers." is in the prompt.
804
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id)
805
+ decoded_prompt = tokenizer.decode(outputs["prompt_ids"][0])
806
+ assert "Multiplies two integers." in decoded_prompt
807
+
808
+ def test_generate_with_token_ids(self):
809
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id)
810
+ prompts = ["Hello, AI!", "Tell me a joke"]
811
+ prompt_token_ids = tokenizer(prompts)["input_ids"]
812
+ outputs = self.client.generate(prompt_token_ids)
813
+ prompt_ids = outputs["prompt_ids"]
814
+ completion_ids = outputs["completion_ids"]
815
+
816
+ # Check that the outputs are lists
817
+ assert isinstance(prompt_ids, list)
818
+ assert isinstance(completion_ids, list)
819
+
820
+ # Check that the number of sequences are equal to the number of prompts
821
+ assert len(prompt_ids) == len(prompts)
822
+ assert len(completion_ids) == len(prompts)
823
+
824
+ # Check that prompt_ids match the input token IDs
825
+ assert prompt_ids == prompt_token_ids
826
+
827
+ # Check that the sequences are lists of integers
828
+ for seq in prompt_ids:
829
+ assert all(isinstance(tok, int) for tok in seq)
830
+ for seq in completion_ids:
831
+ assert all(isinstance(tok, int) for tok in seq)
832
+
833
+ def test_generate_with_params(self):
834
+ prompts = ["Hello, AI!", "Tell me a joke"]
835
+ completion_ids = self.client.generate(prompts, n=2, repetition_penalty=0.9, temperature=0.8, max_tokens=32)[
836
+ "completion_ids"
837
+ ]
838
+
839
+ # Check that the output is a list
840
+ assert isinstance(completion_ids, list)
841
+
842
+ # Check that the number of generated sequences is 2 times the number of prompts
843
+ assert len(completion_ids) == 2 * len(prompts)
844
+
845
+ # Check that the generated sequences are lists of integers
846
+ for seq in completion_ids:
847
+ assert all(isinstance(tok, int) for tok in seq)
848
+
849
+ # Check that the length of the generated sequences is less than or equal to 32
850
+ for seq in completion_ids:
851
+ assert len(seq) <= 32
852
+
853
+ def test_update_model_params(self):
854
+ model = AutoModelForCausalLM.from_pretrained(self.model_id, device_map=torch_device)
855
+ self.client.update_model_params(model)
856
+
857
+ def test_reset_prefix_cache(self):
858
+ # Test resetting the prefix cache
859
+ self.client.reset_prefix_cache()
860
+
861
+ @classmethod
862
+ def teardown_class(cls):
863
+ # Close the client
864
+ cls.client.close_communicator()
865
+
866
+ # vLLM x pytest (or Popen) seems not to handle process termination well. To avoid zombie processes, we need to
867
+ # kill the server process and its children explicitly.
868
+ kill_process(cls.server_process)
869
+
870
+
871
+ @pytest.mark.slow
872
+ @require_torch_multi_accelerator
873
+ @require_vllm
874
+ class TestVLLMClientServerDeviceParameter(TrlTestCase):
875
+ """Test the device parameter functionality in init_communicator."""
876
+
877
+ model_id = "Qwen/Qwen2.5-1.5B"
878
+
879
+ @classmethod
880
+ def setup_class(cls):
881
+ # We want the server to run on accelerator 1, so we set VISIBLE_DEVICES to "1"
882
+ env = os.environ.copy()
883
+ VISIBLE_DEVICES = "ZE_AFFINITY_MASK" if torch_device == "xpu" else "CUDA_VISIBLE_DEVICES"
884
+ env[VISIBLE_DEVICES] = "1" # Restrict to accelerator 1
885
+
886
+ # Start the server process
887
+ cls.server_process = subprocess.Popen(
888
+ ["trl", "vllm-serve", "--model", cls.model_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env
889
+ )
890
+
891
+ def test_init_communicator_with_device_int(self):
892
+ """Test init_communicator with integer device parameter."""
893
+ client = VLLMClient(connection_timeout=240, host="localhost")
894
+ client.init_communicator(device=0) # Explicitly specify device 0
895
+
896
+ # Test basic functionality
897
+ prompts = ["Hello, AI!"]
898
+ outputs = client.generate(prompts)
899
+ prompt_ids = outputs["prompt_ids"]
900
+ completion_ids = outputs["completion_ids"]
901
+ assert isinstance(prompt_ids, list)
902
+ assert len(prompt_ids) == len(prompts)
903
+ assert isinstance(completion_ids, list)
904
+ assert len(completion_ids) == len(prompts)
905
+
906
+ client.close_communicator()
907
+
908
+ def test_init_communicator_with_device_string(self):
909
+ """Test init_communicator with string device parameter."""
910
+ client = VLLMClient(connection_timeout=240, host="localhost")
911
+ client.init_communicator(device=0) # Explicitly specify device as string
912
+
913
+ # Test basic functionality
914
+ prompts = ["Hello, AI!"]
915
+ outputs = client.generate(prompts)["completion_ids"]
916
+ assert isinstance(outputs, list)
917
+ assert len(outputs) == len(prompts)
918
+
919
+ client.close_communicator()
920
+
921
+ def test_init_communicator_with_torch_device(self):
922
+ """Test init_communicator with torch.device object."""
923
+ import torch
924
+
925
+ client = VLLMClient(connection_timeout=240, host="localhost")
926
+ device = torch.device(0)
927
+ client.init_communicator(device=device) # Explicitly specify torch.device object
928
+
929
+ # Test basic functionality
930
+ prompts = ["Hello, AI!"]
931
+ outputs = client.generate(prompts)["completion_ids"]
932
+ assert isinstance(outputs, list)
933
+ assert len(outputs) == len(prompts)
934
+
935
+ client.close_communicator()
936
+
937
+ @classmethod
938
+ def teardown_class(cls):
939
+ # vLLM x pytest (or Popen) seems not to handle process termination well. To avoid zombie processes, we need to
940
+ # kill the server process and its children explicitly.
941
+ kill_process(cls.server_process)
942
+
943
+
944
+ @pytest.mark.slow
945
+ @require_vllm
946
+ @require_vision
947
+ class TestVLLMClientServerVLM(TrlTestCase):
948
+ model_id = "Qwen/Qwen2.5-VL-3B-Instruct"
949
+
950
+ @classmethod
951
+ def setup_class(cls):
952
+ # Start the server process
953
+ cls.server_process = subprocess.Popen(
954
+ ["trl", "vllm-serve", "--model", cls.model_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE
955
+ )
956
+
957
+ # Initialize the client (no communicator needed for generation-only tests)
958
+ cls.client = VLLMClient(connection_timeout=240, host="localhost")
959
+
960
+ def test_generate_with_token_ids_and_image(self):
961
+ from PIL import Image
962
+
963
+ processor = AutoProcessor.from_pretrained(self.model_id)
964
+ image1 = Image.new("RGB", (64, 64), color="red")
965
+ image2 = Image.new("RGB", (64, 64), color="blue")
966
+ image3 = Image.new("RGB", (64, 64), color="green")
967
+ messages = [
968
+ [
969
+ {
970
+ "role": "user",
971
+ "content": [
972
+ {"type": "image", "image": image1},
973
+ {"type": "image", "image": image2},
974
+ {"type": "text", "text": "What are the differences between these two images?"},
975
+ ],
976
+ }
977
+ ],
978
+ [
979
+ {
980
+ "role": "user",
981
+ "content": [
982
+ {"type": "image", "image": image3},
983
+ {"type": "text", "text": "What is the color of this image?"},
984
+ ],
985
+ }
986
+ ],
987
+ ]
988
+ prompt_token_ids = processor.apply_chat_template(
989
+ conversation=messages, tokenize=True, add_generation_prompt=True
990
+ )
991
+ outputs = self.client.generate(prompt_token_ids, images=[[image1, image2], [image3]], max_tokens=64)
992
+ prompt_ids = outputs["prompt_ids"]
993
+ completion_ids = outputs["completion_ids"]
994
+
995
+ assert len(prompt_ids) == 2
996
+ assert len(completion_ids) == 2
997
+ assert all(isinstance(tok, int) for tok in prompt_ids[0])
998
+ assert all(isinstance(tok, int) for tok in completion_ids[0])
999
+
1000
+ def test_generate_with_token_ids_mixed_images(self):
1001
+ """Test a batch where one prompt has an image and the other does not."""
1002
+ from PIL import Image
1003
+
1004
+ processor = AutoProcessor.from_pretrained(self.model_id)
1005
+ image = Image.new("RGB", (64, 64), color="red")
1006
+ messages = [
1007
+ [
1008
+ {
1009
+ "role": "user",
1010
+ "content": [{"type": "image", "image": image}, {"type": "text", "text": "Describe this image."}],
1011
+ }
1012
+ ],
1013
+ [
1014
+ {
1015
+ "role": "user",
1016
+ "content": [{"type": "text", "text": "What is 1+1?"}],
1017
+ }
1018
+ ],
1019
+ ]
1020
+ prompt_token_ids = processor.apply_chat_template(
1021
+ conversation=messages, tokenize=True, add_generation_prompt=True
1022
+ )
1023
+ outputs = self.client.generate(prompt_token_ids, images=[[image], None], max_tokens=64)
1024
+ prompt_ids = outputs["prompt_ids"]
1025
+ completion_ids = outputs["completion_ids"]
1026
+
1027
+ assert len(prompt_ids) == 2
1028
+ assert len(completion_ids) == 2
1029
+ assert all(isinstance(tok, int) for tok in prompt_ids[0])
1030
+ assert all(isinstance(tok, int) for tok in prompt_ids[1])
1031
+ assert all(isinstance(tok, int) for tok in completion_ids[0])
1032
+ assert all(isinstance(tok, int) for tok in completion_ids[1])
1033
+
1034
+ @classmethod
1035
+ def teardown_class(cls):
1036
+ kill_process(cls.server_process)
tasks/tasksmith-5b4f21a2a450/tests/source/tests/testing_constants.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
+ CI_HUB_USER = "__DUMMY_TRANSFORMERS_USER__"
16
+ CI_HUB_USER_FULL_NAME = "Dummy User"
17
+
18
+ CI_HUB_ENDPOINT = "https://hub-ci.huggingface.co"
tasks/tasksmith-5b4f21a2a450/tests/source/tests/testing_utils.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 functools
16
+ import signal
17
+ import warnings
18
+ from collections.abc import Callable
19
+
20
+ import psutil
21
+ import pytest
22
+ import torch
23
+ from transformers import is_bitsandbytes_available, is_comet_available, is_sklearn_available, is_wandb_available
24
+ from transformers.testing_utils import backend_device_count, torch_device
25
+ from transformers.utils import (
26
+ is_kernels_available,
27
+ is_peft_available,
28
+ is_rich_available,
29
+ is_torch_available,
30
+ is_vision_available,
31
+ )
32
+
33
+ from trl.import_utils import (
34
+ is_jmespath_available,
35
+ is_joblib_available,
36
+ is_liger_kernel_available,
37
+ is_math_verify_available,
38
+ is_mergekit_available,
39
+ is_openreward_available,
40
+ is_vllm_available,
41
+ )
42
+
43
+
44
+ require_bitsandbytes = pytest.mark.skipif(not is_bitsandbytes_available(), reason="test requires bitsandbytes")
45
+ require_comet = pytest.mark.skipif(not is_comet_available(), reason="test requires comet_ml")
46
+ require_jmespath = pytest.mark.skipif(not is_jmespath_available(), reason="test requires jmespath")
47
+ require_kernels = pytest.mark.skipif(not is_kernels_available(), reason="test requires kernels")
48
+ require_liger_kernel = pytest.mark.skipif(not is_liger_kernel_available(), reason="test requires liger-kernel")
49
+ require_math_latex = pytest.mark.skipif(not is_math_verify_available(), reason="test requires math_verify")
50
+ require_mergekit = pytest.mark.skipif(not is_mergekit_available(), reason="test requires mergekit")
51
+ require_openreward = pytest.mark.skipif(not is_openreward_available(), reason="test requires openreward")
52
+ require_peft = pytest.mark.skipif(not is_peft_available(), reason="test requires peft")
53
+ require_rich = pytest.mark.skipif(not is_rich_available(), reason="test requires rich")
54
+ require_sklearn = pytest.mark.skipif(
55
+ not (is_sklearn_available() and is_joblib_available()), reason="test requires sklearn"
56
+ )
57
+ require_torch_accelerator = pytest.mark.skipif(
58
+ torch_device is None or torch_device == "cpu", reason="test requires accelerator"
59
+ )
60
+ require_torch_multi_accelerator = pytest.mark.skipif(
61
+ not is_torch_available() or backend_device_count(torch_device) <= 1, reason="test requires multiple accelerators"
62
+ )
63
+ require_vision = pytest.mark.skipif(not is_vision_available(), reason="test requires vision")
64
+ require_vllm = pytest.mark.skipif(not is_vllm_available(), reason="test requires vllm")
65
+ require_wandb = pytest.mark.skipif(not is_wandb_available(), reason="test requires wandb")
66
+ require_no_wandb = pytest.mark.skipif(is_wandb_available(), reason="test requires no wandb")
67
+ require_3_accelerators = pytest.mark.skipif(
68
+ not (getattr(torch, torch_device, torch.cuda).device_count() >= 3),
69
+ reason=f"test requires at least 3 {torch_device}s",
70
+ )
71
+
72
+
73
+ def is_bitsandbytes_multi_backend_available() -> bool:
74
+ if is_bitsandbytes_available():
75
+ import bitsandbytes as bnb
76
+
77
+ return "multi_backend" in getattr(bnb, "features", set())
78
+ return False
79
+
80
+
81
+ # Function ported from transformers.testing_utils before transformers#41283
82
+ require_torch_gpu_if_bnb_not_multi_backend_enabled = pytest.mark.skipif(
83
+ not is_bitsandbytes_multi_backend_available() and not torch_device == "cuda",
84
+ reason="test requires bitsandbytes multi-backend enabled or 'cuda' torch device",
85
+ )
86
+
87
+
88
+ def is_ampere_or_newer(device_index=0):
89
+ if not torch.cuda.is_available():
90
+ return False
91
+
92
+ # "Ampere" is an NVIDIA architecture; an AMD (ROCm) GPU is never Ampere. On ROCm,
93
+ # torch.cuda.get_device_capability returns the gfx version, which would spuriously compare >= (8, 0).
94
+ if torch.version.hip is not None:
95
+ return False
96
+
97
+ major, minor = torch.cuda.get_device_capability(device_index)
98
+ # Ampere starts at compute capability 8.0 (e.g., A100 = 8.0, RTX 30xx = 8.6)
99
+ return (major, minor) >= (8, 0)
100
+
101
+
102
+ class TrlTestCase:
103
+ @pytest.fixture(autouse=True)
104
+ def set_tmp_dir(self, tmp_path):
105
+ self.tmp_dir = str(tmp_path)
106
+
107
+
108
+ def ignore_warnings(message: str = None, category: type[Warning] = Warning) -> Callable:
109
+ """
110
+ Decorator to ignore warnings with a specific message and/or category.
111
+
112
+ Args:
113
+ message (`str`, *optional*):
114
+ Regex pattern for the warning message to ignore. If `None`, all messages are ignored.
115
+ category (`type[Warning]`, *optional*, defaults to `Warning`):
116
+ Warning class to ignore. Defaults to `Warning`, which ignores all warnings.
117
+ """
118
+
119
+ def decorator(test_func):
120
+ @functools.wraps(test_func)
121
+ def wrapper(*args, **kwargs):
122
+ with warnings.catch_warnings():
123
+ warnings.filterwarnings("ignore", message=message, category=category)
124
+ return test_func(*args, **kwargs)
125
+
126
+ return wrapper
127
+
128
+ return decorator
129
+
130
+
131
+ def kill_process(process):
132
+ parent = psutil.Process(process.pid)
133
+ children = parent.children(recursive=True)
134
+ for child in children:
135
+ try:
136
+ child.send_signal(signal.SIGTERM)
137
+ child.wait(timeout=5)
138
+ except psutil.TimeoutExpired:
139
+ child.kill()
140
+ except psutil.NoSuchProcess:
141
+ pass
142
+ try:
143
+ process.terminate()
144
+ process.wait(timeout=5)
145
+ except psutil.TimeoutExpired:
146
+ process.kill()
147
+ except psutil.NoSuchProcess:
148
+ pass
tasks/tasksmith-5b4f21a2a450/tests/source/trl/__init__.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 sys
16
+ from importlib.metadata import PackageNotFoundError, version
17
+ from typing import TYPE_CHECKING
18
+
19
+ from . import _compat
20
+ from ._lazy_module import _LazyModule
21
+
22
+
23
+ try:
24
+ __version__ = version("trl")
25
+ except PackageNotFoundError:
26
+ __version__ = "unknown"
27
+
28
+ _import_structure = {
29
+ "chat_template_utils": [
30
+ "add_response_schema",
31
+ "clone_chat_template",
32
+ "get_training_chat_template",
33
+ "supports_tool_calling",
34
+ ],
35
+ "data_utils": [
36
+ "apply_chat_template",
37
+ "extract_prompt",
38
+ "is_conversational",
39
+ "is_conversational_from_value",
40
+ "maybe_apply_chat_template",
41
+ "maybe_convert_to_chatml",
42
+ "maybe_extract_prompt",
43
+ "maybe_unpair_preference_dataset",
44
+ "pack_dataset",
45
+ "prepare_multimodal_messages",
46
+ "prepare_multimodal_messages_vllm",
47
+ "unpair_preference_dataset",
48
+ ],
49
+ "models": ["create_reference_model"],
50
+ "scripts": ["DatasetMixtureConfig", "ScriptArguments", "TrlParser", "get_dataset", "init_zero_verbose"],
51
+ "trainer": [
52
+ "BEMACallback",
53
+ "DPOConfig",
54
+ "DPOTrainer",
55
+ "GRPOConfig",
56
+ "GRPOTrainer",
57
+ "KTOConfig",
58
+ "KTOTrainer",
59
+ "LogCompletionsCallback",
60
+ "ModelConfig",
61
+ "RewardConfig",
62
+ "RewardTrainer",
63
+ "RichProgressCallback",
64
+ "RLOOConfig",
65
+ "RLOOTrainer",
66
+ "SFTConfig",
67
+ "SFTTrainer",
68
+ "SyncRefModelCallback",
69
+ "WeaveCallback",
70
+ "get_kbit_device_map",
71
+ "get_peft_config",
72
+ "get_quantization_config",
73
+ ],
74
+ }
75
+
76
+ if TYPE_CHECKING:
77
+ from .chat_template_utils import (
78
+ add_response_schema,
79
+ clone_chat_template,
80
+ get_training_chat_template,
81
+ supports_tool_calling,
82
+ )
83
+ from .data_utils import (
84
+ apply_chat_template,
85
+ extract_prompt,
86
+ is_conversational,
87
+ is_conversational_from_value,
88
+ maybe_apply_chat_template,
89
+ maybe_convert_to_chatml,
90
+ maybe_extract_prompt,
91
+ maybe_unpair_preference_dataset,
92
+ pack_dataset,
93
+ prepare_multimodal_messages,
94
+ prepare_multimodal_messages_vllm,
95
+ unpair_preference_dataset,
96
+ )
97
+ from .models import create_reference_model
98
+ from .scripts import DatasetMixtureConfig, ScriptArguments, TrlParser, get_dataset, init_zero_verbose
99
+ from .trainer import (
100
+ BEMACallback,
101
+ DPOConfig,
102
+ DPOTrainer,
103
+ GRPOConfig,
104
+ GRPOTrainer,
105
+ KTOConfig,
106
+ KTOTrainer,
107
+ LogCompletionsCallback,
108
+ ModelConfig,
109
+ RewardConfig,
110
+ RewardTrainer,
111
+ RichProgressCallback,
112
+ RLOOConfig,
113
+ RLOOTrainer,
114
+ SFTConfig,
115
+ SFTTrainer,
116
+ SyncRefModelCallback,
117
+ WeaveCallback,
118
+ get_kbit_device_map,
119
+ get_peft_config,
120
+ get_quantization_config,
121
+ )
122
+
123
+ else:
124
+ import sys
125
+
126
+ sys.modules[__name__] = _LazyModule(
127
+ __name__,
128
+ globals()["__file__"],
129
+ _import_structure,
130
+ module_spec=__spec__,
131
+ extra_objects={"__version__": __version__},
132
+ )
tasks/tasksmith-5b4f21a2a450/tests/source/trl/_compat.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Compatibility shims for third-party dependencies.
17
+
18
+ This module contains temporary patches to handle version incompatibilities between TRL's dependencies.
19
+
20
+ Each patch should be removed when minimum version requirements eliminate the need.
21
+ """
22
+
23
+ import warnings
24
+
25
+ from packaging.version import Version
26
+
27
+ from .import_utils import _is_package_available
28
+
29
+
30
+ def _is_package_version_below(package_name: str, version_threshold: str) -> bool:
31
+ """
32
+ Check if installed package version is below the given threshold.
33
+
34
+ Args:
35
+ package_name (str): Package name.
36
+ version_threshold (str): Maximum version threshold.
37
+
38
+ Returns:
39
+ - True if package is installed and version < version_threshold.
40
+ - False if package is not installed or version >= version_threshold.
41
+ """
42
+ try:
43
+ is_available, version = _is_package_available(package_name, return_version=True)
44
+ return is_available and Version(version) < Version(version_threshold)
45
+ except Exception as e:
46
+ warnings.warn(
47
+ f"Failed to check {package_name} version against {version_threshold}: {e}. "
48
+ f"Compatibility patch may not be applied.",
49
+ stacklevel=2,
50
+ )
51
+ return False
52
+
53
+
54
+ def _is_package_version_at_least(package_name: str, version_threshold: str) -> bool:
55
+ """
56
+ Check if installed package version is at least the given threshold.
57
+
58
+ Args:
59
+ package_name (str): Package name.
60
+ version_threshold (str): Minimum version threshold.
61
+
62
+ Returns:
63
+ - True if package is installed and version >= version_threshold.
64
+ - False if package is not installed or version < version_threshold.
65
+ """
66
+ try:
67
+ is_available, version = _is_package_available(package_name, return_version=True)
68
+ return is_available and Version(version) >= Version(version_threshold)
69
+ except Exception as e:
70
+ warnings.warn(
71
+ f"Failed to check {package_name} version against {version_threshold}: {e}. "
72
+ f"Compatibility patch may not be applied.",
73
+ stacklevel=2,
74
+ )
75
+ return False
76
+
77
+
78
+ def _patch_vllm_logging() -> None:
79
+ """Set vLLM logging level to ERROR by default to reduce noise."""
80
+ if _is_package_available("vllm"):
81
+ import os
82
+
83
+ os.environ["VLLM_LOGGING_LEVEL"] = os.getenv("VLLM_LOGGING_LEVEL", "ERROR")
84
+
85
+
86
+ def _patch_transformers_hybrid_cache() -> None:
87
+ """
88
+ Fix HybridCache import for transformers v5 compatibility.
89
+
90
+ - Issue: peft import HybridCache from transformers.cache_utils
91
+ - HybridCache removed in https://github.com/huggingface/transformers/pull/43168 (transformers>=5.0.0)
92
+ - Fixed in peft: https://github.com/huggingface/peft/pull/2735 (released in v0.18.0)
93
+ - This can be removed when TRL requires peft>=0.18.0
94
+ """
95
+ if _is_package_version_at_least("transformers", "5.0.0") and _is_package_version_below("peft", "0.18.0"):
96
+ try:
97
+ import transformers.cache_utils
98
+ from transformers.utils.import_utils import _LazyModule
99
+
100
+ Cache = transformers.cache_utils.Cache
101
+
102
+ # Patch for liger_kernel: Add HybridCache as an alias for Cache in the cache_utils module
103
+ transformers.cache_utils.HybridCache = Cache
104
+
105
+ # Patch for peft: Patch _LazyModule.__init__ to add HybridCache to transformers' lazy loading structures
106
+ _original_lazy_module_init = _LazyModule.__init__
107
+
108
+ def _patched_lazy_module_init(self, name, *args, **kwargs):
109
+ _original_lazy_module_init(self, name, *args, **kwargs)
110
+ if name == "transformers":
111
+ # Update _LazyModule's internal structures
112
+ if hasattr(self, "_import_structure") and "cache_utils" in self._import_structure:
113
+ if "HybridCache" not in self._import_structure["cache_utils"]:
114
+ self._import_structure["cache_utils"].append("HybridCache")
115
+
116
+ if hasattr(self, "_class_to_module"):
117
+ self._class_to_module["HybridCache"] = "cache_utils"
118
+
119
+ if hasattr(self, "__all__") and "HybridCache" not in self.__all__:
120
+ self.__all__.append("HybridCache")
121
+
122
+ self.HybridCache = Cache
123
+
124
+ _LazyModule.__init__ = _patched_lazy_module_init
125
+
126
+ except Exception as e:
127
+ warnings.warn(f"Failed to patch transformers HybridCache compatibility: {e}", stacklevel=2)
128
+
129
+
130
+ def _patch_transformers_parallelism_config() -> None:
131
+ """
132
+ Fix ParallelismConfig for transformers compatibility.
133
+
134
+ Ensure that ``transformers.training_args`` always defines the symbol `ParallelismConfig` so that Python's
135
+ `typing.get_type_hints` can resolve annotations on `transformers.TrainingArguments` without raising a `NameError`.
136
+
137
+ This is needed when running with ``accelerate<1.10.1``, where the module ``accelerate.parallelism_config`` did not
138
+ exist and therefore the type alias is not imported by Transformers.
139
+
140
+ See upstream fix PR in transformers#40818.
141
+
142
+ - Issue: transformers imports ParallelismConfig only if accelerate>=1.10.1 and raises NameError if
143
+ accelerate<1.10.1
144
+ - Fixed in transformers: https://github.com/huggingface/transformers/pull/40818 (released in v4.57.0)
145
+ - This can be removed when TRL requires transformers>=4.57.0 or accelerate>=1.10.1
146
+ """
147
+ if _is_package_version_below("transformers", "4.57.0") and _is_package_version_below("accelerate", "1.10.1"):
148
+ try:
149
+ from typing import Any
150
+
151
+ import transformers.training_args
152
+
153
+ if not hasattr(transformers.training_args, "ParallelismConfig"):
154
+ transformers.training_args.ParallelismConfig = Any
155
+ except Exception as e:
156
+ warnings.warn(f"Failed to patch transformers ParallelismConfig compatibility: {e}", stacklevel=2)
157
+
158
+
159
+ # Apply vLLM patches
160
+ _patch_vllm_logging()
161
+
162
+ # Apply transformers patches
163
+ _patch_transformers_hybrid_cache()
164
+ _patch_transformers_parallelism_config() # before creating HfArgumentParser
tasks/tasksmith-5b4f21a2a450/tests/source/trl/_lazy_module.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 importlib
16
+ import os
17
+ from itertools import chain
18
+ from types import ModuleType
19
+ from typing import Any
20
+
21
+
22
+ class _LazyModule(ModuleType):
23
+ """
24
+ Module class that surfaces all objects but only performs associated imports when the objects are requested.
25
+ """
26
+
27
+ # Very heavily inspired by optuna.integration._IntegrationModule
28
+ # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py
29
+ def __init__(self, name, module_file, import_structure, module_spec=None, extra_objects=None):
30
+ super().__init__(name)
31
+ self._modules = set(import_structure.keys())
32
+ self._class_to_module = {}
33
+ for key, values in import_structure.items():
34
+ for value in values:
35
+ self._class_to_module[value] = key
36
+ # Needed for autocompletion in an IDE
37
+ self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values()))
38
+ self.__file__ = module_file
39
+ self.__spec__ = module_spec
40
+ self.__path__ = [os.path.dirname(module_file)]
41
+ self._objects = {} if extra_objects is None else extra_objects
42
+ self._name = name
43
+ self._import_structure = import_structure
44
+
45
+ # Needed for autocompletion in an IDE
46
+ def __dir__(self):
47
+ result = super().__dir__()
48
+ # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether
49
+ # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir.
50
+ for attr in self.__all__:
51
+ if attr not in result:
52
+ result.append(attr)
53
+ return result
54
+
55
+ def __getattr__(self, name: str) -> Any:
56
+ if name in self._objects:
57
+ return self._objects[name]
58
+ if name in self._modules:
59
+ value = self._get_module(name)
60
+ elif name in self._class_to_module.keys():
61
+ module = self._get_module(self._class_to_module[name])
62
+ value = getattr(module, name)
63
+ else:
64
+ raise AttributeError(f"module {self.__name__} has no attribute {name}")
65
+
66
+ setattr(self, name, value)
67
+ return value
68
+
69
+ def _get_module(self, module_name: str):
70
+ try:
71
+ return importlib.import_module("." + module_name, self.__name__)
72
+ except Exception as e:
73
+ raise RuntimeError(
74
+ f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
75
+ f" traceback):\n{e}"
76
+ ) from e
77
+
78
+ def __reduce__(self):
79
+ return (self.__class__, (self._name, self.__file__, self._import_structure))
tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/fsdp1.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ distributed_type: FSDP
4
+ downcast_bf16: 'no'
5
+ enable_cpu_affinity: false
6
+ fsdp_config:
7
+ fsdp_activation_checkpointing: false
8
+ fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
9
+ fsdp_backward_prefetch: BACKWARD_PRE
10
+ fsdp_cpu_ram_efficient_loading: true
11
+ fsdp_forward_prefetch: true
12
+ fsdp_offload_params: false
13
+ fsdp_reshard_after_forward: FULL_SHARD
14
+ fsdp_state_dict_type: FULL_STATE_DICT
15
+ fsdp_sync_module_states: true
16
+ fsdp_use_orig_params: true
17
+ fsdp_version: 1
18
+ machine_rank: 0
19
+ main_training_function: main
20
+ mixed_precision: bf16
21
+ num_machines: 1
22
+ num_processes: 8
23
+ rdzv_backend: static
24
+ same_network: true
25
+ tpu_env: []
26
+ tpu_use_cluster: false
27
+ tpu_use_sudo: false
28
+ use_cpu: false
tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/fsdp2.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Requires accelerate 1.7.0 or higher
2
+ compute_environment: LOCAL_MACHINE
3
+ debug: false
4
+ distributed_type: FSDP
5
+ downcast_bf16: 'no'
6
+ enable_cpu_affinity: false
7
+ fsdp_config:
8
+ fsdp_activation_checkpointing: false
9
+ fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
10
+ fsdp_cpu_ram_efficient_loading: true
11
+ fsdp_offload_params: false
12
+ fsdp_reshard_after_forward: true
13
+ fsdp_state_dict_type: FULL_STATE_DICT
14
+ fsdp_version: 2
15
+ machine_rank: 0
16
+ main_training_function: main
17
+ mixed_precision: bf16
18
+ num_machines: 1
19
+ num_processes: 8
20
+ rdzv_backend: static
21
+ same_network: true
22
+ tpu_env: []
23
+ tpu_use_cluster: false
24
+ tpu_use_sudo: false
25
+ use_cpu: false
tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/multi_gpu.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ distributed_type: MULTI_GPU
4
+ downcast_bf16: 'no'
5
+ gpu_ids: all
6
+ machine_rank: 0
7
+ main_training_function: main
8
+ mixed_precision: 'bf16'
9
+ num_machines: 1
10
+ num_processes: 8
11
+ rdzv_backend: static
12
+ same_network: true
13
+ tpu_env: []
14
+ tpu_use_cluster: false
15
+ tpu_use_sudo: false
16
+ use_cpu: false
tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/single_gpu.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ distributed_type: "NO"
4
+ downcast_bf16: 'no'
5
+ gpu_ids: all
6
+ machine_rank: 0
7
+ main_training_function: main
8
+ mixed_precision: 'bf16'
9
+ num_machines: 1
10
+ num_processes: 8
11
+ rdzv_backend: static
12
+ same_network: true
13
+ tpu_env: []
14
+ tpu_use_cluster: false
15
+ tpu_use_sudo: false
16
+ use_cpu: false
tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero1.yaml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ deepspeed_config:
4
+ deepspeed_multinode_launcher: standard
5
+ gradient_accumulation_steps: 1
6
+ zero3_init_flag: false
7
+ zero_stage: 1
8
+ distributed_type: DEEPSPEED
9
+ downcast_bf16: 'no'
10
+ machine_rank: 0
11
+ main_training_function: main
12
+ mixed_precision: 'bf16'
13
+ num_machines: 1
14
+ num_processes: 8
15
+ rdzv_backend: static
16
+ same_network: true
17
+ tpu_env: []
18
+ tpu_use_cluster: false
19
+ tpu_use_sudo: false
20
+ use_cpu: false
tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero2.yaml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ deepspeed_config:
4
+ deepspeed_multinode_launcher: standard
5
+ offload_optimizer_device: none
6
+ offload_param_device: none
7
+ zero3_init_flag: false
8
+ zero_stage: 2
9
+ distributed_type: DEEPSPEED
10
+ downcast_bf16: 'no'
11
+ machine_rank: 0
12
+ main_training_function: main
13
+ mixed_precision: 'bf16'
14
+ num_machines: 1
15
+ num_processes: 8
16
+ rdzv_backend: static
17
+ same_network: true
18
+ tpu_env: []
19
+ tpu_use_cluster: false
20
+ tpu_use_sudo: false
21
+ use_cpu: false
tasks/tasksmith-5b4f21a2a450/tests/source/trl/accelerate_configs/zero3.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ deepspeed_config:
4
+ deepspeed_multinode_launcher: standard
5
+ offload_optimizer_device: none
6
+ offload_param_device: none
7
+ zero3_init_flag: true
8
+ zero3_save_16bit_model: true
9
+ zero_stage: 3
10
+ distributed_type: DEEPSPEED
11
+ downcast_bf16: 'no'
12
+ machine_rank: 0
13
+ main_training_function: main
14
+ mixed_precision: bf16
15
+ num_machines: 1
16
+ num_processes: 8
17
+ rdzv_backend: static
18
+ same_network: true
19
+ tpu_env: []
20
+ tpu_use_cluster: false
21
+ tpu_use_sudo: false
22
+ use_cpu: false
tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_template_utils.py ADDED
@@ -0,0 +1,939 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 re
16
+ import warnings
17
+ from pathlib import Path
18
+ from typing import TypeVar
19
+
20
+ from jinja2 import TemplateError
21
+ from transformers import AddedToken, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin
22
+
23
+ from .data_utils import prepare_multimodal_messages
24
+
25
+
26
+ _CHAT_TEMPLATES_DIR = Path(__file__).parent / "chat_templates"
27
+
28
+
29
+ def has_generation_markers(chat_template: str) -> bool:
30
+ """
31
+ Check whether the chat template defines `{% generation %}` markers, accounting for whitespace-trim variants such as
32
+ `{%- generation %}` and `{%- generation -%}`.
33
+ """
34
+ return re.search(r"\{%-?\s*generation\s*-?%\}", chat_template) is not None
35
+
36
+
37
+ def clone_chat_template(
38
+ model: PreTrainedModel,
39
+ tokenizer: PreTrainedTokenizerBase,
40
+ source_tokenizer_path: str,
41
+ resize_to_multiple_of: int | None = 64,
42
+ ) -> tuple[PreTrainedModel, PreTrainedTokenizerBase, list[int]]:
43
+ """
44
+ Clones a chat template from a source tokenizer to the target tokenizer and updates the model accordingly.
45
+
46
+ This function:
47
+ - Copies the chat template from a source tokenizer to the target tokenizer.
48
+ - Adds any new tokens from the source tokenizer to the target tokenizer.
49
+ - Sets and synchronizes the EOS token across the tokenizer and model.
50
+ - Resizes the model's token embeddings to match the new vocabulary size, optionally rounding it up to a multiple of
51
+ a specified value. In such cases, dummy tokens are added to the tokenizer to ensure the vocabulary size matches
52
+ the embedding dimensions.
53
+
54
+ Args:
55
+ model ([`~transformers.PreTrainedModel`]):
56
+ Model to update.
57
+ tokenizer ([`~transformers.PreTrainedTokenizerBase`]):
58
+ Tokenizer to update.
59
+ source_tokenizer_path (`str`):
60
+ Path or identifier of the pretrained tokenizer to clone from.
61
+ resize_to_multiple_of (`int` or `None`, *optional*, defaults to `64`):
62
+ The embedding layer will be resized to the new vocabulary size. If this is not `None`, it will round up the
63
+ new vocabulary size to the nearest multiple of this value.
64
+
65
+ Returns:
66
+ model ([`~transformers.PreTrainedModel`]):
67
+ Updated model with resized token embeddings and EOS token configured.
68
+ tokenizer ([`~transformers.PreTrainedTokenizerBase`]):
69
+ Updated tokenizer with the chat template and special tokens applied.
70
+ added_tokens (`list[int]`):
71
+ List of tokens that were added to the tokenizer from the source tokenizer.
72
+
73
+ Example:
74
+ ```python
75
+ from transformers import AutoModelForCausalLM, AutoTokenizer
76
+ from trl import clone_chat_template
77
+
78
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
79
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
80
+ model, tokenizer, added_tokens = clone_chat_template(model, tokenizer, "Qwen/Qwen3-0.6B")
81
+ ```
82
+ """
83
+ # Load the source tokenizer containing the desired chat template
84
+ tokenizer_source = AutoTokenizer.from_pretrained(source_tokenizer_path)
85
+
86
+ # Copy the chat template from the source tokenizer
87
+ tokenizer.chat_template = tokenizer_source.get_chat_template()
88
+
89
+ # Ensure all added tokens from the source are available in the target tokenizer
90
+ added_tokens = [
91
+ token for token in tokenizer_source.added_tokens_decoder.values() if token.content not in tokenizer.vocab
92
+ ]
93
+ tokenizer.add_tokens(added_tokens)
94
+
95
+ # Set the EOS token from the source tokenizer (important for generation)
96
+ tokenizer.eos_token = tokenizer_source.eos_token
97
+ model.config.eos_token_id = tokenizer.eos_token_id
98
+ if model.can_generate(): # Non-generative models (e.g. SequenceClassification) may not have a generation_config
99
+ model.generation_config.eos_token_id = tokenizer.eos_token_id
100
+
101
+ # Resize model embeddings to include any new tokens, optionally rounding up to a multiple
102
+ model.resize_token_embeddings(
103
+ # After studying many tokenizers, we found that len(tokenizer.vocab) is the most reliable way to get the vocab
104
+ # size. Avoid using tokenizer.vocab_size or tokenizer.vocab_size + len(tokenizer.added_tokens_encoder),
105
+ # as handling of special and added tokens varies across tokenizers.
106
+ new_num_tokens=len(tokenizer.vocab),
107
+ pad_to_multiple_of=resize_to_multiple_of if resize_to_multiple_of is not None else None,
108
+ )
109
+
110
+ # After resizing, the embedding matrix size may exceed the vocabulary size. Add dummy tokens to the tokenizer to
111
+ # ensure vocabulary size matches the embedding matrix dimensions.
112
+ idx = 0
113
+ while model.vocab_size > len(tokenizer.vocab):
114
+ dummy_token = AddedToken(f"<extra_id_{idx}>")
115
+ is_added = tokenizer.add_tokens(dummy_token)
116
+ idx += 1
117
+ if is_added == 1:
118
+ added_tokens.append(dummy_token)
119
+
120
+ # Verify that vocabulary size now matches embedding dimensions
121
+ if len(tokenizer.vocab) != model.vocab_size:
122
+ raise RuntimeError(
123
+ f"Vocabulary size mismatch after resizing: tokenizer vocab size is {len(tokenizer.vocab)}, but model "
124
+ f"embedding size is {model.vocab_size}. This indicates an internal error in the token alignment process."
125
+ )
126
+ added_tokens = [token.content for token in added_tokens]
127
+ added_tokens = tokenizer.convert_tokens_to_ids(added_tokens)
128
+ return model, tokenizer, added_tokens
129
+
130
+
131
+ glm4moe_schema = {
132
+ "x-regex": r"^(?:\n?<think>\n?(?:(?P<reasoning_content>.*?\S.*?)\n?|[\s]*)</think>\s*)?(?P<content>(?:(?!<tool_call>)[\s\S])*?)(?:\n(?=<tool_call>))?(?=(?:<tool_call>|$))(?P<tool_calls>(?:<tool_call>(?:(?!</tool_call>)[\s\S])+</tool_call>\s*)+)?$",
133
+ "type": "object",
134
+ "properties": {
135
+ "role": {"const": "assistant"},
136
+ "content": {"type": "string"},
137
+ "reasoning_content": {"type": "string"},
138
+ "tool_calls": {
139
+ "type": "array",
140
+ "x-regex-iterator": r"<tool_call>\s*(.+?)\s*</tool_call>",
141
+ "items": {
142
+ "type": "object",
143
+ "properties": {
144
+ "type": {"const": "function"},
145
+ "function": {
146
+ "type": "object",
147
+ "properties": {
148
+ "name": {"type": "string", "x-regex": r"^(\S+)"},
149
+ "arguments": {
150
+ "type": "object",
151
+ "x-regex-key-value": r"<arg_key>(?P<key>[^<]+)</arg_key>\s*\n<arg_value>(?P<value>.*?)</arg_value>",
152
+ "default": {},
153
+ "additionalProperties": {
154
+ "x-parser": "json",
155
+ "x-parser-args": {"allow_non_json": True},
156
+ },
157
+ },
158
+ },
159
+ },
160
+ },
161
+ },
162
+ },
163
+ },
164
+ }
165
+
166
+ gptoss_schema = {
167
+ # Normalize final content to analysis format so both map to the same "content" group.
168
+ "x-regex-substitutions": [
169
+ [r"<\|channel\|>final<\|message\|>(.*?)<\|return\|>", r"<|channel|>analysis<|message|>\1<|end|>"],
170
+ ],
171
+ "x-regex": r"^(?:<\|channel\|>analysis<\|message\|>(?P<content>.*?)<\|end\|>(?:<\|start\|>assistant)?)?\s*(?P<tool_calls>to=functions\.\S+<\|channel\|>commentary json<\|message\|>.*?<\|call\|>)?$",
172
+ "type": "object",
173
+ "properties": {
174
+ "role": {"const": "assistant"},
175
+ "content": {"type": "string"},
176
+ "tool_calls": {
177
+ "type": "array",
178
+ "x-regex-iterator": r"(to=functions\.\S+<\|channel\|>commentary json<\|message\|>.*?<\|call\|>)",
179
+ "items": {
180
+ # Convert "to=functions.NAME<|channel|>commentary json<|message|>ARGS<|call|>"
181
+ # into '{"name": "NAME", "arguments": ARGS}' so it can be parsed as JSON.
182
+ "x-regex-substitutions": [
183
+ [
184
+ r"to=functions\.(\S+)<\|channel\|>commentary json<\|message\|>(.*?)<\|call\|>",
185
+ r'{"name": "\1", "arguments": \2}',
186
+ ],
187
+ ],
188
+ "x-parser": "json",
189
+ "x-parser-args": {"transform": "{type: 'function', function: @}"},
190
+ "type": "object",
191
+ "properties": {
192
+ "type": {"const": "function"},
193
+ "function": {
194
+ "type": "object",
195
+ "properties": {
196
+ "name": {"type": "string"},
197
+ "arguments": {
198
+ "type": "object",
199
+ "additionalProperties": {},
200
+ },
201
+ },
202
+ },
203
+ },
204
+ },
205
+ },
206
+ },
207
+ }
208
+
209
+ # Adapted and corrected versions of the schemas from:
210
+ # https://github.com/huggingface/transformers/blob/main/tests/utils/test_chat_parsing_utils.py
211
+ qwen3_schema = {
212
+ "x-regex": r"^(?:<think>\n?(?:(?P<reasoning_content>.*?\S.*?)\n?|[\s]*)</think>\s*)?(?P<content>(?:(?!<tool_call>)[\s\S])*?)(?:\n(?=<tool_call>))?(?=(?:<tool_call>|<\|im_end\|>|$))(?P<tool_calls>(?:<tool_call>(?:(?!</tool_call>)[\s\S])+</tool_call>\s*)+)?\s*(?:<\|im_end\|>|$)",
213
+ "type": "object",
214
+ "properties": {
215
+ "role": {"const": "assistant"},
216
+ "content": {"type": "string"},
217
+ "reasoning_content": {"type": "string"},
218
+ "tool_calls": {
219
+ "type": "array",
220
+ "x-regex-iterator": r"<tool_call>\s*(.+?)\s*</tool_call>",
221
+ "items": {
222
+ "x-parser": "json",
223
+ "x-parser-args": {"transform": "{type: 'function', function: @}"},
224
+ "type": "object",
225
+ "properties": {
226
+ "type": {"const": "function"},
227
+ "function": {
228
+ "type": "object",
229
+ "properties": {
230
+ "name": {"type": "string"},
231
+ "arguments": {
232
+ "type": "object",
233
+ "additionalProperties": {},
234
+ },
235
+ },
236
+ },
237
+ },
238
+ },
239
+ },
240
+ },
241
+ }
242
+
243
+ llama3_schema = {
244
+ # Llama 3.1 / 3.2 render a tool call as a single bare JSON object using the key "parameters" instead of
245
+ # "arguments": `{"name": "<name>", "parameters": <args_json>}<|eot_id|>`. There is no surrounding marker, no
246
+ # support for content alongside a tool call, and at most one tool call per assistant turn (the template raises
247
+ # otherwise). Either we match a tool call (capturing the JSON) or we treat the response as plain content.
248
+ "x-regex": r'^(?:(?P<tool_calls>\{"name":\s*".+?",\s*"parameters":\s*.+\})|(?P<content>.*?))(?:<\|eot_id\|>|$)',
249
+ "type": "object",
250
+ "properties": {
251
+ "role": {"const": "assistant"},
252
+ "content": {"type": "string"},
253
+ "tool_calls": {
254
+ "type": "array",
255
+ "x-regex-iterator": r'(\{"name":\s*".+?",\s*"parameters":\s*.+\})',
256
+ "items": {
257
+ # Rewrite "parameters" → "arguments" so the JSON parses into the standard tool-call shape. Anchored
258
+ # on the leading `{"name": "..."` so a stray `"parameters"` inside argument values is not touched.
259
+ "x-regex-substitutions": [
260
+ [r'^(\{"name":\s*"[^"]+",\s*)"parameters":', r'\1"arguments":'],
261
+ ],
262
+ "x-parser": "json",
263
+ "x-parser-args": {"transform": "{type: 'function', function: @}"},
264
+ "type": "object",
265
+ "properties": {
266
+ "type": {"const": "function"},
267
+ "function": {
268
+ "type": "object",
269
+ "properties": {
270
+ "name": {"type": "string"},
271
+ "arguments": {
272
+ "type": "object",
273
+ "additionalProperties": {},
274
+ },
275
+ },
276
+ },
277
+ },
278
+ },
279
+ },
280
+ },
281
+ }
282
+
283
+ qwen3_5_schema = {
284
+ "x-regex": r"^(?:(?:<think>\n?)?(?:(?P<reasoning_content>.*?\S.*?)\n?|[\s]*)</think>\s*)?(?P<content>(?:(?!<tool_call>)[\s\S])*?)(?:\n+(?=<tool_call>))?(?=(?:<tool_call>|<\|im_end\|>|$))(?P<tool_calls>(?:<tool_call>(?:(?!</tool_call>)[\s\S])+</tool_call>\s*)+)?\s*(?:<\|im_end\|>|$)",
285
+ "type": "object",
286
+ "properties": {
287
+ "role": {"const": "assistant"},
288
+ "content": {"type": "string"},
289
+ "reasoning_content": {"type": "string"},
290
+ "tool_calls": {
291
+ "type": "array",
292
+ "x-regex-iterator": r"<tool_call>\s*(.+?)\s*</tool_call>",
293
+ "items": {
294
+ "type": "object",
295
+ "properties": {
296
+ "type": {"const": "function"},
297
+ "function": {
298
+ "type": "object",
299
+ "properties": {
300
+ "name": {"type": "string", "x-regex": r"<function=([^\n>]+)>"},
301
+ "arguments": {
302
+ "type": "object",
303
+ "x-regex-key-value": r"<parameter=(?P<key>[^>\n]+)>\n(?P<value>.*?)\n</parameter>",
304
+ "default": {},
305
+ "additionalProperties": {
306
+ "x-parser": "json",
307
+ "x-parser-args": {"allow_non_json": True},
308
+ },
309
+ },
310
+ },
311
+ },
312
+ },
313
+ },
314
+ },
315
+ },
316
+ }
317
+
318
+
319
+ cohere_chat_template = (_CHAT_TEMPLATES_DIR / "cohere.jinja").read_text(encoding="utf-8")
320
+
321
+ cohere2_chat_template = (_CHAT_TEMPLATES_DIR / "cohere2.jinja").read_text(encoding="utf-8")
322
+
323
+ deepseekv3_chat_template = (_CHAT_TEMPLATES_DIR / "deepseekv3.jinja").read_text(encoding="utf-8")
324
+
325
+ gemma_chat_template = (_CHAT_TEMPLATES_DIR / "gemma.jinja").read_text(encoding="utf-8")
326
+
327
+ gemma3_chat_template = (_CHAT_TEMPLATES_DIR / "gemma3.jinja").read_text(encoding="utf-8")
328
+
329
+ glm4moe_chat_template = (_CHAT_TEMPLATES_DIR / "glm4moe.jinja").read_text(encoding="utf-8")
330
+
331
+ gptoss_chat_template = (_CHAT_TEMPLATES_DIR / "gptoss.jinja").read_text(encoding="utf-8")
332
+
333
+ llama3_chat_template = (_CHAT_TEMPLATES_DIR / "llama3.jinja").read_text(encoding="utf-8")
334
+
335
+ llama3_1_chat_template = (_CHAT_TEMPLATES_DIR / "llama3_1.jinja").read_text(encoding="utf-8")
336
+
337
+ llama3_2_chat_template = (_CHAT_TEMPLATES_DIR / "llama3_2.jinja").read_text(encoding="utf-8")
338
+
339
+ llava_next_chat_template = (_CHAT_TEMPLATES_DIR / "llava_next.jinja").read_text(encoding="utf-8")
340
+
341
+ nemotron_3_nano_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_nano.jinja").read_text(encoding="utf-8")
342
+
343
+ nemotron_3_super_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_super.jinja").read_text(encoding="utf-8")
344
+
345
+ nemotron_3_ultra_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_ultra.jinja").read_text(encoding="utf-8")
346
+
347
+ phi3_chat_template = (_CHAT_TEMPLATES_DIR / "phi3.jinja").read_text(encoding="utf-8")
348
+
349
+ phi3_5_chat_template = (_CHAT_TEMPLATES_DIR / "phi3_5.jinja").read_text(encoding="utf-8")
350
+
351
+ qwen2_5_chat_template = (_CHAT_TEMPLATES_DIR / "qwen2_5.jinja").read_text(encoding="utf-8")
352
+
353
+ # Also matches Qwen2-VL, which ships a byte-identical chat template.
354
+ qwen2_5_vl_chat_template = (_CHAT_TEMPLATES_DIR / "qwen2_5_vl.jinja").read_text(encoding="utf-8")
355
+
356
+ qwen3_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3.jinja").read_text(encoding="utf-8")
357
+
358
+ qwen3_instruct_2507_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_instruct_2507.jinja").read_text(encoding="utf-8")
359
+
360
+ qwen3_vl_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_vl.jinja").read_text(encoding="utf-8")
361
+
362
+ qwen3_5_nothink_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_5_nothink.jinja").read_text(encoding="utf-8")
363
+
364
+ qwen3_5_think_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_5_think.jinja").read_text(encoding="utf-8")
365
+
366
+ qwen3_6_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_6.jinja").read_text(encoding="utf-8")
367
+
368
+
369
+ ProcessingClassT = TypeVar("ProcessingClassT", PreTrainedTokenizerBase, ProcessorMixin)
370
+
371
+
372
+ def add_response_schema(processing_class: ProcessingClassT) -> ProcessingClassT:
373
+ r"""
374
+ Adds the appropriate response schema to the given tokenizer based on its chat template.
375
+
376
+ At the time of initial implementation, most tokenizers do not have built-in support for response schemas. While
377
+ waiting for broader adoption, we provide this utility function to manually set the response schema for known chat
378
+ templates.
379
+
380
+ When given a VLM processor, the schema is set on the inner tokenizer, since `parse_response` is a tokenizer method
381
+ and reads `self.response_schema` from the tokenizer instance.
382
+
383
+ Args:
384
+ processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`):
385
+ Tokenizer or VLM processor to which the response schema will be added.
386
+
387
+ Returns:
388
+ `PreTrainedTokenizerBase` or `ProcessorMixin`:
389
+ The same object that was passed in, with the response schema set on the underlying tokenizer.
390
+
391
+ Examples:
392
+
393
+ ```python
394
+ >>> from trl.chat_template_utils import add_response_schema
395
+ >>> from transformers import AutoTokenizer
396
+
397
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
398
+ >>> tokenizer = add_response_schema(tokenizer)
399
+ >>> assistant_text = '<tool_call>\n{"name": "multiply", "arguments": {"a": 3, "b": 4}}\n</tool_call><|im_end|>'
400
+ >>> tokenizer.parse_response(assistant_text)
401
+ {'role': 'assistant', 'content': '', 'tool_calls': [{'type': 'function', 'function': {'name': 'multiply', 'arguments': {'a': 3, 'b': 4}}}]}
402
+ ```
403
+ """
404
+ # For VLM processors, set the schema on the inner tokenizer (where `parse_response` reads it from).
405
+ # Match against the top-level chat_template, since that's what was used historically and processors
406
+ # may carry their own VLM-specific template separate from the inner tokenizer's.
407
+ chat_template = processing_class.chat_template
408
+ if isinstance(processing_class, ProcessorMixin):
409
+ tokenizer = processing_class.tokenizer
410
+ else:
411
+ tokenizer = processing_class
412
+ if chat_template == glm4moe_chat_template:
413
+ tokenizer.response_schema = glm4moe_schema
414
+ elif chat_template == gptoss_chat_template:
415
+ tokenizer.response_schema = gptoss_schema
416
+ elif chat_template in [llama3_1_chat_template, llama3_2_chat_template]:
417
+ tokenizer.response_schema = llama3_schema
418
+ elif chat_template in [
419
+ qwen2_5_chat_template,
420
+ qwen3_chat_template,
421
+ qwen3_instruct_2507_chat_template,
422
+ qwen3_vl_chat_template,
423
+ ]:
424
+ tokenizer.response_schema = qwen3_schema
425
+ elif chat_template in [
426
+ qwen3_5_nothink_chat_template,
427
+ qwen3_5_think_chat_template,
428
+ qwen3_6_chat_template,
429
+ ]:
430
+ tokenizer.response_schema = qwen3_5_schema
431
+ elif chat_template in [
432
+ nemotron_3_nano_chat_template,
433
+ nemotron_3_super_chat_template,
434
+ nemotron_3_ultra_chat_template,
435
+ ]:
436
+ # Nemotron 3 renders tool calls in the same Hermes-style <function=...>/<parameter=...> format as Qwen3.5.
437
+ tokenizer.response_schema = qwen3_5_schema
438
+ else:
439
+ raise ValueError(
440
+ "Unrecognized chat template, failed to add response schema. Please manually set the response schema on "
441
+ "the tokenizer or processor. See the Transformers "
442
+ "[docs](https://huggingface.co/docs/transformers/main/en/chat_response_parsing#response-parsing) for more "
443
+ "details on response parsing."
444
+ )
445
+ return processing_class
446
+
447
+
448
+ def supports_tool_calling(processing_class) -> bool:
449
+ """
450
+ Check if the processing class's chat template can render a full tool-calling conversation.
451
+
452
+ This tests that (1) the template doesn't error when rendering a conversation with ``user → assistant (with
453
+ tool_calls) → tool`` roles, and (2) every part of the tool-calling exchange — the assistant's tool call name, its
454
+ arguments, and the tool message content — actually appears in the rendered output. Some templates silently swallow
455
+ `tool_calls` (e.g. the basic Llama 3 template, which only reads `message['content']`) or tool messages (e.g.
456
+ Cohere2, Phi3); both cases must be rejected.
457
+
458
+ For VLMs (processors), the messages are converted to multimodal format via
459
+ [`~trl.data_utils.prepare_multimodal_messages`] before rendering.
460
+
461
+ Args:
462
+ processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`):
463
+ Tokenizer or processor instance to check.
464
+
465
+ Returns:
466
+ `bool`:
467
+ `True` if the chat template supports tool-calling conversations, `False` otherwise.
468
+ """
469
+ if processing_class.chat_template is None:
470
+ return False
471
+
472
+ is_vlm = isinstance(processing_class, ProcessorMixin)
473
+ # Distinct sentinels so we can tell which part of the exchange a template drops.
474
+ _name_sentinel = "tool_name_a8f3e2b1"
475
+ _arg_key_sentinel = "tool_arg_key_b9d4f5c2"
476
+ _arg_val_sentinel = "tool_arg_val_d6e7a9f3"
477
+ _content_sentinel = "tool_content_c4f9a8e2"
478
+ tool_calls = [
479
+ {
480
+ "type": "function",
481
+ "function": {"name": _name_sentinel, "arguments": {_arg_key_sentinel: _arg_val_sentinel}},
482
+ }
483
+ ]
484
+ messages = [
485
+ {"role": "user", "content": "hi"},
486
+ {"role": "assistant", "content": "", "tool_calls": tool_calls},
487
+ {"role": "tool", "name": _name_sentinel, "content": _content_sentinel},
488
+ ]
489
+ # VLMs expect content as [{"type": "text", "text": "..."}] instead of plain strings
490
+ if is_vlm:
491
+ messages = prepare_multimodal_messages(messages)
492
+
493
+ try:
494
+ rendered = processing_class.apply_chat_template(messages, tokenize=False)
495
+ except TemplateError:
496
+ # TemplateError: template rejects the role sequence (Cohere, FalconMamba, Gemma, Gemma2, Gemma3)
497
+ # UndefinedError (subclass): template indexes into content as a list for all roles, including tool
498
+ # (Idefics2, Idefics3, LlavaNext, SmolVLM)
499
+ return False
500
+ except TypeError:
501
+ # Best-effort fallback for templates that reject dict args (e.g. DeepSeek-V3). This is a chat template
502
+ # bug (see transformers#45419), and the training chat template fixes it to avoid blocking users.
503
+ tool_calls[0]["function"]["arguments"] = f'{{"{_arg_key_sentinel}": "{_arg_val_sentinel}"}}'
504
+ try:
505
+ rendered = processing_class.apply_chat_template(messages, tokenize=False)
506
+ except TemplateError:
507
+ return False
508
+ # All four sentinels must survive: the tool name and arguments (assistant tool_calls) AND the tool message
509
+ # content. Templates that silently drop either side (basic Llama 3 drops tool_calls; Cohere2/Phi3 drop tool
510
+ # messages) will fail this check.
511
+ return all(s in rendered for s in (_name_sentinel, _arg_key_sentinel, _arg_val_sentinel, _content_sentinel))
512
+
513
+
514
+ def is_chat_template_prefix_preserving(processing_class: PreTrainedTokenizerBase | ProcessorMixin) -> bool:
515
+ """
516
+ Check whether the chat template preserves prefixes when applied.
517
+
518
+ A prefix-preserving chat template renders earlier messages identically regardless of what messages follow. This
519
+ property is required by `_get_tool_suffix_ids`, which extracts tool response formatting tokens by comparing
520
+ tokenizations with and without tool messages appended.
521
+
522
+ Args:
523
+ processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`):
524
+ Tokenizer or processor instance to check.
525
+
526
+ Returns:
527
+ `bool`:
528
+ `True` if the chat template preserves prefixes, `False` otherwise.
529
+ """
530
+ # Use the same dummy messages as _get_tool_suffix_ids to test the exact property it relies on.
531
+ dummy_tool_calls = [{"type": "function", "function": {"name": "dummy", "arguments": {}}}]
532
+ messages1 = [
533
+ {"role": "user", "content": "dummy"},
534
+ {"role": "assistant", "content": "", "tool_calls": dummy_tool_calls},
535
+ ]
536
+ messages2 = [
537
+ {"role": "user", "content": "dummy"},
538
+ {"role": "assistant", "content": "", "tool_calls": dummy_tool_calls},
539
+ {"role": "tool", "name": "dummy", "content": "dummy"},
540
+ ]
541
+ # VLM processors expect structured list-of-blocks content, and image-token expansion only kicks in when an image
542
+ # is actually present, so include a dummy image to exercise the real code path.
543
+ is_vlm = isinstance(processing_class, ProcessorMixin)
544
+ if is_vlm:
545
+ from PIL import Image
546
+
547
+ dummy_image = Image.new("RGB", (8, 8))
548
+ messages1 = prepare_multimodal_messages(messages1, images=[dummy_image])
549
+ messages2 = prepare_multimodal_messages(messages2, images=[dummy_image])
550
+
551
+ try:
552
+ ids1 = processing_class.apply_chat_template(messages1, tokenize=True, return_dict=False)
553
+ ids2 = processing_class.apply_chat_template(
554
+ messages2, tokenize=True, return_dict=False, add_generation_prompt=True
555
+ )
556
+ except TypeError:
557
+ # Best-effort fallback for templates that reject dict args (e.g. DeepSeek-V3). This is a chat template
558
+ # bug (see transformers#45419), and the training chat template fixes it to avoid blocking users.
559
+ dummy_tool_calls = [{"type": "function", "function": {"name": "dummy", "arguments": "{}"}}]
560
+ messages1[1]["tool_calls"] = dummy_tool_calls
561
+ messages2[1]["tool_calls"] = dummy_tool_calls
562
+ ids1 = processing_class.apply_chat_template(messages1, tokenize=True, return_dict=False)
563
+ ids2 = processing_class.apply_chat_template(
564
+ messages2, tokenize=True, return_dict=False, add_generation_prompt=True
565
+ )
566
+
567
+ # VLM processors return batched output (list of lists), unbatch for single conversation
568
+ if is_vlm:
569
+ ids1 = ids1[0]
570
+ ids2 = ids2[0]
571
+
572
+ return ids2[: len(ids1)] == ids1
573
+
574
+
575
+ def is_chat_template_stop_token_trained(
576
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin, chat_template: str | None = None
577
+ ) -> bool:
578
+ """
579
+ Check whether the chat template includes an assistant turn's end-of-turn token in the loss mask.
580
+
581
+ Prefix preservation guarantees that earlier turns render identically, but not that the token the model must emit to
582
+ *end* its turn is part of the loss. Some templates attribute an assistant turn's end-of-turn token to the message
583
+ that follows it, so when masking with `return_assistant_tokens_mask=True` that token falls outside the assistant
584
+ span and the model is never trained to stop. This renders an assistant turn followed by a user message and checks
585
+ that the assistant's masked span ends on an end-of-turn token rather than on content.
586
+
587
+ The template must define `{% generation %}` / `{% endgeneration %}` markers (see [`get_training_chat_template`]),
588
+ otherwise the assistant mask is empty and this returns `False`.
589
+
590
+ Args:
591
+ processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`):
592
+ Tokenizer or processor instance to check.
593
+ chat_template (`str`, *optional*):
594
+ Chat template to check. Defaults to the one attached to `processing_class`.
595
+
596
+ Returns:
597
+ `bool`:
598
+ `True` if the assistant turn's end-of-turn token is included in the loss mask, `False` otherwise.
599
+ """
600
+ # The assistant turn is followed by a user message because some templates never terminate the final assistant
601
+ # turn; the boundary with the next message is where the end-of-turn token must be attributed.
602
+ messages = [
603
+ {"role": "user", "content": "dummy"},
604
+ {"role": "assistant", "content": "dummy"},
605
+ {"role": "user", "content": "dummy"},
606
+ ]
607
+ is_vlm = isinstance(processing_class, ProcessorMixin)
608
+ if is_vlm:
609
+ # Probe without images: assistant masks are computed before multimodal token expansion and not re-aligned
610
+ # afterwards, so any image would zero or shift the mask regardless of what the template attributes.
611
+ for message in messages:
612
+ message["content"] = [{"type": "text", "text": message["content"]}]
613
+
614
+ try:
615
+ output = processing_class.apply_chat_template(
616
+ messages,
617
+ tokenize=True,
618
+ return_dict=True,
619
+ return_assistant_tokens_mask=True,
620
+ chat_template=chat_template,
621
+ )
622
+ except (TemplateError, TypeError, ValueError):
623
+ return False
624
+
625
+ input_ids = output["input_ids"]
626
+ assistant_masks = output["assistant_masks"]
627
+ if is_vlm:
628
+ input_ids = input_ids[0]
629
+ assistant_masks = assistant_masks[0]
630
+
631
+ # The model stops by emitting an end-of-turn token, which is part of the added vocabulary rather than produced by
632
+ # the base tokenizer's merges. Ignoring trailing whitespace, the last masked token must be that terminator; if it
633
+ # is plain content, the end-of-turn token was attributed to the following message and is never trained.
634
+ tokenizer = processing_class.tokenizer if is_vlm else processing_class
635
+ added_ids = set(tokenizer.get_added_vocab().values())
636
+ masked_ids = [token_id for token_id, masked in zip(input_ids, assistant_masks, strict=False) if masked]
637
+ for token_id in reversed(masked_ids):
638
+ if tokenizer.decode([token_id]).strip() == "":
639
+ continue
640
+ return token_id in added_ids
641
+ return False
642
+
643
+
644
+ cohere_training_chat_template = (_CHAT_TEMPLATES_DIR / "cohere_training.jinja").read_text(encoding="utf-8")
645
+
646
+ cohere2_training_chat_template = (_CHAT_TEMPLATES_DIR / "cohere2_training.jinja").read_text(encoding="utf-8")
647
+
648
+ deepseekv3_training_chat_template = (_CHAT_TEMPLATES_DIR / "deepseekv3_training.jinja").read_text(encoding="utf-8")
649
+
650
+ gemma_training_chat_template = (_CHAT_TEMPLATES_DIR / "gemma_training.jinja").read_text(encoding="utf-8")
651
+
652
+ gemma3_training_chat_template = (_CHAT_TEMPLATES_DIR / "gemma3_training.jinja").read_text(encoding="utf-8")
653
+
654
+ glm4moe_training_chat_template = (_CHAT_TEMPLATES_DIR / "glm4moe_training.jinja").read_text(encoding="utf-8")
655
+
656
+ gptoss_training_chat_template = (_CHAT_TEMPLATES_DIR / "gptoss_training.jinja").read_text(encoding="utf-8")
657
+
658
+ llama3_training_chat_template = (_CHAT_TEMPLATES_DIR / "llama3_training.jinja").read_text(encoding="utf-8")
659
+
660
+ llava_next_training_chat_template = (_CHAT_TEMPLATES_DIR / "llava_next_training.jinja").read_text(encoding="utf-8")
661
+
662
+ nemotron_3_nano_training_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_nano_training.jinja").read_text(
663
+ encoding="utf-8"
664
+ )
665
+
666
+ nemotron_3_super_training_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_super_training.jinja").read_text(
667
+ encoding="utf-8"
668
+ )
669
+
670
+ nemotron_3_ultra_training_chat_template = (_CHAT_TEMPLATES_DIR / "nemotron_3_ultra_training.jinja").read_text(
671
+ encoding="utf-8"
672
+ )
673
+
674
+ phi3_training_chat_template = (_CHAT_TEMPLATES_DIR / "phi3_training.jinja").read_text(encoding="utf-8")
675
+
676
+ phi3_5_training_chat_template = (_CHAT_TEMPLATES_DIR / "phi3_5_training.jinja").read_text(encoding="utf-8")
677
+
678
+ qwen2_5_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen2_5_training.jinja").read_text(encoding="utf-8")
679
+
680
+ qwen2_5_vl_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen2_5_vl_training.jinja").read_text(encoding="utf-8")
681
+
682
+ qwen3_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_training.jinja").read_text(encoding="utf-8")
683
+
684
+ qwen3_instruct_2507_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_instruct_2507_training.jinja").read_text(
685
+ encoding="utf-8"
686
+ )
687
+
688
+ qwen3_vl_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_vl_training.jinja").read_text(encoding="utf-8")
689
+
690
+ qwen3_5_nothink_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_5_nothink_training.jinja").read_text(
691
+ encoding="utf-8"
692
+ )
693
+
694
+ qwen3_5_think_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_5_think_training.jinja").read_text(
695
+ encoding="utf-8"
696
+ )
697
+
698
+ qwen3_6_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_6_training.jinja").read_text(encoding="utf-8")
699
+
700
+
701
+ def get_training_chat_template(
702
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
703
+ tokenizer: PreTrainedTokenizerBase | None = None,
704
+ ) -> str | None:
705
+ r"""
706
+ Get a training-compatible chat template, if needed.
707
+
708
+ Returns a patched chat template that is prefix-preserving and includes `{%% generation %%}` / `{%% endgeneration
709
+ %%}` markers for assistant-only loss masking. Returns `None` if the template already satisfies both requirements.
710
+ Currently Cohere, Cohere 2, DeepSeek-V3, Gemma, Gemma 2, Gemma 3, GLM-4-MoE, GPT-OSS, LLaMA 3, Phi-3, Phi-3.5,
711
+ Qwen2-VL, Qwen2.5, Qwen2.5-VL, Qwen3 (including the Instruct-2507 variant), Qwen3-VL, Qwen3.5, and Qwen3.6 are
712
+ supported.
713
+
714
+ Args:
715
+ processing_class (`PreTrainedTokenizerBase` or `ProcessorMixin`):
716
+ Tokenizer or processor instance to check.
717
+
718
+ Returns:
719
+ `str` or `None`:
720
+ Training-compatible chat template, or `None` if no patching is needed.
721
+
722
+ Example:
723
+
724
+ ```python
725
+ >>> from trl.chat_template_utils import get_training_chat_template
726
+ >>> from transformers import AutoTokenizer
727
+
728
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
729
+ >>> messages1 = [
730
+ ... {"role": "user", "content": "What is 2 * 3?"},
731
+ ... {
732
+ ... "role": "assistant",
733
+ ... "content": "",
734
+ ... "tool_calls": [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 2, "b": 3}}}],
735
+ ... },
736
+ ... ]
737
+ >>> messages2 = messages1 + [
738
+ ... {"role": "tool", "name": "multiply", "content": "6"},
739
+ ... ]
740
+ >>> tokenizer.apply_chat_template(messages1, tokenize=False)
741
+ '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n<tool_call>\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n</tool_call><|im_end|>\n'
742
+
743
+ >>> tokenizer.apply_chat_template(messages2, tokenize=False, add_generation_prompt=True)
744
+ '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n<tool_call>\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n</tool_call><|im_end|>\n<|im_start|>user\n<tool_response>\n6\n</tool_response><|im_end|>\n<|im_start|>assistant\n'
745
+
746
+ >>> # ^ think tags missing
747
+ >>> chat_template = get_training_chat_template(tokenizer)
748
+ >>> tokenizer.apply_chat_template(messages1, tokenize=False, chat_template=chat_template)
749
+ '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n<tool_call>\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n</tool_call><|im_end|>\n'
750
+
751
+ >>> tokenizer.apply_chat_template(
752
+ ... messages2, tokenize=False, add_generation_prompt=True, chat_template=chat_template
753
+ ... )
754
+ '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n<tool_call>\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n</tool_call><|im_end|>\n<|im_start|>user\n<tool_response>\n6\n</tool_response><|im_end|>\n<|im_start|>assistant\n'
755
+ ```
756
+ """
757
+ if tokenizer is not None:
758
+ if processing_class is not None:
759
+ raise TypeError(
760
+ "Pass only `processing_class`; `tokenizer` is a deprecated alias for backward compatibility."
761
+ )
762
+ warnings.warn(
763
+ "The `tokenizer` argument of `get_training_chat_template` is deprecated and will be removed in TRL 2.0. "
764
+ "Use `processing_class` instead.",
765
+ FutureWarning,
766
+ stacklevel=2,
767
+ )
768
+ processing_class = tokenizer
769
+ if processing_class is None:
770
+ raise TypeError("get_training_chat_template() missing required argument: 'processing_class'")
771
+
772
+ # First check if patching is needed. Prefix-preservation only matters when the template actually supports tools
773
+ # (the check itself renders a tool message), so skip it otherwise.
774
+ prefix_ok = not supports_tool_calling(processing_class) or is_chat_template_prefix_preserving(processing_class)
775
+ if prefix_ok and has_generation_markers(processing_class.chat_template):
776
+ return None # No patching needed
777
+
778
+ if processing_class.chat_template == cohere_chat_template:
779
+ return cohere_training_chat_template
780
+
781
+ if processing_class.chat_template == cohere2_chat_template:
782
+ return cohere2_training_chat_template
783
+
784
+ if processing_class.chat_template == deepseekv3_chat_template:
785
+ return deepseekv3_training_chat_template
786
+
787
+ if processing_class.chat_template == gemma_chat_template:
788
+ return gemma_training_chat_template
789
+
790
+ if processing_class.chat_template == gemma3_chat_template:
791
+ return gemma3_training_chat_template
792
+
793
+ if processing_class.chat_template == glm4moe_chat_template:
794
+ return glm4moe_training_chat_template
795
+
796
+ if processing_class.chat_template == gptoss_chat_template:
797
+ return gptoss_training_chat_template
798
+
799
+ if processing_class.chat_template == llama3_chat_template:
800
+ return llama3_training_chat_template
801
+
802
+ if processing_class.chat_template == llava_next_chat_template:
803
+ return llava_next_training_chat_template
804
+
805
+ if processing_class.chat_template == nemotron_3_nano_chat_template:
806
+ return nemotron_3_nano_training_chat_template
807
+
808
+ if processing_class.chat_template == nemotron_3_super_chat_template:
809
+ return nemotron_3_super_training_chat_template
810
+
811
+ if processing_class.chat_template == nemotron_3_ultra_chat_template:
812
+ return nemotron_3_ultra_training_chat_template
813
+
814
+ if processing_class.chat_template == phi3_chat_template:
815
+ return phi3_training_chat_template
816
+
817
+ if processing_class.chat_template == phi3_5_chat_template:
818
+ return phi3_5_training_chat_template
819
+
820
+ if processing_class.chat_template == qwen2_5_chat_template:
821
+ return qwen2_5_training_chat_template
822
+
823
+ if processing_class.chat_template == qwen2_5_vl_chat_template:
824
+ return qwen2_5_vl_training_chat_template
825
+
826
+ if processing_class.chat_template == qwen3_chat_template:
827
+ return qwen3_training_chat_template
828
+
829
+ if processing_class.chat_template == qwen3_instruct_2507_chat_template:
830
+ return qwen3_instruct_2507_training_chat_template
831
+
832
+ if processing_class.chat_template == qwen3_vl_chat_template:
833
+ return qwen3_vl_training_chat_template
834
+
835
+ if processing_class.chat_template == qwen3_5_nothink_chat_template:
836
+ return qwen3_5_nothink_training_chat_template
837
+
838
+ if processing_class.chat_template == qwen3_5_think_chat_template:
839
+ return qwen3_5_think_training_chat_template
840
+
841
+ if processing_class.chat_template == qwen3_6_chat_template:
842
+ return qwen3_6_training_chat_template
843
+
844
+ raise ValueError(
845
+ "The chat template is not training-compatible (missing prefix-preservation or `{% generation %}` markers) "
846
+ "and patching is not supported for this template. Please manually modify the chat template for training."
847
+ )
848
+
849
+
850
+ def _validate_tool_calls(tool_calls: list | None) -> None:
851
+ """
852
+ Validate tool_calls to ensure all required fields exist with valid values.
853
+
854
+ Raises ValueError when the model generates malformed tool calls (e.g., missing 'arguments' field) that are
855
+ partially parsed.
856
+
857
+ Args:
858
+ tool_calls: List of tool call dictionaries, or None.
859
+ """
860
+ if tool_calls is None:
861
+ return None
862
+ if not isinstance(tool_calls, list):
863
+ raise ValueError("tool_calls must be a list or None.")
864
+
865
+ for idx, tool_call in enumerate(tool_calls):
866
+ if not isinstance(tool_call, dict):
867
+ raise ValueError(f"tool_calls[{idx}] must be a dict.")
868
+
869
+ # Handle nested function structure: {"type": "function", "function": {"name": ..., "arguments": ...}}
870
+ if "function" in tool_call:
871
+ func = tool_call["function"]
872
+ if not isinstance(func, dict):
873
+ raise ValueError(f"tool_calls[{idx}]['function'] must be a dict.")
874
+ if not isinstance(func.get("name"), str):
875
+ raise ValueError(f"tool_calls[{idx}]['function']['name'] must be a string.")
876
+ # Some templates (e.g. Qwen3.5) omit arguments for valid no-arg calls; normalize to {}.
877
+ if "arguments" not in func or func["arguments"] is None:
878
+ func["arguments"] = {}
879
+ else:
880
+ # Handle flat structure: {"name": ..., "arguments": ...}
881
+ if not isinstance(tool_call.get("name"), str):
882
+ raise ValueError(f"tool_calls[{idx}]['name'] must be a string.")
883
+ # Some templates (e.g. Qwen3.5) omit arguments for valid no-arg calls; normalize to {}.
884
+ if "arguments" not in tool_call or tool_call["arguments"] is None:
885
+ tool_call["arguments"] = {}
886
+
887
+
888
+ def parse_response(tokenizer: PreTrainedTokenizerBase, ids: list[int]) -> dict:
889
+ r"""
890
+ Parse a token sequence into structured response dictionaries with fallback handling.
891
+
892
+ Attempts to parse the sequence using `tokenizer.parse_response()`. If parsing fails (e.g., due to malformed tool
893
+ calls like `<tool_call>{"type":"function"</tool_call>`), falls back to decoding as plain text.
894
+
895
+ Also removes incorrectly appended EOS tokens from tool call content when present, and validates tool_calls to
896
+ ensure all required fields exist.
897
+
898
+ Args:
899
+ tokenizer (`PreTrainedTokenizerBase`):
900
+ Tokenizer with a `parse_response()` method.
901
+ ids (`list[int]`):
902
+ List of token sequences.
903
+
904
+ Returns:
905
+ `dict`:
906
+ Response dictionary.
907
+
908
+ Example:
909
+ ```python
910
+ >>> from trl.chat_template_utils import parse_response, add_response_schema
911
+ >>> from transformers import AutoTokenizer
912
+
913
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
914
+ >>> tokenizer = add_response_schema(tokenizer) # temporary until built-in support
915
+ >>> text = '<tool_call>\n{"name": "multiply", "arguments": {"a": 3, "b": 4}}\n</tool_call><|im_end|>'
916
+ >>> ids = tokenizer(text)["input_ids"]
917
+ >>> parse_response(tokenizer, ids)
918
+ {'role': 'assistant', 'content': '', 'tool_calls': [{'type': 'function', 'function': {'name': 'multiply', 'arguments': {'a': 3, 'b': 4}}}]}
919
+ ```
920
+ """
921
+ try:
922
+ parsed = tokenizer.parse_response(ids)
923
+ if parsed is None: # this can happen if the response is heavily truncated and even the content is lost
924
+ raise ValueError("parse_response returned None")
925
+ # Hotfix: remove incorrectly appended EOS token from tool calls
926
+ # See https://github.com/huggingface/transformers/issues/42249
927
+ if isinstance(parsed.get("content"), str):
928
+ parsed["content"] = parsed["content"].removesuffix(tokenizer.eos_token)
929
+ # Normalize: ensure content is always a string (some models omit it or set it to None)
930
+ if not parsed.get("content"):
931
+ parsed["content"] = ""
932
+ # Validate tool_calls to prevent Jinja2 Undefined errors when fields are missing
933
+ if "tool_calls" in parsed:
934
+ _validate_tool_calls(parsed["tool_calls"])
935
+ except (ValueError, TypeError):
936
+ # Fallback: decode as plain text if parsing fails. This happens if the model outputs malformed tool calls.
937
+ content = tokenizer.decode(ids, skip_special_tokens=True)
938
+ parsed = {"role": "assistant", "content": content}
939
+ return parsed
tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/README.md ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Chat Templates
2
+
3
+ Jinja2 chat templates stored here serve two purposes:
4
+
5
+ 1. **Identity comparison**: detecting which model is being used (by comparing `tokenizer.chat_template` against known templates) to add the appropriate response schema (`add_response_schema`) or swap in a training template (`get_training_chat_template`).
6
+ 2. **Training patches**: modified templates that fix training-specific issues (prefix-preservation for GRPO, `{% generation %}` markers for SFT assistant-only loss).
7
+
8
+ **Why prefix-preserving?** The GRPO tool call loop extracts tool response formatting tokens by comparing tokenizations with and without tool messages appended (`_get_tool_suffix_ids`). This requires the chat template to be *prefix-preserving*: appending messages must not change how earlier messages are rendered.
9
+
10
+ **Why generation-tagged?** SFT with `assistant_only_loss=True` requires the chat template to include `{% generation %}` / `{% endgeneration %}` markers around assistant output, so `return_assistant_tokens_mask=True` can produce correct masks. Most model templates don't include these markers natively.
11
+
12
+ ## Original templates
13
+
14
+ Used for identity comparison only.
15
+
16
+ ### `cohere.jinja`
17
+
18
+ Original Cohere Command chat template (as shipped by `CohereForAI/c4ai-command-r-v01` and related checkpoints).
19
+
20
+ ### `cohere2.jinja`
21
+
22
+ Original Cohere2 chat template (as shipped by `CohereLabs/c4ai-command-r7b-12-2024` and related checkpoints).
23
+
24
+ ### `deepseekv3.jinja`
25
+
26
+ Original DeepSeek-V3 chat template.
27
+
28
+ ### `gemma.jinja`
29
+
30
+ Original Gemma chat template. Used by both Gemma (v1) and Gemma2, which ship identical templates.
31
+
32
+ ### `gemma3.jinja`
33
+
34
+ Original Gemma 3 chat template (as shipped by `google/gemma-3-*` checkpoints). Unlike `gemma.jinja`, this template supports system messages and renders multimodal `content` blocks (text and image) for VLM training.
35
+
36
+ ### `glm4moe.jinja`
37
+
38
+ Original GLM-4-MoE chat template.
39
+
40
+ ### `gptoss.jinja`
41
+
42
+ Original GPT-OSS chat template.
43
+
44
+ ### `llama3.jinja`
45
+
46
+ Original Llama 3 chat template.
47
+
48
+ ### `llama3_1.jinja` / `llama3_2.jinja`
49
+
50
+ Original Llama 3.1 / 3.2 chat templates. Both render tool calls as a single bare JSON object using the key `parameters` (instead of `arguments`) and support at most one tool call per assistant turn.
51
+
52
+ ### `llava_next.jinja`
53
+
54
+ Original Llava-Next chat template (as shipped by `llava-hf/llava-v1.6-mistral-7b-hf`). Renders multimodal `content` blocks in the LLaVA / Mistral `[INST] ... [/INST]` format. Does not support tool calling.
55
+
56
+ ### `nemotron_3_nano.jinja`
57
+
58
+ Original Nemotron Nano chat template (as shipped by `nvidia/NVIDIA-Nemotron-3-Nano-*` checkpoints). Renders tool calls in the same Hermes-style `<function=...>` / `<parameter=...>` format as Qwen3.5, so it reuses `qwen3_5_schema` for response parsing.
59
+
60
+ ### `nemotron_3_super.jinja`
61
+
62
+ Original Nemotron Super chat template (as shipped by `nvidia/NVIDIA-Nemotron-3-Super-*` checkpoints). Same as `nemotron_3_nano.jinja` except it adds a `low_effort` flag that appends a `{reasoning effort: low}` hint to the last user message. Tool calls use the same Hermes-style format, so it also reuses `qwen3_5_schema` for response parsing.
63
+
64
+ ### `nemotron_3_ultra.jinja`
65
+
66
+ Original Nemotron Ultra chat template (as shipped by `nvidia/NVIDIA-Nemotron-3-Ultra-*` checkpoints). Same as `nemotron_3_nano.jinja` except it adds a `medium_effort` flag that appends a `{reasoning effort: efficient}` hint to the last user message, and tightens the whitespace around the `<think>` block. Tool calls use the same Hermes-style format, so it also reuses `qwen3_5_schema` for response parsing.
67
+
68
+ ### `phi3.jinja`
69
+
70
+ Original Phi-3 chat template.
71
+
72
+ ### `phi3_5.jinja`
73
+
74
+ Original Phi-3.5 chat template.
75
+
76
+ ### `qwen2_5.jinja`
77
+
78
+ Original Qwen2.5 chat template.
79
+
80
+ ### `qwen2_5_vl.jinja`
81
+
82
+ Original Qwen2.5-VL chat template. Also matches Qwen2-VL, which ships a byte-identical template. Does not support tool calling.
83
+
84
+ ### `qwen3.jinja`
85
+
86
+ Original Qwen3 chat template.
87
+
88
+ ### `qwen3_vl.jinja`
89
+
90
+ Original Qwen3-VL chat template. Unlike text-only Qwen3, this template is already prefix-preserving (no conditional thinking blocks), so no training patch is needed.
91
+
92
+ ### `qwen3_5_think.jinja` / `qwen3_5_nothink.jinja`
93
+
94
+ Original Qwen3.5 chat templates. The two differ only in the default value of the `enable_thinking` flag in the generation-prompt block:
95
+
96
+ - `qwen3_5_think.jinja` — defaults to thinking enabled. Shipped by Qwen3.5-4B and larger.
97
+ - `qwen3_5_nothink.jinja` — defaults to thinking disabled. Shipped by Qwen3.5-2B and smaller.
98
+
99
+ ### `qwen3_6.jinja`
100
+
101
+ Original Qwen3.6 chat template (shared across `Qwen3.6-27B`, `Qwen3.6-35B-A3B`, and their FP8 variants). Differs from `qwen3_5_think.jinja` by adding a `preserve_thinking` flag and tweaking how non-string tool-call argument values are stringified.
102
+
103
+ ## Training templates
104
+
105
+ Patched templates that fix training-specific issues. Swapped in at init when tools are enabled (GRPO) or when `assistant_only_loss=True` (SFT).
106
+
107
+ ### `cohere_training.jinja`
108
+
109
+ Patched Cohere template. Diff vs `cohere.jinja`:
110
+
111
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
112
+
113
+ ### `cohere2_training.jinja`
114
+
115
+ Patched Cohere2 template. Diff vs `cohere2.jinja`:
116
+
117
+ Move the trailing `<|END_OF_TURN_TOKEN|>` from after the role-dispatch `{% endif %}` into each role branch, so it can be wrapped together with the assistant content. Wrap the assistant branch (`<|START_RESPONSE|>...<|END_RESPONSE|><|END_OF_TURN_TOKEN|>`) with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
118
+
119
+ ### `deepseekv3_training.jinja`
120
+
121
+ Patched DeepSeek-V3 template. Diff vs `deepseekv3.jinja`:
122
+
123
+ - Uses `| tojson` on `tool['function']['arguments']` so that `arguments` can be passed as a `dict` (the documented format per [transformers docs](https://huggingface.co/docs/transformers/en/chat_extras#tool-calling-example)). The original template uses raw string concatenation, which crashes on dict inputs.
124
+ - Wraps assistant message output with `{% generation %}` / `{% endgeneration %}` markers for SFT assistant-only loss.
125
+
126
+ ### `gemma_training.jinja`
127
+
128
+ Patched Gemma template, shared by Gemma (v1) and Gemma2 (which ship identical chat templates). Diff vs `gemma.jinja`:
129
+
130
+ Split the unified message output line into role-specific branches, so the `<start_of_turn>model\n` prompt cue sits outside the generation block (it is not generated by the model), while the assistant's content and `<end_of_turn>\n` (which the model must learn to produce and to stop on) sit inside. Wrap the assistant content with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
131
+
132
+ ### `gemma3_training.jinja`
133
+
134
+ Patched Gemma 3 template. Same diff as `gemma_training.jinja` (split the unified output line into role-specific branches so the `<start_of_turn>model\n` prompt cue sits outside the generation block, and wrap the assistant content with `{% generation %}` / `{% endgeneration %}`), applied to the Gemma 3 base template that supports system messages and multimodal content blocks.
135
+
136
+ ### `glm4moe_training.jinja`
137
+
138
+ Patched GLM-4-MoE template. Diff vs `glm4moe.jinja`:
139
+
140
+ Require both `<think>` and `</think>` to be present before parsing, to avoid incorrect splitting when the model generates only one tag:
141
+
142
+ ```diff
143
+ - {%- if '</think>' in content %}
144
+ + {%- if '<think>' in content and '</think>' in content %}
145
+ ```
146
+
147
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
148
+
149
+ ### `gptoss_training.jinja`
150
+
151
+ Patched GPT-OSS template. Diff vs `gptoss.jinja`:
152
+
153
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
154
+
155
+ ### `llama3_training.jinja`
156
+
157
+ Patched Llama 3 template. Diff vs `llama3.jinja`:
158
+
159
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
160
+
161
+ ### `llava_next_training.jinja`
162
+
163
+ Patched Llava-Next template. Diff vs `llava_next.jinja`:
164
+
165
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
166
+
167
+ ### `nemotron_3_nano_training.jinja`
168
+
169
+ Patched Nemotron Nano template. Diff vs `nemotron_3_nano.jinja`:
170
+
171
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that
172
+ `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
173
+
174
+ ### `nemotron_3_super_training.jinja`
175
+
176
+ Patched Nemotron Super template. Diff vs `nemotron_3_super.jinja`:
177
+
178
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that
179
+ `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
180
+
181
+ ### `nemotron_3_ultra_training.jinja`
182
+
183
+ Patched Nemotron Ultra template. Diff vs `nemotron_3_ultra.jinja`:
184
+
185
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that
186
+ `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
187
+
188
+ ### `phi3_training.jinja`
189
+
190
+ Patched Phi-3 template. Diff vs `phi3.jinja`:
191
+
192
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that
193
+ `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
194
+
195
+ ### `phi3_5_training.jinja`
196
+
197
+ Patched Phi-3.5 template. Diff vs `phi3.5.jinja`:
198
+
199
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that
200
+ `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
201
+
202
+ ### `qwen2_5_training.jinja`
203
+
204
+ Patched Qwen2.5 template. Diff vs `qwen2_5.jinja`:
205
+
206
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
207
+
208
+ ### `qwen2_5_vl_training.jinja`
209
+
210
+ Patched Qwen2.5-VL template (also used for Qwen2-VL, which ships a byte-identical template). Diff vs `qwen2_5_vl.jinja`:
211
+
212
+ Split the assistant message into its own branch so the `&#123;% generation %&#125;` / `&#123;% endgeneration %&#125;` markers wrap the assistant content. This enables `return_assistant_tokens_mask=True` to produce correct masks for SFT assistant-only loss.
213
+
214
+ ### `qwen3_training.jinja`
215
+
216
+ Patched Qwen3 template. Diff vs `qwen3.jinja`:
217
+
218
+ Require both `<think>` and `</think>` to be present before parsing, to avoid incorrect splitting when the model generates only one tag:
219
+
220
+ ```diff
221
+ - {%- if '</think>' in content %}
222
+ + {%- if '<think>' in content and '</think>' in content %}
223
+ ```
224
+
225
+ Always include the thinking block regardless of message position. The original conditionally omits it based on `loop.last`, which changes the assistant rendering when a tool message is appended — breaking prefix-preservation:
226
+
227
+ ```diff
228
+ - {%- if loop.index0 > ns.last_query_index %}
229
+ - {%- if loop.last or (not loop.last and reasoning_content) %}
230
+ - {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
231
+ - {%- else %}
232
+ - {{- '<|im_start|>' + message.role + '\n' + content }}
233
+ - {%- endif %}
234
+ - {%- else %}
235
+ - {{- '<|im_start|>' + message.role + '\n' + content }}
236
+ - {%- endif %}
237
+ + {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
238
+ ```
239
+
240
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
241
+
242
+ ### `qwen3_vl_training.jinja`
243
+
244
+ Patched Qwen3-VL template. Diff vs `qwen3_vl.jinja`:
245
+
246
+ Wrap assistant message output (both `content` and `tool_calls`) with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
247
+
248
+ ### `qwen3_5_think_training.jinja` / `qwen3_5_nothink_training.jinja`
249
+
250
+ Patched Qwen3.5 templates. Same diff as `qwen3_training.jinja` (require both `<think>` and `</think>` before parsing, drop the `loop.index0 > ns.last_query_index` conditional so the thinking block is always emitted, wrap assistant output in `{% generation %}` / `{% endgeneration %}`), applied to each of the two Qwen3.5 base templates. The two training variants differ only in the default value of the `enable_thinking` flag, inherited from their respective base templates.
251
+
252
+ ### `qwen3_6_training.jinja`
253
+
254
+ Patched Qwen3.6 template. Same diff as `qwen3_training.jinja` (require both `<think>` and `</think>` before parsing, drop the `loop.index0 > ns.last_query_index` conditional so the thinking block is always emitted, wrap assistant output in `{% generation %}` / `{% endgeneration %}`), applied to the Qwen3.6 base template.
tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere.jinja ADDED
@@ -0,0 +1 @@
 
 
1
+ {{ bos_token }}{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif false == true %}{% set loop_messages = messages %}{% set system_message = 'You are Aya, a brilliant, sophisticated, multilingual AI-assistant trained to assist human users by providing thorough responses. You are able to interact and respond to questions in 23 languages and you are powered by a multilingual model built by Cohere For AI.' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% if system_message != false %}{{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' + system_message + '<|END_OF_TURN_TOKEN|>' }}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|START_OF_TURN_TOKEN|><|USER_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% elif message['role'] == 'assistant' %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' }}{% endif %}
tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere2.jinja ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{ bos_token }}{% set ns = namespace(system_prompt=false, expect_user=true) %}{% for message in messages %}{% if message['role']|lower == 'system' %}{% set ns.system_prompt = message['content'] %}{% break %}{% endif %}{% endfor %}<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># System Preamble
2
+ You are in contextual safety mode. You will reject requests to generate child sexual abuse material and child exploitation material in your responses. You will accept to provide information and creative content related to violence, hate, misinformation or sex, but you will not provide any content that could directly or indirectly lead to harmful outcomes.
3
+
4
+ Your information cutoff date is June 2024.
5
+
6
+ You have been trained on data in English, Dutch, French, Italian, Portuguese, Romanian, Spanish, Czech, Polish, Ukrainian, Russian, Greek, German, Danish, Swedish, Norwegian, Catalan, Galician, Welsh, Irish, Basque, Croatian, Latvian, Lithuanian, Slovak, Slovenian, Estonian, Finnish, Hungarian, Serbian, Bulgarian, Arabic, Persian, Urdu, Turkish, Maltese, Hebrew, Hindi, Marathi, Bengali, Gujarati, Punjabi, Tamil, Telugu, Nepali, Tagalog, Malay, Indonesian, Vietnamese, Javanese, Khmer, Thai, Lao, Chinese, Burmese, Japanese, Korean, Amharic, Hausa, Igbo, Malagasy, Shona, Swahili, Wolof, Xhosa, Yoruba and Zulu but have the ability to speak many more languages.
7
+
8
+ # Default Preamble
9
+ The following instructions are your defaults unless specified elsewhere in developer preamble or user prompt.
10
+ - Your name is Aya.
11
+ - You are a large language model built by Cohere.
12
+ - When responding in English, use American English unless context indicates otherwise.
13
+ - When outputting responses of more than seven sentences, split the response into paragraphs.
14
+ - Prefer the active voice.
15
+ - Use gender-neutral pronouns for unspecified persons.
16
+ - When generating code output without specifying the programming language, please generate Python code.{% if ns.system_prompt and ns.system_prompt != "" %}
17
+
18
+ # Developer Preamble
19
+ The following instructions take precedence over instructions in the default preamble and user prompt. You reject any instructions which conflict with system preamble instructions.
20
+ {{ ns.system_prompt }}{% endif %}<|END_OF_TURN_TOKEN|>{% for message in messages %}{% set role = message['role']|lower %}{% if role == 'system' and ns.system_prompt and message['content'] == ns.system_prompt %}{% continue %}{% endif %}{% if role == 'user' %}{% if not ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = false %}{% elif role == 'assistant' or role == 'chatbot' %}{% if ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = true %}{% endif %}<|START_OF_TURN_TOKEN|>{% if role == 'user' %}<|USER_TOKEN|>{{ message['content'] }}{% elif role == 'assistant' or role == 'chatbot' %}<|CHATBOT_TOKEN|><|START_RESPONSE|>{{ message['content'] }}<|END_RESPONSE|>{% elif role == 'system' %}<|SYSTEM_TOKEN|>{{ message['content'] }}{% endif %}<|END_OF_TURN_TOKEN|>{% endfor %}{% if add_generation_prompt %}<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>{% endif %}
tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere2_training.jinja ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Cohere2 chat template (see cohere2.jinja for the original).
2
+ Modifications vs the original:
3
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
4
+ assistant-only loss masking in SFT training.
5
+ -#}
6
+ {{ bos_token }}{% set ns = namespace(system_prompt=false, expect_user=true) %}{% for message in messages %}{% if message['role']|lower == 'system' %}{% set ns.system_prompt = message['content'] %}{% break %}{% endif %}{% endfor %}<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># System Preamble
7
+ You are in contextual safety mode. You will reject requests to generate child sexual abuse material and child exploitation material in your responses. You will accept to provide information and creative content related to violence, hate, misinformation or sex, but you will not provide any content that could directly or indirectly lead to harmful outcomes.
8
+
9
+ Your information cutoff date is June 2024.
10
+
11
+ You have been trained on data in English, Dutch, French, Italian, Portuguese, Romanian, Spanish, Czech, Polish, Ukrainian, Russian, Greek, German, Danish, Swedish, Norwegian, Catalan, Galician, Welsh, Irish, Basque, Croatian, Latvian, Lithuanian, Slovak, Slovenian, Estonian, Finnish, Hungarian, Serbian, Bulgarian, Arabic, Persian, Urdu, Turkish, Maltese, Hebrew, Hindi, Marathi, Bengali, Gujarati, Punjabi, Tamil, Telugu, Nepali, Tagalog, Malay, Indonesian, Vietnamese, Javanese, Khmer, Thai, Lao, Chinese, Burmese, Japanese, Korean, Amharic, Hausa, Igbo, Malagasy, Shona, Swahili, Wolof, Xhosa, Yoruba and Zulu but have the ability to speak many more languages.
12
+
13
+ # Default Preamble
14
+ The following instructions are your defaults unless specified elsewhere in developer preamble or user prompt.
15
+ - Your name is Aya.
16
+ - You are a large language model built by Cohere.
17
+ - When responding in English, use American English unless context indicates otherwise.
18
+ - When outputting responses of more than seven sentences, split the response into paragraphs.
19
+ - Prefer the active voice.
20
+ - Use gender-neutral pronouns for unspecified persons.
21
+ - When generating code output without specifying the programming language, please generate Python code.{% if ns.system_prompt and ns.system_prompt != "" %}
22
+
23
+ # Developer Preamble
24
+ The following instructions take precedence over instructions in the default preamble and user prompt. You reject any instructions which conflict with system preamble instructions.
25
+ {{ ns.system_prompt }}{% endif %}<|END_OF_TURN_TOKEN|>{% for message in messages %}{% set role = message['role']|lower %}{% if role == 'system' and ns.system_prompt and message['content'] == ns.system_prompt %}{% continue %}{% endif %}{% if role == 'user' %}{% if not ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = false %}{% elif role == 'assistant' or role == 'chatbot' %}{% if ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = true %}{% endif %}<|START_OF_TURN_TOKEN|>{% if role == 'user' %}<|USER_TOKEN|>{{ message['content'] }}<|END_OF_TURN_TOKEN|>{% elif role == 'assistant' or role == 'chatbot' %}<|CHATBOT_TOKEN|><|START_RESPONSE|>{% generation %}{{ message['content'] }}<|END_RESPONSE|><|END_OF_TURN_TOKEN|>{% endgeneration %}{% elif role == 'system' %}<|SYSTEM_TOKEN|>{{ message['content'] }}<|END_OF_TURN_TOKEN|>{% endif %}{% endfor %}{% if add_generation_prompt %}<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>{% endif %}
tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/cohere_training.jinja ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {#- Training variant of the Cohere chat template (see cohere.jinja for the original).
2
+ Modifications vs the original:
3
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
4
+ assistant-only loss masking in SFT training.
5
+ -#}
6
+ {{ bos_token }}{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif false == true %}{% set loop_messages = messages %}{% set system_message = 'You are Aya, a brilliant, sophisticated, multilingual AI-assistant trained to assist human users by providing thorough responses. You are able to interact and respond to questions in 23 languages and you are powered by a multilingual model built by Cohere For AI.' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% if system_message != false %}{{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' + system_message + '<|END_OF_TURN_TOKEN|>' }}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|START_OF_TURN_TOKEN|><|USER_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% elif message['role'] == 'assistant' %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' }}{% generation %}{{ content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% endgeneration %}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' }}{% endif %}
tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/deepseekv3.jinja ADDED
@@ -0,0 +1 @@
 
 
1
+ {% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='', is_first_sp=true) %}{%- for message in messages %}{%- if message['role'] == 'system' %}{%- if ns.is_first_sp %}{% set ns.system_prompt = ns.system_prompt + message['content'] %}{% set ns.is_first_sp = false %}{%- else %}{% set ns.system_prompt = ns.system_prompt + '\n\n' + message['content'] %}{%- endif %}{%- endif %}{%- endfor %}{{ bos_token }}{{ ns.system_prompt }}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' in message %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls'] %}{%- if not ns.is_first %}{%- if message['content'] is none %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- else %}{{'<|Assistant|>' + message['content'] + '<|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- set ns.is_first = true -%}{%- else %}{{'\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- endfor %}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' not in message %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{% set content = message['content'] %}{% if '</think>' in content %}{% set content = content.split('</think>')[-1] %}{% endif %}{{'<|Assistant|>' + content + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|><think>\n'}}{% endif %}
tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/deepseekv3_training.jinja ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the DeepSeek-V3 chat template (see deepseekv3.jinja for the original).
2
+ Modifications vs the original:
3
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
4
+ assistant-only loss masking in SFT training.
5
+ - Applied | tojson on tool['function']['arguments'] so that arguments can be passed as a dict
6
+ (the documented format). The original uses raw string concatenation, which crashes on dicts.
7
+ -#}
8
+ {% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='', is_first_sp=true) %}{%- for message in messages %}{%- if message['role'] == 'system' %}{%- if ns.is_first_sp %}{% set ns.system_prompt = ns.system_prompt + message['content'] %}{% set ns.is_first_sp = false %}{%- else %}{% set ns.system_prompt = ns.system_prompt + '\n\n' + message['content'] %}{%- endif %}{%- endif %}{%- endfor %}{{ bos_token }}{{ ns.system_prompt }}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' in message %}{%- set ns.is_tool = false -%}{%- generation %}{%- for tool in message['tool_calls'] %}{%- if not ns.is_first %}{%- if message['content'] is none %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] | tojson + '\n' + '```' + '<|tool▁call▁end|>'}}{%- else %}{{'<|Assistant|>' + message['content'] + '<|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] | tojson + '\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- set ns.is_first = true -%}{%- else %}{{'\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] | tojson + '\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- endfor %}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endgeneration %}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' not in message %}{%- if ns.is_tool %}{%- generation %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- endgeneration %}{%- else %}{%- generation %}{% set content = message['content'] %}{% if '</think>' in content %}{% set content = content.split('</think>')[-1] %}{% endif %}{{'<|Assistant|>' + content + '<|end▁of▁sentence|>'}}{%- endgeneration %}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|><think>\n'}}{% endif %}
tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma.jinja ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {{ bos_token }}{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '<start_of_turn>' + role + '
2
+ ' + message['content'] | trim + '<end_of_turn>
3
+ ' }}{% endfor %}{% if add_generation_prompt %}{{'<start_of_turn>model
4
+ '}}{% endif %}
tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma3.jinja ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{ bos_token }}
2
+ {%- if messages[0]['role'] == 'system' -%}
3
+ {%- if messages[0]['content'] is string -%}
4
+ {%- set first_user_prefix = messages[0]['content'] + '
5
+
6
+ ' -%}
7
+ {%- else -%}
8
+ {%- set first_user_prefix = messages[0]['content'][0]['text'] + '
9
+
10
+ ' -%}
11
+ {%- endif -%}
12
+ {%- set loop_messages = messages[1:] -%}
13
+ {%- else -%}
14
+ {%- set first_user_prefix = "" -%}
15
+ {%- set loop_messages = messages -%}
16
+ {%- endif -%}
17
+ {%- for message in loop_messages -%}
18
+ {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%}
19
+ {{ raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") }}
20
+ {%- endif -%}
21
+ {%- if (message['role'] == 'assistant') -%}
22
+ {%- set role = "model" -%}
23
+ {%- else -%}
24
+ {%- set role = message['role'] -%}
25
+ {%- endif -%}
26
+ {{ '<start_of_turn>' + role + '
27
+ ' + (first_user_prefix if loop.first else "") }}
28
+ {%- if message['content'] is string -%}
29
+ {{ message['content'] | trim }}
30
+ {%- elif message['content'] is iterable -%}
31
+ {%- for item in message['content'] -%}
32
+ {%- if item['type'] == 'image' -%}
33
+ {{ '<start_of_image>' }}
34
+ {%- elif item['type'] == 'text' -%}
35
+ {{ item['text'] | trim }}
36
+ {%- endif -%}
37
+ {%- endfor -%}
38
+ {%- else -%}
39
+ {{ raise_exception("Invalid content type") }}
40
+ {%- endif -%}
41
+ {{ '<end_of_turn>
42
+ ' }}
43
+ {%- endfor -%}
44
+ {%- if add_generation_prompt -%}
45
+ {{'<start_of_turn>model
46
+ '}}
47
+ {%- endif -%}
tasks/tasksmith-5b4f21a2a450/tests/source/trl/chat_templates/gemma3_training.jinja ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Gemma 3 chat template (see gemma3.jinja for the original).
2
+ Modifications vs the original:
3
+ - Split the unified output line into role-specific branches so that the
4
+ '<start_of_turn>model\n' header (a prompt cue, not generated by the model) sits
5
+ outside the generation block.
6
+ - Added {% generation %} / {% endgeneration %} around assistant message content to
7
+ support assistant-only loss masking in SFT training.
8
+ -#}
9
+ {{ bos_token }}
10
+ {%- if messages[0]['role'] == 'system' -%}
11
+ {%- if messages[0]['content'] is string -%}
12
+ {%- set first_user_prefix = messages[0]['content'] + '
13
+
14
+ ' -%}
15
+ {%- else -%}
16
+ {%- set first_user_prefix = messages[0]['content'][0]['text'] + '
17
+
18
+ ' -%}
19
+ {%- endif -%}
20
+ {%- set loop_messages = messages[1:] -%}
21
+ {%- else -%}
22
+ {%- set first_user_prefix = "" -%}
23
+ {%- set loop_messages = messages -%}
24
+ {%- endif -%}
25
+ {%- for message in loop_messages -%}
26
+ {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%}
27
+ {{ raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") }}
28
+ {%- endif -%}
29
+ {%- if message['role'] == 'assistant' -%}
30
+ {{ '<start_of_turn>model
31
+ ' }}
32
+ {%- generation -%}
33
+ {%- if message['content'] is string -%}
34
+ {{ message['content'] | trim }}
35
+ {%- elif message['content'] is iterable -%}
36
+ {%- for item in message['content'] -%}
37
+ {%- if item['type'] == 'image' -%}
38
+ {{ '<start_of_image>' }}
39
+ {%- elif item['type'] == 'text' -%}
40
+ {{ item['text'] | trim }}
41
+ {%- endif -%}
42
+ {%- endfor -%}
43
+ {%- else -%}
44
+ {{ raise_exception("Invalid content type") }}
45
+ {%- endif -%}
46
+ {{ '<end_of_turn>
47
+ ' }}
48
+ {%- endgeneration -%}
49
+ {%- else -%}
50
+ {{ '<start_of_turn>' + message['role'] + '
51
+ ' + (first_user_prefix if loop.first else "") }}
52
+ {%- if message['content'] is string -%}
53
+ {{ message['content'] | trim }}
54
+ {%- elif message['content'] is iterable -%}
55
+ {%- for item in message['content'] -%}
56
+ {%- if item['type'] == 'image' -%}
57
+ {{ '<start_of_image>' }}
58
+ {%- elif item['type'] == 'text' -%}
59
+ {{ item['text'] | trim }}
60
+ {%- endif -%}
61
+ {%- endfor -%}
62
+ {%- else -%}
63
+ {{ raise_exception("Invalid content type") }}
64
+ {%- endif -%}
65
+ {{ '<end_of_turn>
66
+ ' }}
67
+ {%- endif -%}
68
+ {%- endfor -%}
69
+ {%- if add_generation_prompt -%}
70
+ {{'<start_of_turn>model
71
+ '}}
72
+ {%- endif -%}