Stage Harbor release files 72001-72500
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_gspo_token_trainer.py +60 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_harbor.py +138 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_kto_trainer.py +774 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_merge_model_callback.py +84 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_minillm_trainer.py +52 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_modeling_value_head.py +112 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_nash_md_trainer.py +195 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_online_dpo_trainer.py +461 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_openreward.py +252 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_orpo_trainer.py +198 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_ppo_trainer.py +829 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_prm_trainer.py +376 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_sdft_trainer.py +524 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_sdpo_trainer.py +582 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_self_distillation_trainer_behavior.py +336 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_ssd_trainer.py +237 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_tpo_trainer.py +332 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_utils.py +160 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_xpo_trainer.py +143 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/invariant/README.md +57 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/invariant/__init__.py +14 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/invariant/references/dpo.json +280 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/invariant/references/sft.json +280 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/invariant/references/sft_fa2.json +281 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/invariant/test_invariant.py +299 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/tasksmith_behavior.py +202 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_activation_offloading.py +237 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_callbacks.py +238 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_chat_template_utils.py +1258 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_cli.py +140 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_cli_utils.py +426 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_data_utils.py +1335 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_dpo_trainer.py +1358 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_grpo_trainer.py +0 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_model_utils.py +34 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_reward_trainer.py +868 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_rewards.py +399 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_rich_progress_callback.py +64 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_rloo_trainer.py +1836 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_sft_trainer.py +0 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_skills.py +578 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_skills_cli.py +288 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_utils.py +1380 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_vllm_client_server.py +1036 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/testing_constants.py +18 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/tests/testing_utils.py +150 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/trl/__init__.py +132 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/trl/_compat.py +164 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/trl/_lazy_module.py +79 -0
- tasks/tasksmith-b71e9e0a47b6/tests/source/trl/accelerate_configs/fsdp1.yaml +28 -0
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_gspo_token_trainer.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import torch
|
| 17 |
+
from datasets import load_dataset
|
| 18 |
+
from transformers.utils import is_peft_available
|
| 19 |
+
|
| 20 |
+
from trl import GRPOConfig
|
| 21 |
+
from trl.experimental.gspo_token import GRPOTrainer as GSPOTokenTrainer
|
| 22 |
+
|
| 23 |
+
from ..testing_utils import TrlTestCase
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if is_peft_available():
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TestGSPOTokenTrainer(TrlTestCase):
|
| 31 |
+
def test_train(self):
|
| 32 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 33 |
+
|
| 34 |
+
training_args = GRPOConfig(
|
| 35 |
+
output_dir=self.tmp_dir,
|
| 36 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 37 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 38 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 39 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 40 |
+
num_iterations=2, # the importance sampling weights won't be 0 in this case
|
| 41 |
+
importance_sampling_level="sequence_token",
|
| 42 |
+
report_to="none",
|
| 43 |
+
)
|
| 44 |
+
trainer = GSPOTokenTrainer(
|
| 45 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 46 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 47 |
+
args=training_args,
|
| 48 |
+
train_dataset=dataset,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 52 |
+
|
| 53 |
+
trainer.train()
|
| 54 |
+
|
| 55 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 56 |
+
|
| 57 |
+
# Check that the params have changed
|
| 58 |
+
for n, param in previous_trainable_params.items():
|
| 59 |
+
new_param = trainer.model.get_parameter(n)
|
| 60 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_harbor.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Tests for the Harbor x TRL integration that don't need a running Harbor sandbox.
|
| 16 |
+
|
| 17 |
+
`harbor` is imported lazily (only when an env is *started*), so spec construction, agent resolution, dataset building,
|
| 18 |
+
and the reward function are all testable without `harbor` / a sandbox backend.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import pytest
|
| 24 |
+
|
| 25 |
+
from trl.experimental.harbor import AGENTS, HarborBashEnv, HarborEnv, HarborSpec
|
| 26 |
+
from trl.experimental.harbor._spec import _outcome_reward_func, _resolve_agent
|
| 27 |
+
|
| 28 |
+
from ..testing_utils import TrlTestCase
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _write_task(tasks_dir: Path, task_id: str, gold: str, difficulty: int) -> None:
|
| 32 |
+
d = tasks_dir / task_id
|
| 33 |
+
(d / "environment").mkdir(parents=True)
|
| 34 |
+
(d / "tests").mkdir()
|
| 35 |
+
(d / "instruction.md").write_text(f"Solve task {task_id}.")
|
| 36 |
+
# Built from a joined list (not a triple-quoted block) so doc-builder doesn't reflow the TOML.
|
| 37 |
+
lines = [
|
| 38 |
+
"[task]",
|
| 39 |
+
f'name = "{task_id}"',
|
| 40 |
+
"[metadata]",
|
| 41 |
+
f'gold_answer = "{gold}"',
|
| 42 |
+
'reward_mode_initial = "exact_short"',
|
| 43 |
+
f"difficulty_level = {difficulty}",
|
| 44 |
+
f'kaggle_dataset_name = "owner/{task_id}"',
|
| 45 |
+
]
|
| 46 |
+
(d / "task.toml").write_text("\n".join(lines))
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class TestResolveAgent(TrlTestCase):
|
| 50 |
+
def test_builtin_name(self):
|
| 51 |
+
assert _resolve_agent("bash") is HarborBashEnv
|
| 52 |
+
assert AGENTS["bash"] is HarborBashEnv
|
| 53 |
+
|
| 54 |
+
def test_class_passthrough(self):
|
| 55 |
+
assert _resolve_agent(HarborBashEnv) is HarborBashEnv
|
| 56 |
+
|
| 57 |
+
def test_import_path(self):
|
| 58 |
+
assert _resolve_agent("trl.experimental.harbor:HarborBashEnv") is HarborBashEnv
|
| 59 |
+
|
| 60 |
+
def test_file_path(self):
|
| 61 |
+
path = Path(self.tmp_dir) / "my_harness.py"
|
| 62 |
+
path.write_text(
|
| 63 |
+
"from trl.experimental.harbor import HarborEnv\n"
|
| 64 |
+
"class MyEnv(HarborEnv):\n"
|
| 65 |
+
" def run_cmd(self, command: str) -> str:\n"
|
| 66 |
+
" 'Run a command.\\n\\nArgs:\\n command: cmd.'\n"
|
| 67 |
+
" return self._exec(command)\n"
|
| 68 |
+
)
|
| 69 |
+
cls = _resolve_agent(f"{path}:MyEnv")
|
| 70 |
+
assert issubclass(cls, HarborEnv) and cls.__name__ == "MyEnv"
|
| 71 |
+
|
| 72 |
+
def test_unknown_name_raises(self):
|
| 73 |
+
with pytest.raises(ValueError):
|
| 74 |
+
_resolve_agent("not-a-harness")
|
| 75 |
+
|
| 76 |
+
def test_non_harborenv_raises(self):
|
| 77 |
+
with pytest.raises(TypeError):
|
| 78 |
+
_resolve_agent("trl.experimental.harbor:HarborSpec") # not a HarborEnv subclass
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class TestHarborSpecDataset(TrlTestCase):
|
| 82 |
+
def _suite(self) -> str:
|
| 83 |
+
tasks = Path(self.tmp_dir) / "tasks"
|
| 84 |
+
tasks.mkdir()
|
| 85 |
+
_write_task(tasks, "0001_a", "alpha", 0)
|
| 86 |
+
_write_task(tasks, "0002_b", "beta", 3)
|
| 87 |
+
return str(self.tmp_dir)
|
| 88 |
+
|
| 89 |
+
def test_train_dataset_columns_and_metadata(self):
|
| 90 |
+
ds = HarborSpec(self._suite()).train_dataset
|
| 91 |
+
assert len(ds) == 2
|
| 92 |
+
assert ds[0]["prompt"] == [{"role": "user", "content": ""}] # env appends instruction at reset
|
| 93 |
+
assert ds[0]["task_dir"].endswith("0001_a")
|
| 94 |
+
assert ds[0]["task_index"] == 0
|
| 95 |
+
assert ds[0]["gold_answer"] == "alpha"
|
| 96 |
+
assert ds[1]["difficulty_level"] == 3
|
| 97 |
+
|
| 98 |
+
def test_num_tasks_cap(self):
|
| 99 |
+
ds = HarborSpec(self._suite(), num_tasks=1).train_dataset
|
| 100 |
+
assert len(ds) == 1
|
| 101 |
+
|
| 102 |
+
def test_indices_selection(self):
|
| 103 |
+
ds = HarborSpec(self._suite(), indices=[1]).train_dataset
|
| 104 |
+
assert len(ds) == 1 and ds[0]["task_dir"].endswith("0002_b")
|
| 105 |
+
|
| 106 |
+
def test_num_tasks_and_indices_mutually_exclusive(self):
|
| 107 |
+
with pytest.raises(ValueError):
|
| 108 |
+
HarborSpec(self._suite(), num_tasks=1, indices=[0])
|
| 109 |
+
|
| 110 |
+
def test_environment_factory_returns_fresh_envs(self):
|
| 111 |
+
factory = HarborSpec(self._suite(), agent="bash").environment_factory
|
| 112 |
+
e1, e2 = factory(), factory()
|
| 113 |
+
assert isinstance(e1, HarborBashEnv) and e1 is not e2
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class TestRewardFunc(TrlTestCase):
|
| 117 |
+
def test_outcome_reward_reads_env_reward(self):
|
| 118 |
+
class _Env:
|
| 119 |
+
def __init__(self, r):
|
| 120 |
+
self.reward = r
|
| 121 |
+
|
| 122 |
+
assert _outcome_reward_func([_Env(1.0), _Env(0.0)]) == [1.0, 0.0]
|
| 123 |
+
|
| 124 |
+
def test_outcome_reward_uses_environment_reward_when_passed(self):
|
| 125 |
+
# AsyncGRPOTrainer captures rewards in its rollout worker and passes them as a list, with no
|
| 126 |
+
# live env instances. The reward func must use them directly.
|
| 127 |
+
assert _outcome_reward_func(environment_reward=[0.25, 0.75]) == [0.25, 0.75]
|
| 128 |
+
|
| 129 |
+
def test_fresh_env_reward_is_zero_without_backend(self):
|
| 130 |
+
# The trainer discovers tool methods via `inspect.getmembers`, which evaluates properties. A fresh
|
| 131 |
+
# env (never `reset`) must expose its tools and return 0.0 from `reward` WITHOUT starting the
|
| 132 |
+
# Harbor backend or importing `harbor` (not installed in the trainer env).
|
| 133 |
+
import inspect
|
| 134 |
+
|
| 135 |
+
env = HarborBashEnv()
|
| 136 |
+
names = {n for n, _ in inspect.getmembers(env, predicate=inspect.ismethod)}
|
| 137 |
+
assert {"bash", "reset"} <= names
|
| 138 |
+
assert env.reward == 0.0
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_kto_trainer.py
ADDED
|
@@ -0,0 +1,774 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 multiprocess
|
| 16 |
+
import pytest
|
| 17 |
+
import torch
|
| 18 |
+
import transformers
|
| 19 |
+
from datasets import Dataset, load_dataset
|
| 20 |
+
from packaging.version import Version
|
| 21 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 22 |
+
|
| 23 |
+
from trl.experimental.kto import KTOConfig, KTOTrainer
|
| 24 |
+
from trl.experimental.kto.kto_trainer import (
|
| 25 |
+
DataCollatorForUnpairedPreference,
|
| 26 |
+
DataCollatorForVisionUnpairedPreference,
|
| 27 |
+
_get_kl_completion_ids,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
from ..testing_utils import TrlTestCase, require_liger_kernel, require_peft, require_vision
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@require_vision
|
| 34 |
+
class TestDataCollatorForVisionUnpairedPreference(TrlTestCase):
|
| 35 |
+
@pytest.mark.skipif(
|
| 36 |
+
Version(transformers.__version__) < Version("5.3.0"),
|
| 37 |
+
reason="mm_token_type_ids are returned by default since transformers-5.3.0 (see transformers#43972)",
|
| 38 |
+
)
|
| 39 |
+
def test_mm_token_type_ids_shape(self):
|
| 40 |
+
# Regression guard: when the processor returns mm_token_type_ids (Qwen2.5-VL after transformers#43972),
|
| 41 |
+
# the collator must produce a KL_completion_token_type_ids whose width matches KL_completion_input_ids,
|
| 42 |
+
# not the main completion's width (the two differ whenever their text lengths differ).
|
| 43 |
+
from PIL import Image
|
| 44 |
+
from transformers import AutoProcessor
|
| 45 |
+
|
| 46 |
+
processor = AutoProcessor.from_pretrained("trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration")
|
| 47 |
+
collator = DataCollatorForVisionUnpairedPreference(processor, calculate_kl=True)
|
| 48 |
+
image = Image.new("RGB", (16, 16))
|
| 49 |
+
examples = [
|
| 50 |
+
{
|
| 51 |
+
"images": [image],
|
| 52 |
+
"prompt": [{"role": "user", "content": "What is this?"}],
|
| 53 |
+
"completion": [{"role": "assistant", "content": "A red square."}],
|
| 54 |
+
"label": True,
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"images": [image],
|
| 58 |
+
"prompt": [{"role": "user", "content": "Describe it."}],
|
| 59 |
+
"completion": [{"role": "assistant", "content": "An image."}],
|
| 60 |
+
"label": False,
|
| 61 |
+
},
|
| 62 |
+
]
|
| 63 |
+
output = collator(examples)
|
| 64 |
+
|
| 65 |
+
assert "mm_token_type_ids" in output
|
| 66 |
+
assert output["mm_token_type_ids"].shape == output["completion_input_ids"].shape, (
|
| 67 |
+
f"mm_token_type_ids shape {output['mm_token_type_ids'].shape} != "
|
| 68 |
+
f"completion_input_ids shape {output['completion_input_ids'].shape}"
|
| 69 |
+
)
|
| 70 |
+
assert "KL_completion_mm_token_type_ids" in output
|
| 71 |
+
assert output["KL_completion_mm_token_type_ids"].shape == output["KL_completion_input_ids"].shape, (
|
| 72 |
+
f"KL_completion_mm_token_type_ids shape {output['KL_completion_mm_token_type_ids'].shape} != "
|
| 73 |
+
f"KL_completion_input_ids shape {output['KL_completion_input_ids'].shape}"
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
def test_output_keys(self):
|
| 77 |
+
from PIL import Image
|
| 78 |
+
from transformers import AutoProcessor
|
| 79 |
+
|
| 80 |
+
processor = AutoProcessor.from_pretrained("trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration")
|
| 81 |
+
image = Image.new("RGB", (16, 16))
|
| 82 |
+
|
| 83 |
+
def make_examples():
|
| 84 |
+
return [
|
| 85 |
+
{
|
| 86 |
+
"images": [image],
|
| 87 |
+
"prompt": [{"role": "user", "content": "What is this?"}],
|
| 88 |
+
"completion": [{"role": "assistant", "content": "A red square."}],
|
| 89 |
+
"label": True,
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"images": [image],
|
| 93 |
+
"prompt": [{"role": "user", "content": "Describe it."}],
|
| 94 |
+
"completion": [{"role": "assistant", "content": "An image."}],
|
| 95 |
+
"label": False,
|
| 96 |
+
},
|
| 97 |
+
]
|
| 98 |
+
|
| 99 |
+
# With KL
|
| 100 |
+
collator = DataCollatorForVisionUnpairedPreference(processor, calculate_kl=True)
|
| 101 |
+
output = collator(make_examples())
|
| 102 |
+
for key in ["completion_input_ids", "completion_attention_mask", "completion_mask", "pixel_values", "label"]:
|
| 103 |
+
assert key in output, f"Missing key: {key}"
|
| 104 |
+
for key in ["KL_completion_input_ids", "KL_completion_attention_mask", "KL_completion_mask"]:
|
| 105 |
+
assert key in output, f"Missing KL key: {key}"
|
| 106 |
+
|
| 107 |
+
# Without KL
|
| 108 |
+
collator_no_kl = DataCollatorForVisionUnpairedPreference(processor, calculate_kl=False)
|
| 109 |
+
output_no_kl = collator_no_kl(make_examples())
|
| 110 |
+
assert "completion_input_ids" in output_no_kl
|
| 111 |
+
assert "KL_completion_input_ids" not in output_no_kl
|
| 112 |
+
|
| 113 |
+
def test_kl_cycling(self):
|
| 114 |
+
# The KL completion for example i must be the completion from example i-1 (cycled by +1).
|
| 115 |
+
from PIL import Image
|
| 116 |
+
from transformers import AutoProcessor
|
| 117 |
+
|
| 118 |
+
processor = AutoProcessor.from_pretrained("trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration")
|
| 119 |
+
collator = DataCollatorForVisionUnpairedPreference(processor, calculate_kl=True)
|
| 120 |
+
image = Image.new("RGB", (16, 16))
|
| 121 |
+
# Two distinct completions so that cycling is detectable
|
| 122 |
+
examples = [
|
| 123 |
+
{
|
| 124 |
+
"images": [image],
|
| 125 |
+
"prompt": [{"role": "user", "content": "Q1"}],
|
| 126 |
+
"completion": [{"role": "assistant", "content": "Answer one."}],
|
| 127 |
+
"label": True,
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"images": [image],
|
| 131 |
+
"prompt": [{"role": "user", "content": "Q2"}],
|
| 132 |
+
"completion": [{"role": "assistant", "content": "Answer two."}],
|
| 133 |
+
"label": False,
|
| 134 |
+
},
|
| 135 |
+
]
|
| 136 |
+
output = collator(examples)
|
| 137 |
+
# KL completions are cycled: KL[0] = completion[-1], KL[1] = completion[0]
|
| 138 |
+
# They must differ from the matching main completion (unless both are identical strings, which they aren't here)
|
| 139 |
+
assert not torch.equal(output["completion_input_ids"][0], output["KL_completion_input_ids"][0])
|
| 140 |
+
assert not torch.equal(output["completion_input_ids"][1], output["KL_completion_input_ids"][1])
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class TestDataCollatorForUnpairedPreference(TrlTestCase):
|
| 144 |
+
def test_padding_and_masks(self):
|
| 145 |
+
collator = DataCollatorForUnpairedPreference(pad_token_id=0)
|
| 146 |
+
examples = [
|
| 147 |
+
{"prompt_ids": [1, 2, 3], "completion_ids": [4, 5], "KL_completion_ids": [6], "label": True},
|
| 148 |
+
{"prompt_ids": [7, 8], "completion_ids": [9, 10], "KL_completion_ids": [11, 12, 13], "label": False},
|
| 149 |
+
]
|
| 150 |
+
result = collator(examples)
|
| 151 |
+
|
| 152 |
+
expected_completion_input_ids = torch.tensor(
|
| 153 |
+
[
|
| 154 |
+
[1, 2, 3, 4, 5], # prompt + completion (example 1)
|
| 155 |
+
[7, 8, 9, 10, 0], # prompt + completion (example 2, padded)
|
| 156 |
+
]
|
| 157 |
+
)
|
| 158 |
+
expected_completion_attention_mask = torch.tensor(
|
| 159 |
+
[
|
| 160 |
+
[1, 1, 1, 1, 1],
|
| 161 |
+
[1, 1, 1, 1, 0],
|
| 162 |
+
]
|
| 163 |
+
)
|
| 164 |
+
expected_completion_mask = torch.tensor(
|
| 165 |
+
[
|
| 166 |
+
[0, 0, 0, 1, 1], # completion (example 1)
|
| 167 |
+
[0, 0, 1, 1, 0], # completion (example 2, padded)
|
| 168 |
+
]
|
| 169 |
+
)
|
| 170 |
+
expected_kl_completion_input_ids = torch.tensor(
|
| 171 |
+
[
|
| 172 |
+
[1, 2, 3, 6, 0], # prompt + KL completion (example 1, padded)
|
| 173 |
+
[7, 8, 11, 12, 13], # prompt + KL completion (example 2)
|
| 174 |
+
]
|
| 175 |
+
)
|
| 176 |
+
expected_kl_completion_attention_mask = torch.tensor(
|
| 177 |
+
[
|
| 178 |
+
[1, 1, 1, 1, 0],
|
| 179 |
+
[1, 1, 1, 1, 1],
|
| 180 |
+
]
|
| 181 |
+
)
|
| 182 |
+
expected_kl_completion_mask = torch.tensor(
|
| 183 |
+
[
|
| 184 |
+
[0, 0, 0, 1, 0], # KL completion (example 1, padded)
|
| 185 |
+
[0, 0, 1, 1, 1], # KL completion (example 2)
|
| 186 |
+
]
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
assert set(result.keys()) == {
|
| 190 |
+
"completion_input_ids",
|
| 191 |
+
"completion_attention_mask",
|
| 192 |
+
"completion_mask",
|
| 193 |
+
"KL_completion_input_ids",
|
| 194 |
+
"KL_completion_attention_mask",
|
| 195 |
+
"KL_completion_mask",
|
| 196 |
+
"label",
|
| 197 |
+
}
|
| 198 |
+
torch.testing.assert_close(result["completion_input_ids"], expected_completion_input_ids)
|
| 199 |
+
torch.testing.assert_close(result["completion_attention_mask"], expected_completion_attention_mask)
|
| 200 |
+
torch.testing.assert_close(result["completion_mask"], expected_completion_mask)
|
| 201 |
+
torch.testing.assert_close(result["KL_completion_input_ids"], expected_kl_completion_input_ids)
|
| 202 |
+
torch.testing.assert_close(result["KL_completion_attention_mask"], expected_kl_completion_attention_mask)
|
| 203 |
+
torch.testing.assert_close(result["KL_completion_mask"], expected_kl_completion_mask)
|
| 204 |
+
assert result["label"] == [True, False]
|
| 205 |
+
|
| 206 |
+
def test_optional_reference_logps(self):
|
| 207 |
+
collator = DataCollatorForUnpairedPreference(pad_token_id=0)
|
| 208 |
+
examples = [
|
| 209 |
+
{
|
| 210 |
+
"prompt_ids": [1, 2],
|
| 211 |
+
"completion_ids": [3],
|
| 212 |
+
"KL_completion_ids": [4],
|
| 213 |
+
"ref_logps": 0.1,
|
| 214 |
+
"ref_KL_logps": 0.2,
|
| 215 |
+
"label": True,
|
| 216 |
+
},
|
| 217 |
+
{
|
| 218 |
+
"prompt_ids": [5],
|
| 219 |
+
"completion_ids": [6, 7],
|
| 220 |
+
"KL_completion_ids": [8, 9],
|
| 221 |
+
"ref_logps": 0.3,
|
| 222 |
+
"ref_KL_logps": 0.4,
|
| 223 |
+
"label": False,
|
| 224 |
+
},
|
| 225 |
+
]
|
| 226 |
+
result = collator(examples)
|
| 227 |
+
|
| 228 |
+
expected_ref_logps = torch.tensor([0.1, 0.3])
|
| 229 |
+
expected_ref_kl_logps = torch.tensor([0.2, 0.4])
|
| 230 |
+
|
| 231 |
+
assert set(result.keys()) == {
|
| 232 |
+
"completion_input_ids",
|
| 233 |
+
"completion_attention_mask",
|
| 234 |
+
"completion_mask",
|
| 235 |
+
"KL_completion_input_ids",
|
| 236 |
+
"KL_completion_attention_mask",
|
| 237 |
+
"KL_completion_mask",
|
| 238 |
+
"ref_logps",
|
| 239 |
+
"ref_KL_logps",
|
| 240 |
+
"label",
|
| 241 |
+
}
|
| 242 |
+
torch.testing.assert_close(result["ref_logps"], expected_ref_logps)
|
| 243 |
+
torch.testing.assert_close(result["ref_KL_logps"], expected_ref_kl_logps)
|
| 244 |
+
|
| 245 |
+
def test_with_pad_to_multiple_of(self):
|
| 246 |
+
collator = DataCollatorForUnpairedPreference(pad_token_id=0, pad_to_multiple_of=5)
|
| 247 |
+
examples = [
|
| 248 |
+
{"prompt_ids": [1], "completion_ids": [2], "KL_completion_ids": [3], "label": True},
|
| 249 |
+
{"prompt_ids": [4, 5], "completion_ids": [6, 7], "KL_completion_ids": [8, 9], "label": False},
|
| 250 |
+
]
|
| 251 |
+
result = collator(examples)
|
| 252 |
+
|
| 253 |
+
expected_completion_input_ids = torch.tensor(
|
| 254 |
+
[
|
| 255 |
+
[1, 2, 0, 0, 0], # prompt + completion (example 1, padded to multiple of 5)
|
| 256 |
+
[4, 5, 6, 7, 0], # prompt + completion (example 2)
|
| 257 |
+
]
|
| 258 |
+
)
|
| 259 |
+
expected_kl_completion_input_ids = torch.tensor(
|
| 260 |
+
[
|
| 261 |
+
[1, 3, 0, 0, 0], # prompt + KL completion (example 1, padded to multiple of 5)
|
| 262 |
+
[4, 5, 8, 9, 0], # prompt + KL completion (example 2)
|
| 263 |
+
]
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
assert set(result.keys()) == {
|
| 267 |
+
"completion_input_ids",
|
| 268 |
+
"completion_attention_mask",
|
| 269 |
+
"completion_mask",
|
| 270 |
+
"KL_completion_input_ids",
|
| 271 |
+
"KL_completion_attention_mask",
|
| 272 |
+
"KL_completion_mask",
|
| 273 |
+
"label",
|
| 274 |
+
}
|
| 275 |
+
torch.testing.assert_close(result["completion_input_ids"], expected_completion_input_ids)
|
| 276 |
+
torch.testing.assert_close(result["KL_completion_input_ids"], expected_kl_completion_input_ids)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class TestKTOTrainer(TrlTestCase):
|
| 280 |
+
def setup_method(self):
|
| 281 |
+
self.model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 282 |
+
self.model = AutoModelForCausalLM.from_pretrained(self.model_id, dtype="float32")
|
| 283 |
+
self.ref_model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 284 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
|
| 285 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 286 |
+
|
| 287 |
+
@pytest.mark.parametrize(
|
| 288 |
+
"config_name, loss_type, pre_compute, eval_dataset",
|
| 289 |
+
[
|
| 290 |
+
("standard_preference", "kto", True, True),
|
| 291 |
+
("standard_unpaired_preference", "kto", False, True),
|
| 292 |
+
("conversational_implicit_prompt_preference", "apo_zero_unpaired", True, True),
|
| 293 |
+
("standard_unpaired_preference", "apo_zero_unpaired", False, True),
|
| 294 |
+
],
|
| 295 |
+
)
|
| 296 |
+
def test_kto_trainer(self, config_name, loss_type, pre_compute, eval_dataset):
|
| 297 |
+
training_args = KTOConfig(
|
| 298 |
+
output_dir=self.tmp_dir,
|
| 299 |
+
per_device_train_batch_size=2,
|
| 300 |
+
max_steps=3,
|
| 301 |
+
gradient_accumulation_steps=1,
|
| 302 |
+
learning_rate=9e-1,
|
| 303 |
+
eval_strategy="steps" if eval_dataset else "no",
|
| 304 |
+
beta=0.1,
|
| 305 |
+
precompute_ref_log_probs=pre_compute,
|
| 306 |
+
loss_type=loss_type,
|
| 307 |
+
report_to="none",
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
dataset = load_dataset("trl-internal-testing/zen", config_name)
|
| 311 |
+
|
| 312 |
+
trainer = KTOTrainer(
|
| 313 |
+
model=self.model,
|
| 314 |
+
ref_model=self.ref_model,
|
| 315 |
+
args=training_args,
|
| 316 |
+
processing_class=self.tokenizer,
|
| 317 |
+
train_dataset=dataset["train"],
|
| 318 |
+
eval_dataset=dataset["test"] if eval_dataset else None,
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 322 |
+
|
| 323 |
+
trainer.train()
|
| 324 |
+
|
| 325 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 326 |
+
|
| 327 |
+
# Check that the params have changed
|
| 328 |
+
for n, param in previous_trainable_params.items():
|
| 329 |
+
new_param = trainer.model.get_parameter(n)
|
| 330 |
+
if param.sum() != 0: # ignore 0 biases
|
| 331 |
+
assert not torch.equal(param, new_param)
|
| 332 |
+
|
| 333 |
+
def test_trust_remote_code(self):
|
| 334 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference", split="train")
|
| 335 |
+
model_id = "trl-internal-testing/tiny-RemoteForCausalLM"
|
| 336 |
+
|
| 337 |
+
with pytest.raises(ValueError, match="custom code"):
|
| 338 |
+
KTOTrainer(
|
| 339 |
+
model=model_id,
|
| 340 |
+
args=KTOConfig(output_dir=self.tmp_dir, report_to="none"),
|
| 341 |
+
train_dataset=dataset,
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
trainer = KTOTrainer(
|
| 345 |
+
model=model_id,
|
| 346 |
+
args=KTOConfig(output_dir=self.tmp_dir, report_to="none", trust_remote_code=True),
|
| 347 |
+
train_dataset=dataset,
|
| 348 |
+
)
|
| 349 |
+
assert type(trainer.model).__name__ == "RemoteForCausalLM"
|
| 350 |
+
|
| 351 |
+
def test_kto_trainer_with_ref_model_is_model(self):
|
| 352 |
+
training_args = KTOConfig(
|
| 353 |
+
output_dir=self.tmp_dir,
|
| 354 |
+
per_device_train_batch_size=2,
|
| 355 |
+
max_steps=3,
|
| 356 |
+
report_to="none",
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference", split="train")
|
| 360 |
+
|
| 361 |
+
with pytest.raises(ValueError):
|
| 362 |
+
KTOTrainer(
|
| 363 |
+
model=self.model,
|
| 364 |
+
ref_model=self.model, # ref_model can't be the same as model
|
| 365 |
+
args=training_args,
|
| 366 |
+
processing_class=self.tokenizer,
|
| 367 |
+
train_dataset=dataset,
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
def test_tokenize_and_process_tokens(self):
|
| 371 |
+
# Pytest/CI often starts background threads before tests run. Under Python 3.12+,
|
| 372 |
+
# using "fork" in a multi-threaded process emits a DeprecationWarning and may deadlock.
|
| 373 |
+
# Force "spawn" to keep this multiprocessing test safe while still exercising `num_proc=2`.
|
| 374 |
+
multiprocess.set_start_method("spawn", force=True)
|
| 375 |
+
|
| 376 |
+
training_args = KTOConfig(
|
| 377 |
+
output_dir=self.tmp_dir,
|
| 378 |
+
per_device_train_batch_size=2,
|
| 379 |
+
max_steps=3,
|
| 380 |
+
gradient_accumulation_steps=1,
|
| 381 |
+
learning_rate=9e-1,
|
| 382 |
+
eval_strategy="steps",
|
| 383 |
+
beta=0.1,
|
| 384 |
+
report_to="none",
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference")
|
| 388 |
+
train_dataset = dataset["train"]
|
| 389 |
+
|
| 390 |
+
trainer = KTOTrainer(
|
| 391 |
+
model=self.model,
|
| 392 |
+
ref_model=self.ref_model,
|
| 393 |
+
args=training_args,
|
| 394 |
+
processing_class=self.tokenizer,
|
| 395 |
+
train_dataset=train_dataset,
|
| 396 |
+
eval_dataset=dataset["test"],
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
# Verify the tokenization step: dataset stores raw token IDs (aligned with DPO style).
|
| 400 |
+
# prompt_ids must start with the tokenized prompt text.
|
| 401 |
+
prompt_ids = self.tokenizer(train_dataset["prompt"][0])["input_ids"]
|
| 402 |
+
assert trainer.train_dataset[0]["prompt_ids"][: len(prompt_ids)] == prompt_ids
|
| 403 |
+
# completion_ids are the raw answer tokens (no prompt prefix, no BOS/EOS added yet).
|
| 404 |
+
assert len(trainer.train_dataset[0]["completion_ids"]) > 0
|
| 405 |
+
|
| 406 |
+
# Verify the collator output (assembly, BOS/EOS insertion, labels).
|
| 407 |
+
example = trainer.train_dataset[0]
|
| 408 |
+
batch = trainer.data_collator([example])
|
| 409 |
+
# completion_input_ids ends with EOS
|
| 410 |
+
assert batch["completion_input_ids"][0, -1].item() == self.tokenizer.eos_token_id
|
| 411 |
+
# completion_mask: prompt tokens are 0, completion tokens are 1; at least the prompt is masked
|
| 412 |
+
assert "completion_mask" in batch
|
| 413 |
+
completion_mask = batch["completion_mask"][0].tolist()
|
| 414 |
+
assert 0 in completion_mask and 1 in completion_mask
|
| 415 |
+
first_completion = next(i for i, m in enumerate(completion_mask) if m == 1)
|
| 416 |
+
assert first_completion > 0 # at least the prompt is masked
|
| 417 |
+
assert all(m == 0 for m in completion_mask[:first_completion])
|
| 418 |
+
|
| 419 |
+
# Test corruption of (prompt, completion) pairs for KL dataset.
|
| 420 |
+
# _get_kl_completion_ids shifts completion_ids by one within each batch; prompt_ids are unchanged.
|
| 421 |
+
synthetic = Dataset.from_dict(
|
| 422 |
+
{
|
| 423 |
+
"prompt_ids": [[1, 2], [3, 4], [5, 6]],
|
| 424 |
+
"completion_ids": [[10, 11], [20, 21], [30, 31]],
|
| 425 |
+
"label": [True, False, True],
|
| 426 |
+
}
|
| 427 |
+
)
|
| 428 |
+
for batch_size in [2, 3]:
|
| 429 |
+
rotated = synthetic.map(_get_kl_completion_ids, batched=True, batch_size=batch_size)
|
| 430 |
+
|
| 431 |
+
# Verify that completion_ids have been rotated (differ from original). When the dataset length
|
| 432 |
+
# modulo batch_size equals 1, the last batch is unaltered: exclude it from the check.
|
| 433 |
+
for i in range(len(rotated) - 1):
|
| 434 |
+
assert synthetic["prompt_ids"][i] == rotated["prompt_ids"][i]
|
| 435 |
+
assert synthetic["completion_ids"][i] != rotated["completion_ids"][i]
|
| 436 |
+
|
| 437 |
+
def test_kto_trainer_without_providing_ref_model(self):
|
| 438 |
+
training_args = KTOConfig(
|
| 439 |
+
output_dir=self.tmp_dir,
|
| 440 |
+
per_device_train_batch_size=2,
|
| 441 |
+
max_steps=3,
|
| 442 |
+
gradient_accumulation_steps=4,
|
| 443 |
+
learning_rate=9e-1,
|
| 444 |
+
eval_strategy="steps",
|
| 445 |
+
beta=0.1,
|
| 446 |
+
report_to="none",
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference")
|
| 450 |
+
|
| 451 |
+
trainer = KTOTrainer(
|
| 452 |
+
model=self.model,
|
| 453 |
+
ref_model=None,
|
| 454 |
+
args=training_args,
|
| 455 |
+
processing_class=self.tokenizer,
|
| 456 |
+
train_dataset=dataset["train"],
|
| 457 |
+
eval_dataset=dataset["test"],
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 461 |
+
|
| 462 |
+
trainer.train()
|
| 463 |
+
|
| 464 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 465 |
+
|
| 466 |
+
# Check that the params have changed
|
| 467 |
+
for n, param in previous_trainable_params.items():
|
| 468 |
+
new_param = trainer.model.get_parameter(n)
|
| 469 |
+
if param.sum() != 0: # ignore 0 biases
|
| 470 |
+
assert not torch.equal(param, new_param)
|
| 471 |
+
|
| 472 |
+
@require_peft
|
| 473 |
+
def test_kto_trainer_without_providing_ref_model_with_lora(self):
|
| 474 |
+
from peft import LoraConfig
|
| 475 |
+
|
| 476 |
+
lora_config = LoraConfig(
|
| 477 |
+
r=16,
|
| 478 |
+
lora_alpha=32,
|
| 479 |
+
lora_dropout=0.05,
|
| 480 |
+
bias="none",
|
| 481 |
+
task_type="CAUSAL_LM",
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
training_args = KTOConfig(
|
| 485 |
+
output_dir=self.tmp_dir,
|
| 486 |
+
per_device_train_batch_size=2,
|
| 487 |
+
max_steps=3,
|
| 488 |
+
gradient_accumulation_steps=4,
|
| 489 |
+
learning_rate=9e-1,
|
| 490 |
+
eval_strategy="steps",
|
| 491 |
+
beta=0.1,
|
| 492 |
+
report_to="none",
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference")
|
| 496 |
+
|
| 497 |
+
trainer = KTOTrainer(
|
| 498 |
+
model=self.model,
|
| 499 |
+
ref_model=None,
|
| 500 |
+
args=training_args,
|
| 501 |
+
processing_class=self.tokenizer,
|
| 502 |
+
train_dataset=dataset["train"],
|
| 503 |
+
eval_dataset=dataset["test"],
|
| 504 |
+
peft_config=lora_config,
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 508 |
+
|
| 509 |
+
trainer.train()
|
| 510 |
+
|
| 511 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 512 |
+
|
| 513 |
+
# Check that the params have changed
|
| 514 |
+
for n, param in previous_trainable_params.items():
|
| 515 |
+
if "lora" in n:
|
| 516 |
+
new_param = trainer.model.get_parameter(n)
|
| 517 |
+
if param.sum() != 0: # ignore 0 biases
|
| 518 |
+
assert not torch.equal(param, new_param)
|
| 519 |
+
|
| 520 |
+
@require_liger_kernel
|
| 521 |
+
def test_kto_trainer_with_liger(self):
|
| 522 |
+
"""Test KTO trainer with Liger kernel enabled."""
|
| 523 |
+
training_args = KTOConfig(
|
| 524 |
+
output_dir=self.tmp_dir,
|
| 525 |
+
report_to="none",
|
| 526 |
+
use_liger_kernel=True, # Enable Liger kernel
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference", split="train")
|
| 530 |
+
|
| 531 |
+
trainer = KTOTrainer(
|
| 532 |
+
model=self.model,
|
| 533 |
+
args=training_args,
|
| 534 |
+
processing_class=self.tokenizer,
|
| 535 |
+
train_dataset=dataset,
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 539 |
+
|
| 540 |
+
trainer.train()
|
| 541 |
+
|
| 542 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 543 |
+
|
| 544 |
+
# check the params have changed
|
| 545 |
+
for n, param in previous_trainable_params.items():
|
| 546 |
+
new_param = trainer.model.get_parameter(n)
|
| 547 |
+
# check the params have changed - ignore 0 biases
|
| 548 |
+
if param.sum() != 0:
|
| 549 |
+
assert not torch.equal(param, new_param)
|
| 550 |
+
|
| 551 |
+
def test_compute_metrics(self):
|
| 552 |
+
model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32")
|
| 553 |
+
ref_model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
|
| 554 |
+
tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
|
| 555 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 556 |
+
|
| 557 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference")
|
| 558 |
+
|
| 559 |
+
def dummy_compute_metrics(*args, **kwargs):
|
| 560 |
+
return {"test": 0.0}
|
| 561 |
+
|
| 562 |
+
training_args = KTOConfig(
|
| 563 |
+
output_dir=self.tmp_dir,
|
| 564 |
+
per_device_train_batch_size=2,
|
| 565 |
+
do_eval=True,
|
| 566 |
+
eval_strategy="steps",
|
| 567 |
+
eval_steps=1,
|
| 568 |
+
per_device_eval_batch_size=2,
|
| 569 |
+
report_to="none",
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
trainer = KTOTrainer(
|
| 573 |
+
model=model,
|
| 574 |
+
ref_model=ref_model,
|
| 575 |
+
args=training_args,
|
| 576 |
+
processing_class=tokenizer,
|
| 577 |
+
train_dataset=dataset["train"],
|
| 578 |
+
eval_dataset=dataset["test"],
|
| 579 |
+
compute_metrics=dummy_compute_metrics,
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
trainer.train()
|
| 583 |
+
|
| 584 |
+
assert trainer.state.log_history[-2]["eval_test"] == 0.0
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
@require_vision
|
| 588 |
+
class TestKTOTrainerVLM(TrlTestCase):
|
| 589 |
+
@pytest.mark.parametrize(
|
| 590 |
+
"model_id",
|
| 591 |
+
[
|
| 592 |
+
"trl-internal-testing/tiny-Gemma3ForConditionalGeneration",
|
| 593 |
+
pytest.param(
|
| 594 |
+
"trl-internal-testing/tiny-Gemma4ForConditionalGeneration",
|
| 595 |
+
marks=pytest.mark.skipif(
|
| 596 |
+
Version(transformers.__version__) < Version("5.5.0"),
|
| 597 |
+
reason="Gemma4 models were introduced in transformers-5.5.0",
|
| 598 |
+
),
|
| 599 |
+
),
|
| 600 |
+
"trl-internal-testing/tiny-LlavaForConditionalGeneration",
|
| 601 |
+
"trl-internal-testing/tiny-LlavaNextForConditionalGeneration",
|
| 602 |
+
"trl-internal-testing/tiny-Qwen2VLForConditionalGeneration",
|
| 603 |
+
"trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 604 |
+
# "trl-internal-testing/tiny-SmolVLMForConditionalGeneration", seems not to support bf16 properly
|
| 605 |
+
pytest.param(
|
| 606 |
+
"trl-internal-testing/tiny-Qwen3VLForConditionalGeneration",
|
| 607 |
+
marks=[
|
| 608 |
+
pytest.mark.skipif(
|
| 609 |
+
Version(transformers.__version__) < Version("4.57.0"),
|
| 610 |
+
reason="Qwen3-VL series were introduced in transformers-4.57.0",
|
| 611 |
+
),
|
| 612 |
+
],
|
| 613 |
+
),
|
| 614 |
+
pytest.param(
|
| 615 |
+
"trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink",
|
| 616 |
+
marks=pytest.mark.skipif(
|
| 617 |
+
Version(transformers.__version__) < Version("5.2.0"),
|
| 618 |
+
reason="Qwen3.5 models were introduced in transformers-5.2.0",
|
| 619 |
+
),
|
| 620 |
+
),
|
| 621 |
+
pytest.param(
|
| 622 |
+
"trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6",
|
| 623 |
+
marks=pytest.mark.skipif(
|
| 624 |
+
Version(transformers.__version__) < Version("5.2.0"),
|
| 625 |
+
reason="Qwen3.5 models were introduced in transformers-5.2.0",
|
| 626 |
+
),
|
| 627 |
+
),
|
| 628 |
+
],
|
| 629 |
+
)
|
| 630 |
+
def test_train_vlm(self, model_id):
|
| 631 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_unpaired_preference", split="train")
|
| 632 |
+
training_args = KTOConfig(
|
| 633 |
+
output_dir=self.tmp_dir,
|
| 634 |
+
max_length=None, # for VLMs, truncating can remove image tokens, leading to errors
|
| 635 |
+
per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 636 |
+
report_to="none",
|
| 637 |
+
)
|
| 638 |
+
trainer = KTOTrainer(model=model_id, args=training_args, train_dataset=dataset)
|
| 639 |
+
|
| 640 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 641 |
+
|
| 642 |
+
trainer.train()
|
| 643 |
+
|
| 644 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 645 |
+
|
| 646 |
+
# Check that the params have changed
|
| 647 |
+
for n, param in previous_trainable_params.items():
|
| 648 |
+
new_param = trainer.model.get_parameter(n)
|
| 649 |
+
# LLaVA & LLaVA-Next: vision_feature_layer=-2 leaves the last encoder layer (layers.1) and
|
| 650 |
+
# post_layernorm (pooler-only path) without gradient by design. Assert they stay frozen — if they
|
| 651 |
+
# ever start training, the feature-selection plumbing has likely regressed.
|
| 652 |
+
if model_id in (
|
| 653 |
+
"trl-internal-testing/tiny-LlavaForConditionalGeneration",
|
| 654 |
+
"trl-internal-testing/tiny-LlavaNextForConditionalGeneration",
|
| 655 |
+
) and ("encoder.layers.1" in n or "post_layernorm" in n):
|
| 656 |
+
assert torch.equal(param, new_param), f"Param {n} expected frozen by LLaVA design, but changed"
|
| 657 |
+
else:
|
| 658 |
+
assert not torch.equal(param, new_param), f"Param {n} is not updated"
|
| 659 |
+
|
| 660 |
+
def test_train_vlm_apo_zero_unpaired(self):
|
| 661 |
+
# apo_zero_unpaired does not need the KL term: verify that calculate_kl=False path works end-to-end.
|
| 662 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_unpaired_preference", split="train")
|
| 663 |
+
training_args = KTOConfig(
|
| 664 |
+
output_dir=self.tmp_dir,
|
| 665 |
+
max_length=None, # for VLMs, truncating can remove image tokens, leading to errors
|
| 666 |
+
per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 667 |
+
loss_type="apo_zero_unpaired",
|
| 668 |
+
report_to="none",
|
| 669 |
+
)
|
| 670 |
+
trainer = KTOTrainer(
|
| 671 |
+
model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 672 |
+
args=training_args,
|
| 673 |
+
train_dataset=dataset,
|
| 674 |
+
)
|
| 675 |
+
trainer.train()
|
| 676 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 677 |
+
|
| 678 |
+
@pytest.mark.parametrize(
|
| 679 |
+
"model_id",
|
| 680 |
+
[
|
| 681 |
+
"trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 682 |
+
],
|
| 683 |
+
)
|
| 684 |
+
@pytest.mark.parametrize(
|
| 685 |
+
"dataset_config",
|
| 686 |
+
["conversational_unpaired_preference", "standard_unpaired_preference"],
|
| 687 |
+
)
|
| 688 |
+
def test_train_vlm_text_only_data(self, model_id, dataset_config):
|
| 689 |
+
dataset = load_dataset("trl-internal-testing/zen", dataset_config, split="train")
|
| 690 |
+
training_args = KTOConfig(output_dir=self.tmp_dir, report_to="none")
|
| 691 |
+
trainer = KTOTrainer(
|
| 692 |
+
model=model_id,
|
| 693 |
+
args=training_args,
|
| 694 |
+
train_dataset=dataset,
|
| 695 |
+
)
|
| 696 |
+
|
| 697 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 698 |
+
|
| 699 |
+
trainer.train()
|
| 700 |
+
|
| 701 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 702 |
+
|
| 703 |
+
# Check that the params have changed
|
| 704 |
+
for n, param in previous_trainable_params.items():
|
| 705 |
+
new_param = trainer.model.get_parameter(n)
|
| 706 |
+
if n.startswith("model.visual"):
|
| 707 |
+
torch.testing.assert_close(param, new_param, rtol=1e-12, atol=1e-12, msg=f"Param {n} is updated")
|
| 708 |
+
else:
|
| 709 |
+
assert not torch.equal(param, new_param), f"Param {n} is not updated"
|
| 710 |
+
|
| 711 |
+
def test_train_vlm_with_max_length(self):
|
| 712 |
+
# Regression test: mm_token_type_ids (and KL_completion_mm_token_type_ids) must be truncated alongside
|
| 713 |
+
# input_ids when max_length is set, otherwise a shape mismatch crashes the model forward pass.
|
| 714 |
+
# max_length=37 truncates 1 completion token (total_len=38) while keeping all image tokens (prompt_len=34) safe.
|
| 715 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_unpaired_preference", split="train")
|
| 716 |
+
training_args = KTOConfig(
|
| 717 |
+
output_dir=self.tmp_dir,
|
| 718 |
+
max_length=37, # total_len=38, prompt_len=34 — truncates completion, not image tokens
|
| 719 |
+
per_device_train_batch_size=2,
|
| 720 |
+
report_to="none",
|
| 721 |
+
)
|
| 722 |
+
trainer = KTOTrainer(
|
| 723 |
+
model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 724 |
+
args=training_args,
|
| 725 |
+
train_dataset=dataset,
|
| 726 |
+
)
|
| 727 |
+
trainer.train()
|
| 728 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 729 |
+
|
| 730 |
+
def test_vision_dataset_with_text_model_raises(self):
|
| 731 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_unpaired_preference", split="train")
|
| 732 |
+
training_args = KTOConfig(output_dir=self.tmp_dir, report_to="none")
|
| 733 |
+
with pytest.raises(ValueError, match="vision-related.*vision-language model"):
|
| 734 |
+
KTOTrainer(
|
| 735 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 736 |
+
args=training_args,
|
| 737 |
+
train_dataset=dataset,
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
def test_precompute_ref_log_probs_raises_for_vision(self):
|
| 741 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_unpaired_preference", split="train")
|
| 742 |
+
training_args = KTOConfig(output_dir=self.tmp_dir, report_to="none", precompute_ref_log_probs=True)
|
| 743 |
+
with pytest.raises(ValueError, match="precompute_ref_log_probs.*not supported for vision datasets"):
|
| 744 |
+
KTOTrainer(
|
| 745 |
+
model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 746 |
+
args=training_args,
|
| 747 |
+
train_dataset=dataset,
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
@require_liger_kernel
|
| 751 |
+
def test_train_vlm_liger(self):
|
| 752 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_unpaired_preference", split="train")
|
| 753 |
+
training_args = KTOConfig(
|
| 754 |
+
output_dir=self.tmp_dir,
|
| 755 |
+
max_length=None, # for VLMs, truncating can remove image tokens, leading to errors
|
| 756 |
+
per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 757 |
+
use_liger_kernel=True,
|
| 758 |
+
report_to="none",
|
| 759 |
+
)
|
| 760 |
+
trainer = KTOTrainer(
|
| 761 |
+
model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 762 |
+
args=training_args,
|
| 763 |
+
train_dataset=dataset,
|
| 764 |
+
)
|
| 765 |
+
|
| 766 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 767 |
+
|
| 768 |
+
trainer.train()
|
| 769 |
+
|
| 770 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 771 |
+
|
| 772 |
+
for n, param in previous_trainable_params.items():
|
| 773 |
+
new_param = trainer.model.get_parameter(n)
|
| 774 |
+
assert not torch.equal(param, new_param), f"Param {n} is not updated"
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_merge_model_callback.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import os
|
| 17 |
+
|
| 18 |
+
from datasets import load_dataset
|
| 19 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 20 |
+
from transformers.trainer_utils import get_last_checkpoint
|
| 21 |
+
|
| 22 |
+
from trl import DPOConfig, DPOTrainer
|
| 23 |
+
from trl.experimental.merge_model_callback import MergeConfig, MergeModelCallback
|
| 24 |
+
|
| 25 |
+
from ..testing_utils import TrlTestCase, require_mergekit
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@require_mergekit
|
| 29 |
+
class TestMergeModelCallback(TrlTestCase):
|
| 30 |
+
def setup_method(self):
|
| 31 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 32 |
+
"trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32"
|
| 33 |
+
)
|
| 34 |
+
self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
|
| 35 |
+
self.dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 36 |
+
|
| 37 |
+
def test_callback(self):
|
| 38 |
+
training_args = DPOConfig(
|
| 39 |
+
output_dir=self.tmp_dir,
|
| 40 |
+
num_train_epochs=1,
|
| 41 |
+
report_to="none",
|
| 42 |
+
save_strategy="steps",
|
| 43 |
+
save_steps=1,
|
| 44 |
+
)
|
| 45 |
+
config = MergeConfig()
|
| 46 |
+
merge_callback = MergeModelCallback(config)
|
| 47 |
+
trainer = DPOTrainer(
|
| 48 |
+
model=self.model,
|
| 49 |
+
args=training_args,
|
| 50 |
+
train_dataset=self.dataset,
|
| 51 |
+
processing_class=self.tokenizer,
|
| 52 |
+
callbacks=[merge_callback],
|
| 53 |
+
)
|
| 54 |
+
trainer.train()
|
| 55 |
+
last_checkpoint = get_last_checkpoint(self.tmp_dir)
|
| 56 |
+
merged_path = os.path.join(last_checkpoint, "merged")
|
| 57 |
+
assert os.path.isdir(merged_path), "Merged folder does not exist in the last checkpoint."
|
| 58 |
+
|
| 59 |
+
def test_every_checkpoint(self):
|
| 60 |
+
training_args = DPOConfig(
|
| 61 |
+
output_dir=self.tmp_dir,
|
| 62 |
+
num_train_epochs=1,
|
| 63 |
+
report_to="none",
|
| 64 |
+
save_strategy="steps",
|
| 65 |
+
save_steps=1,
|
| 66 |
+
)
|
| 67 |
+
config = MergeConfig()
|
| 68 |
+
merge_callback = MergeModelCallback(config, merge_at_every_checkpoint=True)
|
| 69 |
+
trainer = DPOTrainer(
|
| 70 |
+
model=self.model,
|
| 71 |
+
args=training_args,
|
| 72 |
+
train_dataset=self.dataset,
|
| 73 |
+
processing_class=self.tokenizer,
|
| 74 |
+
callbacks=[merge_callback],
|
| 75 |
+
)
|
| 76 |
+
trainer.train()
|
| 77 |
+
|
| 78 |
+
checkpoints = sorted(
|
| 79 |
+
[os.path.join(self.tmp_dir, cp) for cp in os.listdir(self.tmp_dir) if cp.startswith("checkpoint-")]
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
for checkpoint in checkpoints:
|
| 83 |
+
merged_path = os.path.join(checkpoint, "merged")
|
| 84 |
+
assert os.path.isdir(merged_path), f"Merged folder does not exist in checkpoint {checkpoint}."
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_minillm_trainer.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from datasets import load_dataset
|
| 18 |
+
|
| 19 |
+
from trl.experimental.minillm import MiniLLMConfig, MiniLLMTrainer
|
| 20 |
+
|
| 21 |
+
from ..testing_utils import TrlTestCase
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.mark.low_priority
|
| 25 |
+
class TestMiniLLMTrainer(TrlTestCase):
|
| 26 |
+
def test_train(self):
|
| 27 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 28 |
+
|
| 29 |
+
training_args = MiniLLMConfig(
|
| 30 |
+
output_dir=self.tmp_dir,
|
| 31 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 32 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 33 |
+
max_completion_length=32, # reduce the completion length to reduce memory usage
|
| 34 |
+
report_to="none",
|
| 35 |
+
)
|
| 36 |
+
trainer = MiniLLMTrainer(
|
| 37 |
+
model="trl-internal-testing/small-Qwen3ForCausalLM",
|
| 38 |
+
teacher_model="trl-internal-testing/tiny-Qwen3ForCausalLM",
|
| 39 |
+
args=training_args,
|
| 40 |
+
train_dataset=dataset,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 44 |
+
|
| 45 |
+
trainer.train()
|
| 46 |
+
|
| 47 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 48 |
+
|
| 49 |
+
# Check that the params have changed
|
| 50 |
+
for n, param in previous_trainable_params.items():
|
| 51 |
+
new_param = trainer.model.get_parameter(n)
|
| 52 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_modeling_value_head.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import torch
|
| 17 |
+
|
| 18 |
+
from trl.experimental.ppo import AutoModelForCausalLMWithValueHead
|
| 19 |
+
from trl.experimental.utils import create_reference_model
|
| 20 |
+
|
| 21 |
+
from ..testing_utils import TrlTestCase
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class TestReferenceModel(TrlTestCase):
|
| 25 |
+
def setup_method(self):
|
| 26 |
+
self.model = AutoModelForCausalLMWithValueHead.from_pretrained("trl-internal-testing/tiny-GPT2LMHeadModel")
|
| 27 |
+
self.test_input = torch.tensor([[0, 1, 2, 3]])
|
| 28 |
+
self.optimizer = torch.optim.AdamW(self.model.parameters(), lr=1)
|
| 29 |
+
self.layer_format = "pretrained_model.transformer.h.{layer}.attn.c_attn.weight"
|
| 30 |
+
|
| 31 |
+
def test_independent_reference(self):
|
| 32 |
+
layer_0 = self.layer_format.format(layer=0)
|
| 33 |
+
layer_1 = self.layer_format.format(layer=1)
|
| 34 |
+
|
| 35 |
+
ref_model = create_reference_model(self.model)
|
| 36 |
+
|
| 37 |
+
first_layer_before = self.model.get_parameter(layer_0).data.clone()
|
| 38 |
+
last_layer_before = self.model.get_parameter(layer_1).data.clone() # the model only has 2 layers
|
| 39 |
+
|
| 40 |
+
first_ref_layer_before = ref_model.get_parameter(layer_0).data.clone()
|
| 41 |
+
last_ref_layer_before = ref_model.get_parameter(layer_1).data.clone()
|
| 42 |
+
|
| 43 |
+
output = self.model(input_ids=self.test_input, labels=self.test_input)
|
| 44 |
+
output[1].backward()
|
| 45 |
+
self.optimizer.step()
|
| 46 |
+
|
| 47 |
+
first_layer_after = self.model.get_parameter(layer_0).data.clone()
|
| 48 |
+
last_layer_after = self.model.get_parameter(layer_1).data.clone()
|
| 49 |
+
|
| 50 |
+
first_ref_layer_after = ref_model.get_parameter(layer_0).data.clone()
|
| 51 |
+
last_ref_layer_after = ref_model.get_parameter(layer_1).data.clone()
|
| 52 |
+
|
| 53 |
+
# before optimization ref and model are identical
|
| 54 |
+
assert (first_layer_before == first_ref_layer_before).all()
|
| 55 |
+
assert (last_layer_before == last_ref_layer_before).all()
|
| 56 |
+
|
| 57 |
+
# ref model stays identical after optimization
|
| 58 |
+
assert (first_ref_layer_before == first_ref_layer_after).all()
|
| 59 |
+
assert (last_ref_layer_before == last_ref_layer_after).all()
|
| 60 |
+
|
| 61 |
+
# optimized model changes
|
| 62 |
+
assert not (first_layer_before == first_layer_after).all()
|
| 63 |
+
assert not (last_layer_before == last_layer_after).all()
|
| 64 |
+
|
| 65 |
+
def test_shared_layers(self):
|
| 66 |
+
layer_0 = self.layer_format.format(layer=0)
|
| 67 |
+
layer_1 = self.layer_format.format(layer=1)
|
| 68 |
+
|
| 69 |
+
ref_model = create_reference_model(self.model, num_shared_layers=1)
|
| 70 |
+
|
| 71 |
+
first_layer_before = self.model.get_parameter(layer_0).data.clone()
|
| 72 |
+
second_layer_before = self.model.get_parameter(layer_1).data.clone()
|
| 73 |
+
|
| 74 |
+
first_ref_layer_before = ref_model.get_parameter(layer_0).data.clone()
|
| 75 |
+
second_ref_layer_before = ref_model.get_parameter(layer_1).data.clone()
|
| 76 |
+
|
| 77 |
+
output = self.model(input_ids=self.test_input, labels=self.test_input)
|
| 78 |
+
output[1].backward()
|
| 79 |
+
self.optimizer.step()
|
| 80 |
+
|
| 81 |
+
first_layer_after = self.model.get_parameter(layer_0).data.clone()
|
| 82 |
+
second_layer_after = self.model.get_parameter(layer_1).data.clone()
|
| 83 |
+
|
| 84 |
+
first_ref_layer_after = ref_model.get_parameter(layer_0).data.clone()
|
| 85 |
+
second_ref_layer_after = ref_model.get_parameter(layer_1).data.clone()
|
| 86 |
+
|
| 87 |
+
# before optimization ref and model are identical
|
| 88 |
+
assert (first_layer_before == first_ref_layer_before).all()
|
| 89 |
+
assert (second_layer_before == second_ref_layer_before).all()
|
| 90 |
+
|
| 91 |
+
# ref model stays identical after optimization
|
| 92 |
+
assert (first_ref_layer_before == first_ref_layer_after).all()
|
| 93 |
+
assert (second_ref_layer_before == second_ref_layer_after).all()
|
| 94 |
+
|
| 95 |
+
# first layer of optimized model stays the same
|
| 96 |
+
assert (first_layer_before == first_layer_after).all()
|
| 97 |
+
|
| 98 |
+
# other layers in optimized model change
|
| 99 |
+
assert not (second_layer_before == second_layer_after).all()
|
| 100 |
+
|
| 101 |
+
def test_shared_layers_share_memory(self):
|
| 102 |
+
# Shared layers must reference the same storage as the source model, not a `deepcopy` duplicate,
|
| 103 |
+
# so they are held in memory only once (see issue #2904).
|
| 104 |
+
layer_0 = self.layer_format.format(layer=0)
|
| 105 |
+
layer_1 = self.layer_format.format(layer=1)
|
| 106 |
+
|
| 107 |
+
ref_model = create_reference_model(self.model, num_shared_layers=1)
|
| 108 |
+
|
| 109 |
+
# the shared layer points at the same storage as the source model
|
| 110 |
+
assert ref_model.get_parameter(layer_0).data_ptr() == self.model.get_parameter(layer_0).data_ptr()
|
| 111 |
+
# an unshared layer is an independent copy
|
| 112 |
+
assert ref_model.get_parameter(layer_1).data_ptr() != self.model.get_parameter(layer_1).data_ptr()
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_nash_md_trainer.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from datasets import load_dataset
|
| 18 |
+
from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer, GenerationConfig
|
| 19 |
+
from transformers.utils import is_peft_available
|
| 20 |
+
|
| 21 |
+
from trl.experimental.nash_md import NashMDConfig, NashMDTrainer
|
| 22 |
+
from trl.experimental.nash_md.nash_md_trainer import GeometricMixtureWrapper
|
| 23 |
+
from trl.experimental.utils import create_reference_model
|
| 24 |
+
|
| 25 |
+
from ..testing_utils import TrlTestCase, require_peft
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_peft_available():
|
| 29 |
+
from peft import LoraConfig, get_peft_model
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TestGeometricMixtureWrapper(TrlTestCase):
|
| 33 |
+
def setup_method(self):
|
| 34 |
+
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 35 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 36 |
+
self.model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32").to(self.device)
|
| 37 |
+
self.ref_model = create_reference_model(self.model).to(self.device)
|
| 38 |
+
self.generation_config = GenerationConfig.from_pretrained(model_id)
|
| 39 |
+
self.mixture_coef = 0.5
|
| 40 |
+
self.wrapper = GeometricMixtureWrapper(
|
| 41 |
+
self.model, self.ref_model, self.generation_config, mixture_coef=self.mixture_coef
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
def test_forward(self):
|
| 45 |
+
input_ids = torch.tensor([[1, 2, 3, 4, 5]], device=self.device)
|
| 46 |
+
attention_mask = torch.ones_like(input_ids)
|
| 47 |
+
|
| 48 |
+
output = self.wrapper(input_ids=input_ids, attention_mask=attention_mask)
|
| 49 |
+
|
| 50 |
+
assert output is not None
|
| 51 |
+
assert hasattr(output, "logits")
|
| 52 |
+
assert output.logits.shape == (1, 5, self.model.config.vocab_size)
|
| 53 |
+
|
| 54 |
+
def test_mixture_coefficient(self):
|
| 55 |
+
input_ids = torch.tensor([[1, 2, 3, 4, 5]], device=self.device)
|
| 56 |
+
attention_mask = torch.ones_like(input_ids)
|
| 57 |
+
|
| 58 |
+
with torch.no_grad():
|
| 59 |
+
model_output = self.model(input_ids=input_ids, attention_mask=attention_mask)
|
| 60 |
+
ref_model_output = self.ref_model(input_ids=input_ids, attention_mask=attention_mask)
|
| 61 |
+
wrapper_output = self.wrapper(input_ids=input_ids, attention_mask=attention_mask)
|
| 62 |
+
|
| 63 |
+
expected_logits = torch.nn.functional.log_softmax(
|
| 64 |
+
self.mixture_coef * ref_model_output.logits + (1 - self.mixture_coef) * model_output.logits, dim=-1
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
torch.testing.assert_close(wrapper_output.logits, expected_logits)
|
| 68 |
+
|
| 69 |
+
def test_prepare_inputs_for_generation(self):
|
| 70 |
+
input_ids = torch.tensor([[1, 2, 3, 4, 5]], device=self.device)
|
| 71 |
+
attention_mask = torch.ones_like(input_ids)
|
| 72 |
+
|
| 73 |
+
inputs = self.wrapper.prepare_inputs_for_generation(input_ids, attention_mask=attention_mask, use_cache=True)
|
| 74 |
+
|
| 75 |
+
assert "input_ids" in inputs
|
| 76 |
+
assert "attention_mask" in inputs
|
| 77 |
+
assert not inputs.get("use_cache", False)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class TestNashMDTrainer(TrlTestCase):
|
| 81 |
+
def setup_method(self):
|
| 82 |
+
self.model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 83 |
+
self.model = AutoModelForCausalLM.from_pretrained(self.model_id, dtype="float32")
|
| 84 |
+
self.ref_model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 85 |
+
self.reward_model = AutoModelForSequenceClassification.from_pretrained(self.model_id, num_labels=1)
|
| 86 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
|
| 87 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 88 |
+
|
| 89 |
+
@pytest.mark.parametrize("config_name", ["standard_prompt_only", "conversational_prompt_only"])
|
| 90 |
+
def test_nash_md_trainer_training(self, config_name):
|
| 91 |
+
training_args = NashMDConfig(
|
| 92 |
+
output_dir=self.tmp_dir,
|
| 93 |
+
per_device_train_batch_size=2,
|
| 94 |
+
max_steps=3,
|
| 95 |
+
remove_unused_columns=False,
|
| 96 |
+
gradient_accumulation_steps=1,
|
| 97 |
+
learning_rate=9e-1,
|
| 98 |
+
report_to="none",
|
| 99 |
+
)
|
| 100 |
+
dataset = load_dataset("trl-internal-testing/zen", config_name, split="train")
|
| 101 |
+
|
| 102 |
+
trainer = NashMDTrainer(
|
| 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 |
+
)
|
| 110 |
+
|
| 111 |
+
trainer.train()
|
| 112 |
+
|
| 113 |
+
assert "train_loss" in trainer.state.log_history[-1]
|
| 114 |
+
|
| 115 |
+
@require_peft
|
| 116 |
+
def test_train_with_peft(self):
|
| 117 |
+
lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM")
|
| 118 |
+
training_args = NashMDConfig(
|
| 119 |
+
output_dir=self.tmp_dir,
|
| 120 |
+
per_device_train_batch_size=2,
|
| 121 |
+
max_steps=3,
|
| 122 |
+
learning_rate=5.0e-7,
|
| 123 |
+
report_to="none",
|
| 124 |
+
)
|
| 125 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 126 |
+
|
| 127 |
+
trainer = NashMDTrainer(
|
| 128 |
+
model=self.model,
|
| 129 |
+
reward_funcs=self.reward_model,
|
| 130 |
+
args=training_args,
|
| 131 |
+
processing_class=self.tokenizer,
|
| 132 |
+
train_dataset=dataset,
|
| 133 |
+
peft_config=lora_config,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
trainer.train()
|
| 137 |
+
|
| 138 |
+
assert "train_loss" in trainer.state.log_history[-1]
|
| 139 |
+
|
| 140 |
+
@require_peft
|
| 141 |
+
def test_train_with_peft_and_ref_model(self):
|
| 142 |
+
lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM")
|
| 143 |
+
training_args = NashMDConfig(
|
| 144 |
+
output_dir=self.tmp_dir,
|
| 145 |
+
per_device_train_batch_size=2,
|
| 146 |
+
max_steps=3,
|
| 147 |
+
learning_rate=5.0e-7,
|
| 148 |
+
report_to="none",
|
| 149 |
+
)
|
| 150 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 151 |
+
|
| 152 |
+
trainer = NashMDTrainer(
|
| 153 |
+
model=self.model,
|
| 154 |
+
ref_model=self.ref_model,
|
| 155 |
+
reward_funcs=self.reward_model,
|
| 156 |
+
args=training_args,
|
| 157 |
+
processing_class=self.tokenizer,
|
| 158 |
+
train_dataset=dataset,
|
| 159 |
+
peft_config=lora_config,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
trainer.train()
|
| 163 |
+
|
| 164 |
+
assert "train_loss" in trainer.state.log_history[-1]
|
| 165 |
+
|
| 166 |
+
@require_peft
|
| 167 |
+
def test_train_pre_pefted_model_implicit_ref_with_reward_model(self):
|
| 168 |
+
lora_config = LoraConfig(r=8, lora_alpha=16, lora_dropout=0.1, bias="none", task_type="CAUSAL_LM")
|
| 169 |
+
# self.model from setUp is a base AutoModelForCausalLM
|
| 170 |
+
peft_model_instance = get_peft_model(self.model, lora_config)
|
| 171 |
+
|
| 172 |
+
training_args = NashMDConfig(
|
| 173 |
+
output_dir=self.tmp_dir,
|
| 174 |
+
per_device_train_batch_size=1, # Keep small for quick test
|
| 175 |
+
max_steps=2, # Few steps
|
| 176 |
+
learning_rate=5.0e-7,
|
| 177 |
+
eval_strategy="no",
|
| 178 |
+
report_to="none",
|
| 179 |
+
remove_unused_columns=False, # Important for the dummy dataset
|
| 180 |
+
)
|
| 181 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 182 |
+
|
| 183 |
+
trainer = NashMDTrainer(
|
| 184 |
+
model=peft_model_instance, # Pass the already PEFT model
|
| 185 |
+
ref_model=None, # Implicit reference from peft_model_instance's base
|
| 186 |
+
reward_funcs=self.reward_model, # To trigger GeometricMixtureWrapper path
|
| 187 |
+
args=training_args,
|
| 188 |
+
processing_class=self.tokenizer,
|
| 189 |
+
train_dataset=dataset,
|
| 190 |
+
# peft_config is not passed, as model is already PEFT
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
trainer.train()
|
| 194 |
+
|
| 195 |
+
assert "train_loss" in trainer.state.log_history[-1]
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_online_dpo_trainer.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 Dataset, features, load_dataset
|
| 17 |
+
from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer
|
| 18 |
+
from transformers.utils import is_peft_available, is_vision_available
|
| 19 |
+
|
| 20 |
+
from trl.experimental.online_dpo import OnlineDPOConfig, OnlineDPOTrainer
|
| 21 |
+
|
| 22 |
+
from ..testing_utils import TrlTestCase, require_peft, require_torch_accelerator, require_vision, require_vllm
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if is_peft_available():
|
| 26 |
+
from peft import LoraConfig
|
| 27 |
+
|
| 28 |
+
if is_vision_available():
|
| 29 |
+
import numpy as np
|
| 30 |
+
from PIL import Image
|
| 31 |
+
from transformers import AutoModelForImageTextToText, AutoProcessor
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class TestOnlineDPOTrainer(TrlTestCase):
|
| 35 |
+
def setup_method(self):
|
| 36 |
+
self.model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 37 |
+
self.model = AutoModelForCausalLM.from_pretrained(self.model_id, dtype="float32")
|
| 38 |
+
self.ref_model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 39 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
|
| 40 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 41 |
+
|
| 42 |
+
self.reward_model_id = "trl-internal-testing/tiny-LlamaForCausalLM-3.2"
|
| 43 |
+
self.reward_model = AutoModelForSequenceClassification.from_pretrained(self.reward_model_id, num_labels=1)
|
| 44 |
+
self.reward_tokenizer = AutoTokenizer.from_pretrained(self.reward_model_id)
|
| 45 |
+
self.reward_tokenizer.pad_token = self.reward_tokenizer.eos_token
|
| 46 |
+
|
| 47 |
+
def test_trust_remote_code(self):
|
| 48 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 49 |
+
model_id = "trl-internal-testing/tiny-RemoteForCausalLM"
|
| 50 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 51 |
+
|
| 52 |
+
with pytest.raises(ValueError, match="custom code"):
|
| 53 |
+
OnlineDPOTrainer(
|
| 54 |
+
model=model_id,
|
| 55 |
+
reward_funcs=self.reward_model,
|
| 56 |
+
args=OnlineDPOConfig(output_dir=self.tmp_dir, report_to="none"),
|
| 57 |
+
train_dataset=dataset,
|
| 58 |
+
processing_class=tokenizer,
|
| 59 |
+
reward_processing_classes=self.reward_tokenizer,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
trainer = OnlineDPOTrainer(
|
| 63 |
+
model=model_id,
|
| 64 |
+
reward_funcs=self.reward_model,
|
| 65 |
+
args=OnlineDPOConfig(output_dir=self.tmp_dir, report_to="none", trust_remote_code=True),
|
| 66 |
+
train_dataset=dataset,
|
| 67 |
+
processing_class=tokenizer,
|
| 68 |
+
reward_processing_classes=self.reward_tokenizer,
|
| 69 |
+
)
|
| 70 |
+
assert type(trainer.model).__name__ == "RemoteForCausalLM"
|
| 71 |
+
|
| 72 |
+
@pytest.mark.parametrize("config_name", ["standard_prompt_only", "conversational_prompt_only"])
|
| 73 |
+
def test_train(self, config_name):
|
| 74 |
+
training_args = OnlineDPOConfig(
|
| 75 |
+
output_dir=self.tmp_dir,
|
| 76 |
+
per_device_train_batch_size=2,
|
| 77 |
+
max_steps=3,
|
| 78 |
+
learning_rate=5.0e-7,
|
| 79 |
+
report_to="none",
|
| 80 |
+
)
|
| 81 |
+
dataset = load_dataset("trl-internal-testing/zen", config_name, split="train")
|
| 82 |
+
|
| 83 |
+
trainer = OnlineDPOTrainer(
|
| 84 |
+
model=self.model,
|
| 85 |
+
reward_funcs=self.reward_model,
|
| 86 |
+
args=training_args,
|
| 87 |
+
train_dataset=dataset,
|
| 88 |
+
processing_class=self.tokenizer,
|
| 89 |
+
reward_processing_classes=self.reward_tokenizer,
|
| 90 |
+
)
|
| 91 |
+
trainer.train()
|
| 92 |
+
|
| 93 |
+
assert "train_loss" in trainer.state.log_history[-1]
|
| 94 |
+
|
| 95 |
+
def test_train_model_str(self):
|
| 96 |
+
training_args = OnlineDPOConfig(
|
| 97 |
+
output_dir=self.tmp_dir,
|
| 98 |
+
per_device_train_batch_size=2,
|
| 99 |
+
max_steps=3,
|
| 100 |
+
learning_rate=5.0e-7,
|
| 101 |
+
report_to="none",
|
| 102 |
+
)
|
| 103 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 104 |
+
|
| 105 |
+
trainer = OnlineDPOTrainer(
|
| 106 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 107 |
+
reward_funcs=self.reward_model,
|
| 108 |
+
args=training_args,
|
| 109 |
+
train_dataset=dataset,
|
| 110 |
+
processing_class=self.tokenizer,
|
| 111 |
+
reward_processing_classes=self.reward_tokenizer,
|
| 112 |
+
)
|
| 113 |
+
trainer.train()
|
| 114 |
+
|
| 115 |
+
assert "train_loss" in trainer.state.log_history[-1]
|
| 116 |
+
|
| 117 |
+
def test_train_with_ref_model(self):
|
| 118 |
+
training_args = OnlineDPOConfig(
|
| 119 |
+
output_dir=self.tmp_dir,
|
| 120 |
+
per_device_train_batch_size=2,
|
| 121 |
+
max_steps=3,
|
| 122 |
+
learning_rate=5.0e-7,
|
| 123 |
+
report_to="none",
|
| 124 |
+
)
|
| 125 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 126 |
+
|
| 127 |
+
trainer = OnlineDPOTrainer(
|
| 128 |
+
model=self.model,
|
| 129 |
+
ref_model=self.ref_model,
|
| 130 |
+
reward_funcs=self.reward_model,
|
| 131 |
+
args=training_args,
|
| 132 |
+
train_dataset=dataset,
|
| 133 |
+
processing_class=self.tokenizer,
|
| 134 |
+
reward_processing_classes=self.reward_tokenizer,
|
| 135 |
+
)
|
| 136 |
+
trainer.train()
|
| 137 |
+
|
| 138 |
+
assert "train_loss" in trainer.state.log_history[-1]
|
| 139 |
+
|
| 140 |
+
def test_ref_model_is_model(self):
|
| 141 |
+
training_args = OnlineDPOConfig(
|
| 142 |
+
output_dir=self.tmp_dir,
|
| 143 |
+
per_device_train_batch_size=2,
|
| 144 |
+
max_steps=3,
|
| 145 |
+
report_to="none",
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 149 |
+
|
| 150 |
+
with pytest.raises(ValueError):
|
| 151 |
+
OnlineDPOTrainer(
|
| 152 |
+
model=self.model,
|
| 153 |
+
ref_model=self.model, # ref_model can't be the same as model
|
| 154 |
+
reward_funcs=self.reward_model,
|
| 155 |
+
args=training_args,
|
| 156 |
+
train_dataset=dataset,
|
| 157 |
+
processing_class=self.tokenizer,
|
| 158 |
+
reward_processing_classes=self.reward_tokenizer,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
@require_peft
|
| 162 |
+
def test_train_with_peft(self):
|
| 163 |
+
lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM")
|
| 164 |
+
training_args = OnlineDPOConfig(
|
| 165 |
+
output_dir=self.tmp_dir,
|
| 166 |
+
per_device_train_batch_size=2,
|
| 167 |
+
max_steps=3,
|
| 168 |
+
learning_rate=5.0e-7,
|
| 169 |
+
report_to="none",
|
| 170 |
+
)
|
| 171 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 172 |
+
|
| 173 |
+
trainer = OnlineDPOTrainer(
|
| 174 |
+
model=self.model,
|
| 175 |
+
reward_funcs=self.reward_model,
|
| 176 |
+
args=training_args,
|
| 177 |
+
train_dataset=dataset,
|
| 178 |
+
processing_class=self.tokenizer,
|
| 179 |
+
reward_processing_classes=self.reward_tokenizer,
|
| 180 |
+
peft_config=lora_config,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
trainer.train()
|
| 184 |
+
|
| 185 |
+
assert "train_loss" in trainer.state.log_history[-1]
|
| 186 |
+
|
| 187 |
+
@require_peft
|
| 188 |
+
def test_train_with_peft_and_ref_model(self):
|
| 189 |
+
lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM")
|
| 190 |
+
training_args = OnlineDPOConfig(
|
| 191 |
+
output_dir=self.tmp_dir,
|
| 192 |
+
per_device_train_batch_size=2,
|
| 193 |
+
max_steps=3,
|
| 194 |
+
learning_rate=5.0e-7,
|
| 195 |
+
report_to="none",
|
| 196 |
+
)
|
| 197 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 198 |
+
|
| 199 |
+
trainer = OnlineDPOTrainer(
|
| 200 |
+
model=self.model,
|
| 201 |
+
ref_model=self.ref_model,
|
| 202 |
+
reward_funcs=self.reward_model,
|
| 203 |
+
args=training_args,
|
| 204 |
+
train_dataset=dataset,
|
| 205 |
+
processing_class=self.tokenizer,
|
| 206 |
+
reward_processing_classes=self.reward_tokenizer,
|
| 207 |
+
peft_config=lora_config,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
trainer.train()
|
| 211 |
+
|
| 212 |
+
assert "train_loss" in trainer.state.log_history[-1]
|
| 213 |
+
|
| 214 |
+
@pytest.mark.parametrize("config_name", ["standard_prompt_only", "conversational_prompt_only"])
|
| 215 |
+
@require_torch_accelerator
|
| 216 |
+
@require_vllm
|
| 217 |
+
@pytest.mark.slow
|
| 218 |
+
def test_train_with_vllm_server(self, config_name):
|
| 219 |
+
def cleanup_vllm_communicator(trainer):
|
| 220 |
+
"""Clean up vLLM communicator to avoid conflicts between test runs"""
|
| 221 |
+
try:
|
| 222 |
+
if hasattr(trainer, "vllm_client") and trainer.vllm_client is not None:
|
| 223 |
+
trainer.vllm_client.close_communicator()
|
| 224 |
+
except Exception:
|
| 225 |
+
pass # Continue if cleanup fails
|
| 226 |
+
|
| 227 |
+
model_id = "trl-internal-testing/small-Qwen2ForCausalLM-2.5" # We need a bigger model
|
| 228 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
|
| 229 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 230 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 231 |
+
|
| 232 |
+
training_args = OnlineDPOConfig(
|
| 233 |
+
output_dir=self.tmp_dir,
|
| 234 |
+
use_vllm=True,
|
| 235 |
+
vllm_mode="server",
|
| 236 |
+
vllm_gpu_memory_utilization=0.2,
|
| 237 |
+
report_to="none",
|
| 238 |
+
)
|
| 239 |
+
dataset = load_dataset("trl-internal-testing/zen", config_name, split="train")
|
| 240 |
+
|
| 241 |
+
trainer = OnlineDPOTrainer(
|
| 242 |
+
model=model,
|
| 243 |
+
reward_funcs=self.reward_model,
|
| 244 |
+
args=training_args,
|
| 245 |
+
train_dataset=dataset,
|
| 246 |
+
processing_class=tokenizer,
|
| 247 |
+
reward_processing_classes=self.reward_tokenizer,
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
# Ensure cleanup of vLLM communicator after the test
|
| 251 |
+
try:
|
| 252 |
+
trainer.train()
|
| 253 |
+
# Check if training loss is available
|
| 254 |
+
assert "train_loss" in trainer.state.log_history[-1]
|
| 255 |
+
finally:
|
| 256 |
+
cleanup_vllm_communicator(trainer)
|
| 257 |
+
|
| 258 |
+
@require_vllm
|
| 259 |
+
def test_train_with_vllm_colocate(self):
|
| 260 |
+
"""Test vLLM colocate mode with our refactored implementation"""
|
| 261 |
+
model_id = "trl-internal-testing/small-Qwen2ForCausalLM-2.5" # We need a bigger model
|
| 262 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
|
| 263 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 264 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 265 |
+
|
| 266 |
+
training_args = OnlineDPOConfig(
|
| 267 |
+
output_dir=self.tmp_dir,
|
| 268 |
+
use_vllm=True,
|
| 269 |
+
vllm_mode="colocate",
|
| 270 |
+
vllm_gpu_memory_utilization=0.2,
|
| 271 |
+
per_device_train_batch_size=1,
|
| 272 |
+
max_steps=2,
|
| 273 |
+
report_to="none",
|
| 274 |
+
# Test generation parameters
|
| 275 |
+
temperature=0.9,
|
| 276 |
+
top_p=0.95,
|
| 277 |
+
top_k=50,
|
| 278 |
+
repetition_penalty=1.1,
|
| 279 |
+
max_new_tokens=32,
|
| 280 |
+
)
|
| 281 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 282 |
+
|
| 283 |
+
trainer = OnlineDPOTrainer(
|
| 284 |
+
model=model,
|
| 285 |
+
reward_funcs=self.reward_model,
|
| 286 |
+
args=training_args,
|
| 287 |
+
train_dataset=dataset,
|
| 288 |
+
processing_class=tokenizer,
|
| 289 |
+
reward_processing_classes=self.reward_tokenizer,
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
# Verify vLLM setup
|
| 293 |
+
assert trainer.use_vllm
|
| 294 |
+
assert trainer.vllm_mode == "colocate"
|
| 295 |
+
assert trainer.llm is not None
|
| 296 |
+
# self.assertIsNone(trainer.vllm_client)
|
| 297 |
+
# self.assertEqual(trainer.vllm_gpu_memory_utilization, 0.2)
|
| 298 |
+
|
| 299 |
+
# Verify generation parameters
|
| 300 |
+
assert trainer.temperature == 0.9
|
| 301 |
+
assert trainer.top_p == 0.95
|
| 302 |
+
assert trainer.top_k == 50
|
| 303 |
+
assert trainer.repetition_penalty == 1.1
|
| 304 |
+
|
| 305 |
+
# Verify generation config
|
| 306 |
+
assert trainer.generation_config is not None
|
| 307 |
+
assert trainer.generation_config.temperature == 0.9
|
| 308 |
+
assert trainer.generation_config.top_p == 0.95
|
| 309 |
+
assert trainer.generation_config.top_k == 50
|
| 310 |
+
assert trainer.generation_config.repetition_penalty == 1.1
|
| 311 |
+
assert trainer.generation_config.max_tokens == 32
|
| 312 |
+
|
| 313 |
+
trainer.train()
|
| 314 |
+
|
| 315 |
+
assert "train_loss" in trainer.state.log_history[-1]
|
| 316 |
+
|
| 317 |
+
def test_vllm_config_validation(self):
|
| 318 |
+
"""Test vLLM configuration validation"""
|
| 319 |
+
# Test valid vllm_mode values
|
| 320 |
+
config = OnlineDPOConfig(use_vllm=True, vllm_mode="server")
|
| 321 |
+
assert config.vllm_mode == "server"
|
| 322 |
+
|
| 323 |
+
config = OnlineDPOConfig(use_vllm=True, vllm_mode="colocate")
|
| 324 |
+
assert config.vllm_mode == "colocate"
|
| 325 |
+
|
| 326 |
+
# Test default values
|
| 327 |
+
config = OnlineDPOConfig()
|
| 328 |
+
assert config.vllm_mode == "colocate"
|
| 329 |
+
assert config.vllm_server_base_url is None
|
| 330 |
+
assert config.vllm_server_host == "0.0.0.0"
|
| 331 |
+
assert config.vllm_server_port == 8000
|
| 332 |
+
assert config.vllm_server_timeout == 240.0
|
| 333 |
+
assert config.vllm_gpu_memory_utilization == 0.55
|
| 334 |
+
|
| 335 |
+
# Test generation parameters
|
| 336 |
+
assert config.top_p == 1.0
|
| 337 |
+
assert config.top_k == 0
|
| 338 |
+
assert config.min_p is None
|
| 339 |
+
assert config.repetition_penalty == 1.0
|
| 340 |
+
assert config.cache_implementation is None
|
| 341 |
+
assert config.generation_kwargs is None
|
| 342 |
+
|
| 343 |
+
def test_generation_config_setup(self):
|
| 344 |
+
"""Test that generation configuration is properly set up for both vLLM and transformers"""
|
| 345 |
+
training_args = OnlineDPOConfig(
|
| 346 |
+
output_dir=self.tmp_dir,
|
| 347 |
+
use_vllm=False,
|
| 348 |
+
temperature=0.8,
|
| 349 |
+
top_p=0.9,
|
| 350 |
+
top_k=40,
|
| 351 |
+
repetition_penalty=1.2,
|
| 352 |
+
max_new_tokens=64,
|
| 353 |
+
generation_kwargs={"do_sample": False},
|
| 354 |
+
report_to="none",
|
| 355 |
+
)
|
| 356 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 357 |
+
|
| 358 |
+
trainer = OnlineDPOTrainer(
|
| 359 |
+
model=self.model,
|
| 360 |
+
reward_funcs=self.reward_model,
|
| 361 |
+
args=training_args,
|
| 362 |
+
train_dataset=dataset,
|
| 363 |
+
processing_class=self.tokenizer,
|
| 364 |
+
reward_processing_classes=self.reward_tokenizer,
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
# Verify transformers generation config
|
| 368 |
+
assert not trainer.use_vllm
|
| 369 |
+
# When not using vLLM, these attributes should not be set
|
| 370 |
+
assert not (hasattr(trainer, "llm") and trainer.llm is not None)
|
| 371 |
+
assert not (hasattr(trainer, "vllm_client") and trainer.vllm_client is not None)
|
| 372 |
+
assert trainer.generation_config is not None
|
| 373 |
+
assert trainer.generation_config.temperature == 0.8
|
| 374 |
+
assert trainer.generation_config.top_p == 0.9
|
| 375 |
+
assert trainer.generation_config.top_k == 40
|
| 376 |
+
assert trainer.generation_config.repetition_penalty == 1.2
|
| 377 |
+
assert trainer.generation_config.max_new_tokens == 64
|
| 378 |
+
assert not trainer.generation_config.do_sample # From generation_kwargs
|
| 379 |
+
|
| 380 |
+
@pytest.mark.parametrize("config_name", ["standard_prompt_only", "conversational_prompt_only"])
|
| 381 |
+
def test_train_with_reward_funcs(self, config_name):
|
| 382 |
+
def simple_reward_func(prompts, completions, completion_ids, **kwargs):
|
| 383 |
+
return [0.5 for _ in prompts]
|
| 384 |
+
|
| 385 |
+
training_args = OnlineDPOConfig(
|
| 386 |
+
output_dir=self.tmp_dir,
|
| 387 |
+
per_device_train_batch_size=2,
|
| 388 |
+
max_steps=3,
|
| 389 |
+
learning_rate=5.0e-7,
|
| 390 |
+
reward_weights=[0.7, 0.3],
|
| 391 |
+
report_to="none",
|
| 392 |
+
)
|
| 393 |
+
dataset = load_dataset("trl-internal-testing/zen", config_name, split="train")
|
| 394 |
+
|
| 395 |
+
trainer = OnlineDPOTrainer(
|
| 396 |
+
model=self.model,
|
| 397 |
+
reward_funcs=[simple_reward_func, simple_reward_func],
|
| 398 |
+
args=training_args,
|
| 399 |
+
train_dataset=dataset,
|
| 400 |
+
processing_class=self.tokenizer,
|
| 401 |
+
)
|
| 402 |
+
trainer.train()
|
| 403 |
+
|
| 404 |
+
assert "train_loss" in trainer.state.log_history[-1]
|
| 405 |
+
assert len(trainer.reward_funcs) == 2
|
| 406 |
+
assert trainer.reward_weights is not None
|
| 407 |
+
assert round(abs(trainer.reward_weights[0].item() - 0.7), 5) == 0
|
| 408 |
+
assert round(abs(trainer.reward_weights[1].item() - 0.3), 5) == 0
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
@require_vision
|
| 412 |
+
class TestOnlineDPOVisionTrainer(TrlTestCase):
|
| 413 |
+
@pytest.mark.parametrize(
|
| 414 |
+
"model_id",
|
| 415 |
+
[
|
| 416 |
+
"trl-internal-testing/tiny-Idefics2ForConditionalGeneration",
|
| 417 |
+
"trl-internal-testing/tiny-LlavaForConditionalGeneration",
|
| 418 |
+
],
|
| 419 |
+
)
|
| 420 |
+
def test_online_dpo_vlm_trainer(self, model_id):
|
| 421 |
+
dataset_dict = {
|
| 422 |
+
"prompt": [
|
| 423 |
+
[{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "Describe the image."}]}],
|
| 424 |
+
[{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What do you see?"}]}],
|
| 425 |
+
],
|
| 426 |
+
"images": [
|
| 427 |
+
[Image.fromarray(np.random.randint(0, 255, (64, 64, 3), dtype=np.uint8))],
|
| 428 |
+
[Image.fromarray(np.random.randint(0, 255, (64, 64, 3), dtype=np.uint8))],
|
| 429 |
+
],
|
| 430 |
+
}
|
| 431 |
+
dataset = Dataset.from_dict(dataset_dict)
|
| 432 |
+
dataset = dataset.cast_column("images", features.Sequence(features.Image()))
|
| 433 |
+
|
| 434 |
+
model = AutoModelForImageTextToText.from_pretrained(model_id, dtype="float32")
|
| 435 |
+
reward_model = AutoModelForSequenceClassification.from_pretrained(
|
| 436 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.2", num_labels=1
|
| 437 |
+
)
|
| 438 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
| 439 |
+
reward_tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-LlamaForCausalLM-3.2")
|
| 440 |
+
reward_tokenizer.pad_token = reward_tokenizer.eos_token
|
| 441 |
+
|
| 442 |
+
training_args = OnlineDPOConfig(
|
| 443 |
+
output_dir=self.tmp_dir,
|
| 444 |
+
per_device_train_batch_size=1,
|
| 445 |
+
max_steps=2,
|
| 446 |
+
learning_rate=0.01,
|
| 447 |
+
report_to="none",
|
| 448 |
+
)
|
| 449 |
+
trainer = OnlineDPOTrainer(
|
| 450 |
+
model=model,
|
| 451 |
+
reward_funcs=reward_model,
|
| 452 |
+
args=training_args,
|
| 453 |
+
processing_class=processor,
|
| 454 |
+
train_dataset=dataset,
|
| 455 |
+
eval_dataset=dataset,
|
| 456 |
+
reward_processing_classes=reward_tokenizer,
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
trainer.train()
|
| 460 |
+
|
| 461 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_openreward.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 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 |
+
"""Tests for `trl.experimental.openreward`.
|
| 16 |
+
|
| 17 |
+
A class-scoped fixture spawns ``_openreward_echo_env.py`` as a uvicorn subprocess on a free port and points the
|
| 18 |
+
openreward SDK at it via the ``OPENREWARD_API_URL`` / ``OPENREWARD_SESSION_URL`` overrides. Tests then exercise the
|
| 19 |
+
adapter end-to-end against real HTTP — no mocks, no network.
|
| 20 |
+
|
| 21 |
+
The same env definition is published at ``trl-internal-testing/openreward-echo-env`` if you want to point at the hosted
|
| 22 |
+
Space directly.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
import os
|
| 26 |
+
import socket
|
| 27 |
+
import subprocess
|
| 28 |
+
import sys
|
| 29 |
+
import time
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
import pytest
|
| 33 |
+
import requests
|
| 34 |
+
|
| 35 |
+
from trl.experimental.openreward import OpenRewardSpec
|
| 36 |
+
|
| 37 |
+
from ..testing_utils import TrlTestCase, require_openreward
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
_HERE = Path(__file__).parent
|
| 41 |
+
_ECHO_ENV_SCRIPT = _HERE / "_openreward_echo_env.py"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _free_port() -> int:
|
| 45 |
+
with socket.socket() as s:
|
| 46 |
+
s.bind(("127.0.0.1", 0))
|
| 47 |
+
return s.getsockname()[1]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@pytest.fixture(scope="class")
|
| 51 |
+
def echo_env_url():
|
| 52 |
+
"""Spawn the echo env on a free port; tear down on teardown."""
|
| 53 |
+
port = _free_port()
|
| 54 |
+
proc = subprocess.Popen(
|
| 55 |
+
[sys.executable, str(_ECHO_ENV_SCRIPT)],
|
| 56 |
+
env={**os.environ, "PORT": str(port)},
|
| 57 |
+
stdout=subprocess.DEVNULL,
|
| 58 |
+
stderr=subprocess.DEVNULL,
|
| 59 |
+
)
|
| 60 |
+
url = f"http://127.0.0.1:{port}"
|
| 61 |
+
deadline = time.time() + 30.0
|
| 62 |
+
while time.time() < deadline:
|
| 63 |
+
try:
|
| 64 |
+
r = requests.get(f"{url}/health", timeout=1.0)
|
| 65 |
+
if r.status_code == 200:
|
| 66 |
+
break
|
| 67 |
+
except requests.RequestException:
|
| 68 |
+
pass
|
| 69 |
+
time.sleep(0.2)
|
| 70 |
+
else:
|
| 71 |
+
proc.terminate()
|
| 72 |
+
raise RuntimeError(f"echo env did not become ready at {url}")
|
| 73 |
+
|
| 74 |
+
# The openreward SDK by default rewrites base_url into api.<host> /
|
| 75 |
+
# sessions.<host>; for a single-host self-hosted server these env vars
|
| 76 |
+
# bypass that two-subdomain layout.
|
| 77 |
+
saved = {k: os.environ.get(k) for k in ("OPENREWARD_API_URL", "OPENREWARD_SESSION_URL", "OPENREWARD_API_KEY")}
|
| 78 |
+
os.environ["OPENREWARD_API_URL"] = url
|
| 79 |
+
os.environ["OPENREWARD_SESSION_URL"] = url
|
| 80 |
+
os.environ.setdefault("OPENREWARD_API_KEY", "test")
|
| 81 |
+
|
| 82 |
+
yield url
|
| 83 |
+
|
| 84 |
+
for k, v in saved.items():
|
| 85 |
+
if v is None:
|
| 86 |
+
os.environ.pop(k, None)
|
| 87 |
+
else:
|
| 88 |
+
os.environ[k] = v
|
| 89 |
+
proc.terminate()
|
| 90 |
+
try:
|
| 91 |
+
proc.wait(timeout=5.0)
|
| 92 |
+
except subprocess.TimeoutExpired:
|
| 93 |
+
proc.kill()
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@require_openreward
|
| 97 |
+
@pytest.mark.usefixtures("echo_env_url")
|
| 98 |
+
class TestOpenRewardSpec(TrlTestCase):
|
| 99 |
+
"""Exercises the public `OpenRewardSpec` surface against a real ORS server."""
|
| 100 |
+
|
| 101 |
+
def test_construction_is_lazy(self, echo_env_url):
|
| 102 |
+
# Construction must not perform any HTTP — `train_dataset` /
|
| 103 |
+
# `environment_factory` are `cached_property` and only fire on access.
|
| 104 |
+
spec = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=2)
|
| 105 |
+
# Touching only private attributes should not have hit the network.
|
| 106 |
+
assert spec._target == echo_env_url
|
| 107 |
+
assert spec._is_url is True
|
| 108 |
+
assert spec._num_tasks == 2
|
| 109 |
+
|
| 110 |
+
def test_train_dataset_derives_from_env(self, echo_env_url):
|
| 111 |
+
spec = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=2)
|
| 112 |
+
ds = spec.train_dataset
|
| 113 |
+
assert len(ds) == 2
|
| 114 |
+
assert "prompt" in ds.column_names
|
| 115 |
+
assert "task_index" in ds.column_names
|
| 116 |
+
# Per-task metadata folded in (id, target) when include_metadata=True.
|
| 117 |
+
assert "target" in ds.column_names
|
| 118 |
+
assert ds[0]["task_index"] == 0
|
| 119 |
+
assert ds[0]["target"] == "hello"
|
| 120 |
+
assert ds[1]["target"] == "world"
|
| 121 |
+
|
| 122 |
+
def test_train_dataset_with_indices(self, echo_env_url):
|
| 123 |
+
spec = OpenRewardSpec(echo_env_url, env_name="echoenvironment", indices=[0, 2])
|
| 124 |
+
ds = spec.train_dataset
|
| 125 |
+
assert [row["target"] for row in ds] == ["hello", "trl"]
|
| 126 |
+
|
| 127 |
+
def test_num_tasks_and_indices_are_mutually_exclusive(self, echo_env_url):
|
| 128 |
+
with pytest.raises(ValueError):
|
| 129 |
+
OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=2, indices=[0])
|
| 130 |
+
|
| 131 |
+
def test_environment_factory_returns_rollout_env_with_bound_tools(self, echo_env_url):
|
| 132 |
+
spec = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=2)
|
| 133 |
+
env = spec.environment_factory()
|
| 134 |
+
# Shared + task-scoped ORS tools (ORS /tools vs /task_tools) are both bound for GRPO.
|
| 135 |
+
assert callable(env.echo)
|
| 136 |
+
sig = env.echo.__annotations__
|
| 137 |
+
assert sig["text"] is str
|
| 138 |
+
assert sig["return"] is str
|
| 139 |
+
assert callable(env.hint)
|
| 140 |
+
|
| 141 |
+
def test_discover_task_tools_false_skips_task_scoped_binding(self, echo_env_url):
|
| 142 |
+
spec = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=1, discover_task_tools=False)
|
| 143 |
+
env = spec.environment_factory()
|
| 144 |
+
assert callable(env.echo)
|
| 145 |
+
assert not hasattr(env, "hint")
|
| 146 |
+
|
| 147 |
+
def test_reset_returns_prompt_and_opens_session(self, echo_env_url):
|
| 148 |
+
spec = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=1)
|
| 149 |
+
env = spec.environment_factory()
|
| 150 |
+
prompt = env.reset(**spec.train_dataset[0])
|
| 151 |
+
assert "echo" in prompt and "hello" in prompt
|
| 152 |
+
env._close()
|
| 153 |
+
|
| 154 |
+
def test_correct_echo_returns_match_with_reward_and_finished(self, echo_env_url):
|
| 155 |
+
spec = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=1)
|
| 156 |
+
env = spec.environment_factory()
|
| 157 |
+
env.reset(**spec.train_dataset[0])
|
| 158 |
+
out = env.echo(text="hello")
|
| 159 |
+
assert "match" in out
|
| 160 |
+
assert env.reward == 1.0
|
| 161 |
+
assert env.finished is True
|
| 162 |
+
env._close()
|
| 163 |
+
|
| 164 |
+
def test_wrong_echo_returns_no_match_with_zero_reward(self, echo_env_url):
|
| 165 |
+
spec = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=1)
|
| 166 |
+
env = spec.environment_factory()
|
| 167 |
+
env.reset(**spec.train_dataset[0])
|
| 168 |
+
out = env.echo(text="goodbye")
|
| 169 |
+
assert "no match" in out
|
| 170 |
+
assert env.reward == 0.0
|
| 171 |
+
assert env.finished is False
|
| 172 |
+
env._close()
|
| 173 |
+
|
| 174 |
+
def test_reward_func_reads_last_non_null_per_environment(self, echo_env_url):
|
| 175 |
+
spec = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=2)
|
| 176 |
+
env_a = spec.environment_factory()
|
| 177 |
+
env_b = spec.environment_factory()
|
| 178 |
+
env_a.reset(**spec.train_dataset[0])
|
| 179 |
+
env_b.reset(**spec.train_dataset[1])
|
| 180 |
+
env_a.echo(text="hello") # match → reward=1.0
|
| 181 |
+
env_b.echo(text="oops") # no match → reward=0.0
|
| 182 |
+
rewards = spec.reward_funcs(environments=[env_a, env_b])
|
| 183 |
+
assert rewards == [1.0, 0.0]
|
| 184 |
+
env_a._close()
|
| 185 |
+
env_b._close()
|
| 186 |
+
|
| 187 |
+
def test_factory_produces_isolated_sessions(self, echo_env_url):
|
| 188 |
+
# GRPO opens N concurrent envs; mutating one must not leak into another.
|
| 189 |
+
spec = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=2)
|
| 190 |
+
env_a = spec.environment_factory()
|
| 191 |
+
env_b = spec.environment_factory()
|
| 192 |
+
env_a.reset(**spec.train_dataset[0])
|
| 193 |
+
env_b.reset(**spec.train_dataset[1])
|
| 194 |
+
env_a.echo(text="hello")
|
| 195 |
+
assert env_a.reward == 1.0
|
| 196 |
+
assert env_b.reward == 0.0 # untouched
|
| 197 |
+
env_a._close()
|
| 198 |
+
env_b._close()
|
| 199 |
+
|
| 200 |
+
def test_metadata_does_not_overwrite_reserved_columns(self, echo_env_url):
|
| 201 |
+
# If a task spec ever shipped a `prompt` key, the metadata loop must
|
| 202 |
+
# not clobber our chat-format `prompt` column. Same for `task_index`.
|
| 203 |
+
# We assert the shape directly — the echo env's task spec doesn't
|
| 204 |
+
# currently have either, but the guard is what we're testing.
|
| 205 |
+
spec = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=1)
|
| 206 |
+
ds = spec.train_dataset
|
| 207 |
+
# `prompt` is a list-of-message-dicts, not a string from task spec.
|
| 208 |
+
assert isinstance(ds[0]["prompt"], list)
|
| 209 |
+
assert ds[0]["prompt"][0]["role"] == "user"
|
| 210 |
+
# `task_index` is the int we set, not anything from the spec.
|
| 211 |
+
assert isinstance(ds[0]["task_index"], int)
|
| 212 |
+
|
| 213 |
+
def test_task_tools_discovery_index_probes_single_task(self, echo_env_url):
|
| 214 |
+
# task_tools_discovery_index=0 tells the spec to probe only task 0 for
|
| 215 |
+
# tool discovery (ORS /task_tools), regardless of how many tasks are in
|
| 216 |
+
# the dataset. This is the Toolathlon pattern: all tasks expose the same
|
| 217 |
+
# meta-tools, so probing one is sufficient and avoids N sessions.
|
| 218 |
+
spec = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=4, task_tools_discovery_index=0)
|
| 219 |
+
env = spec.environment_factory()
|
| 220 |
+
# Shared tool (echo) and task-specific tool (hint) are both bound.
|
| 221 |
+
assert callable(env.echo)
|
| 222 |
+
assert callable(env.hint)
|
| 223 |
+
# Dataset still has 4 tasks even though discovery only probed index 0.
|
| 224 |
+
assert len(spec.train_dataset) == 4
|
| 225 |
+
env._close()
|
| 226 |
+
|
| 227 |
+
def test_task_tools_discovery_index_with_indices(self, echo_env_url):
|
| 228 |
+
# When indices= is set AND task_tools_discovery_index is set, discovery
|
| 229 |
+
# uses only the explicit discovery index (not all indices for probing).
|
| 230 |
+
spec = OpenRewardSpec(
|
| 231 |
+
echo_env_url, env_name="echoenvironment", indices=[0, 1, 2, 3], task_tools_discovery_index=2
|
| 232 |
+
)
|
| 233 |
+
env = spec.environment_factory()
|
| 234 |
+
# Task tools are still discovered (via index 2).
|
| 235 |
+
assert callable(env.hint)
|
| 236 |
+
assert len(spec.train_dataset) == 4
|
| 237 |
+
env._close()
|
| 238 |
+
|
| 239 |
+
def test_two_specs_get_isolated_rollout_subclasses(self, echo_env_url):
|
| 240 |
+
# Two specs (potentially against different envs with different tool
|
| 241 |
+
# sets) must each produce rollout instances with their own subclass,
|
| 242 |
+
# so neither side's bound tools clobber or shadow the other's.
|
| 243 |
+
spec_a = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=1)
|
| 244 |
+
spec_b = OpenRewardSpec(echo_env_url, env_name="echoenvironment", num_tasks=1)
|
| 245 |
+
env_a = spec_a.environment_factory()
|
| 246 |
+
env_b = spec_b.environment_factory()
|
| 247 |
+
# Each rollout is a distinct subclass of _RolloutEnvironment.
|
| 248 |
+
assert type(env_a) is not type(env_b)
|
| 249 |
+
# Both subclasses still get their own `echo` method.
|
| 250 |
+
assert callable(env_a.echo) and callable(env_b.echo)
|
| 251 |
+
env_a._close()
|
| 252 |
+
env_b._close()
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_orpo_trainer.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from datasets import load_dataset
|
| 18 |
+
from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer
|
| 19 |
+
|
| 20 |
+
from trl.experimental.orpo import ORPOConfig, ORPOTrainer
|
| 21 |
+
|
| 22 |
+
from ..testing_utils import TrlTestCase, require_peft
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TestORPOTrainer(TrlTestCase):
|
| 26 |
+
def setup_method(self):
|
| 27 |
+
self.model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 28 |
+
self.model = AutoModelForCausalLM.from_pretrained(self.model_id, dtype="float32")
|
| 29 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
|
| 30 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 31 |
+
|
| 32 |
+
# get t5 as seq2seq example:
|
| 33 |
+
model_id = "trl-internal-testing/tiny-T5ForConditionalGeneration"
|
| 34 |
+
self.t5_model = AutoModelForSeq2SeqLM.from_pretrained(model_id, dtype="float32")
|
| 35 |
+
self.t5_tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 36 |
+
|
| 37 |
+
def test_trust_remote_code(self):
|
| 38 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 39 |
+
model_id = "trl-internal-testing/tiny-RemoteForCausalLM"
|
| 40 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 41 |
+
|
| 42 |
+
with pytest.raises(ValueError, match="custom code"):
|
| 43 |
+
ORPOTrainer(
|
| 44 |
+
model=model_id,
|
| 45 |
+
args=ORPOConfig(output_dir=self.tmp_dir, report_to="none"),
|
| 46 |
+
processing_class=tokenizer,
|
| 47 |
+
train_dataset=dataset,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
trainer = ORPOTrainer(
|
| 51 |
+
model=model_id,
|
| 52 |
+
args=ORPOConfig(output_dir=self.tmp_dir, report_to="none", trust_remote_code=True),
|
| 53 |
+
processing_class=tokenizer,
|
| 54 |
+
train_dataset=dataset,
|
| 55 |
+
)
|
| 56 |
+
assert type(trainer.model).__name__ == "RemoteForCausalLM"
|
| 57 |
+
|
| 58 |
+
@pytest.mark.parametrize(
|
| 59 |
+
"name, config_name",
|
| 60 |
+
[
|
| 61 |
+
("qwen", "standard_preference"),
|
| 62 |
+
("t5", "standard_implicit_prompt_preference"),
|
| 63 |
+
("qwen", "conversational_preference"),
|
| 64 |
+
],
|
| 65 |
+
)
|
| 66 |
+
def test_orpo_trainer(self, name, config_name):
|
| 67 |
+
training_args = ORPOConfig(
|
| 68 |
+
output_dir=self.tmp_dir,
|
| 69 |
+
per_device_train_batch_size=2,
|
| 70 |
+
max_steps=3,
|
| 71 |
+
remove_unused_columns=False,
|
| 72 |
+
gradient_accumulation_steps=1,
|
| 73 |
+
learning_rate=9e-1,
|
| 74 |
+
eval_strategy="steps",
|
| 75 |
+
beta=0.1,
|
| 76 |
+
report_to="none",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
dataset = load_dataset("trl-internal-testing/zen", config_name)
|
| 80 |
+
|
| 81 |
+
if name == "qwen":
|
| 82 |
+
model = self.model
|
| 83 |
+
tokenizer = self.tokenizer
|
| 84 |
+
elif name == "t5":
|
| 85 |
+
model = self.t5_model
|
| 86 |
+
tokenizer = self.t5_tokenizer
|
| 87 |
+
training_args.is_encoder_decoder = True
|
| 88 |
+
|
| 89 |
+
trainer = ORPOTrainer(
|
| 90 |
+
model=model,
|
| 91 |
+
args=training_args,
|
| 92 |
+
processing_class=tokenizer,
|
| 93 |
+
train_dataset=dataset["train"],
|
| 94 |
+
eval_dataset=dataset["test"],
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 98 |
+
|
| 99 |
+
trainer.train()
|
| 100 |
+
|
| 101 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 102 |
+
|
| 103 |
+
# Check that the params have changed
|
| 104 |
+
for n, param in previous_trainable_params.items():
|
| 105 |
+
new_param = trainer.model.get_parameter(n)
|
| 106 |
+
if param.sum() != 0: # ignore 0 biases
|
| 107 |
+
assert not torch.equal(param, new_param)
|
| 108 |
+
|
| 109 |
+
@pytest.mark.parametrize(
|
| 110 |
+
"config_name",
|
| 111 |
+
[
|
| 112 |
+
"standard_preference",
|
| 113 |
+
"standard_implicit_prompt_preference",
|
| 114 |
+
"conversational_preference",
|
| 115 |
+
"conversational_implicit_prompt_preference",
|
| 116 |
+
],
|
| 117 |
+
)
|
| 118 |
+
@require_peft
|
| 119 |
+
def test_orpo_trainer_with_lora(self, config_name):
|
| 120 |
+
from peft import LoraConfig
|
| 121 |
+
|
| 122 |
+
lora_config = LoraConfig(
|
| 123 |
+
r=16,
|
| 124 |
+
lora_alpha=32,
|
| 125 |
+
lora_dropout=0.05,
|
| 126 |
+
bias="none",
|
| 127 |
+
task_type="CAUSAL_LM",
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
training_args = ORPOConfig(
|
| 131 |
+
output_dir=self.tmp_dir,
|
| 132 |
+
per_device_train_batch_size=2,
|
| 133 |
+
max_steps=3,
|
| 134 |
+
remove_unused_columns=False,
|
| 135 |
+
gradient_accumulation_steps=4,
|
| 136 |
+
learning_rate=9e-1,
|
| 137 |
+
eval_strategy="steps",
|
| 138 |
+
beta=0.1,
|
| 139 |
+
report_to="none",
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
dataset = load_dataset("trl-internal-testing/zen", config_name)
|
| 143 |
+
|
| 144 |
+
trainer = ORPOTrainer(
|
| 145 |
+
model=self.model,
|
| 146 |
+
args=training_args,
|
| 147 |
+
processing_class=self.tokenizer,
|
| 148 |
+
train_dataset=dataset["train"],
|
| 149 |
+
eval_dataset=dataset["test"],
|
| 150 |
+
peft_config=lora_config,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 154 |
+
|
| 155 |
+
trainer.train()
|
| 156 |
+
|
| 157 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 158 |
+
|
| 159 |
+
# Check that the params have changed
|
| 160 |
+
for n, param in previous_trainable_params.items():
|
| 161 |
+
if "lora" in n:
|
| 162 |
+
new_param = trainer.model.get_parameter(n)
|
| 163 |
+
if param.sum() != 0: # ignore 0 biases
|
| 164 |
+
assert not torch.equal(param, new_param)
|
| 165 |
+
|
| 166 |
+
def test_compute_metrics(self):
|
| 167 |
+
model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32")
|
| 168 |
+
tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
|
| 169 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 170 |
+
|
| 171 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference")
|
| 172 |
+
|
| 173 |
+
def dummy_compute_metrics(*args, **kwargs):
|
| 174 |
+
return {"test": 0.0}
|
| 175 |
+
|
| 176 |
+
training_args = ORPOConfig(
|
| 177 |
+
output_dir=self.tmp_dir,
|
| 178 |
+
remove_unused_columns=False,
|
| 179 |
+
per_device_train_batch_size=2,
|
| 180 |
+
do_eval=True,
|
| 181 |
+
eval_strategy="steps",
|
| 182 |
+
eval_steps=1,
|
| 183 |
+
per_device_eval_batch_size=2,
|
| 184 |
+
report_to="none",
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
trainer = ORPOTrainer(
|
| 188 |
+
model=model,
|
| 189 |
+
args=training_args,
|
| 190 |
+
processing_class=tokenizer,
|
| 191 |
+
train_dataset=dataset["train"],
|
| 192 |
+
eval_dataset=dataset["test"],
|
| 193 |
+
compute_metrics=dummy_compute_metrics,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
trainer.train()
|
| 197 |
+
|
| 198 |
+
assert trainer.state.log_history[-2]["eval_test"] == 0.0
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_ppo_trainer.py
ADDED
|
@@ -0,0 +1,829 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import os
|
| 17 |
+
|
| 18 |
+
import pytest
|
| 19 |
+
import torch
|
| 20 |
+
from datasets import load_dataset
|
| 21 |
+
from transformers import (
|
| 22 |
+
AutoModelForCausalLM,
|
| 23 |
+
AutoModelForSeq2SeqLM,
|
| 24 |
+
AutoModelForSequenceClassification,
|
| 25 |
+
AutoTokenizer,
|
| 26 |
+
GenerationConfig,
|
| 27 |
+
)
|
| 28 |
+
from transformers.utils import is_peft_available
|
| 29 |
+
|
| 30 |
+
from trl.experimental.ppo import (
|
| 31 |
+
AutoModelForCausalLMWithValueHead,
|
| 32 |
+
AutoModelForSeq2SeqLMWithValueHead,
|
| 33 |
+
PPOConfig,
|
| 34 |
+
PPOTrainer,
|
| 35 |
+
)
|
| 36 |
+
from trl.experimental.ppo.ppo_trainer import batch_generation, masked_mean, masked_var, masked_whiten
|
| 37 |
+
|
| 38 |
+
from ..testing_utils import (
|
| 39 |
+
TrlTestCase,
|
| 40 |
+
require_bitsandbytes,
|
| 41 |
+
require_peft,
|
| 42 |
+
require_torch_gpu_if_bnb_not_multi_backend_enabled,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if is_peft_available():
|
| 47 |
+
from peft import LoraConfig, get_peft_model
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
ALL_CAUSAL_LM_MODELS = [
|
| 51 |
+
"trl-internal-testing/tiny-BloomForCausalLM",
|
| 52 |
+
"trl-internal-testing/tiny-CohereForCausalLM",
|
| 53 |
+
# "trl-internal-testing/tiny-FalconMambaForCausalLM", # FalconMambaForCausalLM modeling seems to be broken for now
|
| 54 |
+
"trl-internal-testing/tiny-Gemma2ForCausalLM",
|
| 55 |
+
"trl-internal-testing/tiny-GemmaForCausalLM",
|
| 56 |
+
"trl-internal-testing/tiny-GPT2LMHeadModel",
|
| 57 |
+
"trl-internal-testing/tiny-GPTNeoXForCausalLM",
|
| 58 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.1",
|
| 59 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.2",
|
| 60 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3",
|
| 61 |
+
"trl-internal-testing/tiny-MistralForCausalLM-0.1",
|
| 62 |
+
"trl-internal-testing/tiny-MistralForCausalLM-0.2",
|
| 63 |
+
"trl-internal-testing/tiny-OPTForCausalLM",
|
| 64 |
+
"trl-internal-testing/tiny-Phi3ForCausalLM-3",
|
| 65 |
+
"trl-internal-testing/tiny-Phi3ForCausalLM-3.5",
|
| 66 |
+
"trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
ALL_SEQ2SEQ_MODELS = [
|
| 70 |
+
"trl-internal-testing/tiny-T5ForConditionalGeneration",
|
| 71 |
+
"trl-internal-testing/tiny-BartModel",
|
| 72 |
+
]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class TestBatchGeneration(TrlTestCase):
|
| 76 |
+
def setup_method(self):
|
| 77 |
+
# Initialize the tokenizer
|
| 78 |
+
self.model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 79 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 80 |
+
self.model = AutoModelForCausalLM.from_pretrained(self.model_id, dtype="float32").to(self.device)
|
| 81 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
|
| 82 |
+
|
| 83 |
+
self.generation_config = GenerationConfig(
|
| 84 |
+
max_new_tokens=128,
|
| 85 |
+
temperature=0.5,
|
| 86 |
+
do_sample=True,
|
| 87 |
+
top_k=0,
|
| 88 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
# Example input
|
| 92 |
+
dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train")
|
| 93 |
+
self.examples = dataset["messages"]
|
| 94 |
+
self.mini_batch_size = 3
|
| 95 |
+
|
| 96 |
+
def test_mini_batch_generation(self):
|
| 97 |
+
batch = [
|
| 98 |
+
self.tokenizer.apply_chat_template(example[:-1], add_generation_prompt=True, tokenize=False)
|
| 99 |
+
for example in self.examples
|
| 100 |
+
]
|
| 101 |
+
queries = self.tokenizer(batch, padding=True, return_tensors="pt")["input_ids"].to(self.device)
|
| 102 |
+
bs, context_length = queries.shape
|
| 103 |
+
|
| 104 |
+
query_responses, logits = batch_generation(
|
| 105 |
+
self.model, queries, self.mini_batch_size, self.tokenizer.pad_token_id, self.generation_config
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
max_length_query = query_responses.shape[1]
|
| 109 |
+
max_length_logits = max_length_query - context_length
|
| 110 |
+
|
| 111 |
+
assert max_length_query > context_length
|
| 112 |
+
assert query_responses.shape == (bs, max_length_query)
|
| 113 |
+
assert logits.shape == (bs, max_length_logits, self.model.config.vocab_size)
|
| 114 |
+
|
| 115 |
+
def test_single_batch_generation(self):
|
| 116 |
+
batch = [
|
| 117 |
+
self.tokenizer.apply_chat_template(example[:-1], add_generation_prompt=True, tokenize=False)
|
| 118 |
+
for example in self.examples
|
| 119 |
+
]
|
| 120 |
+
queries = self.tokenizer(batch, padding=True, return_tensors="pt")["input_ids"].to(self.device)
|
| 121 |
+
bs, context_length = queries.shape
|
| 122 |
+
|
| 123 |
+
query_responses, logits = batch_generation(
|
| 124 |
+
self.model, queries, bs, self.tokenizer.pad_token_id, self.generation_config
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
max_length_query = query_responses.shape[1]
|
| 128 |
+
max_length_logits = max_length_query - context_length
|
| 129 |
+
|
| 130 |
+
assert max_length_query > context_length
|
| 131 |
+
assert query_responses.shape == (bs, max_length_query)
|
| 132 |
+
assert logits.shape == (bs, max_length_logits, self.model.config.vocab_size)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class BaseTester:
|
| 136 |
+
class VHeadModelTester(TrlTestCase):
|
| 137 |
+
all_model_names = None
|
| 138 |
+
trl_model_class = None
|
| 139 |
+
transformers_model_class = None
|
| 140 |
+
|
| 141 |
+
def setup_method(self):
|
| 142 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 143 |
+
|
| 144 |
+
def test_value_head(self):
|
| 145 |
+
r"""
|
| 146 |
+
Test if the v-head is added to the model successfully
|
| 147 |
+
"""
|
| 148 |
+
for model_name in self.all_model_names:
|
| 149 |
+
model = self.trl_model_class.from_pretrained(model_name)
|
| 150 |
+
assert hasattr(model, "v_head")
|
| 151 |
+
|
| 152 |
+
def test_value_head_shape(self):
|
| 153 |
+
r"""
|
| 154 |
+
Test if the v-head has the correct shape
|
| 155 |
+
"""
|
| 156 |
+
for model_name in self.all_model_names:
|
| 157 |
+
model = self.trl_model_class.from_pretrained(model_name)
|
| 158 |
+
assert model.v_head.summary.weight.shape[0] == 1
|
| 159 |
+
|
| 160 |
+
def test_value_head_init_random(self):
|
| 161 |
+
r"""
|
| 162 |
+
Test if the v-head has been randomly initialized. We can check that by making sure the bias is different
|
| 163 |
+
than zeros by default.
|
| 164 |
+
"""
|
| 165 |
+
for model_name in self.all_model_names:
|
| 166 |
+
model = self.trl_model_class.from_pretrained(model_name)
|
| 167 |
+
assert not torch.allclose(model.v_head.summary.bias, torch.zeros_like(model.v_head.summary.bias))
|
| 168 |
+
|
| 169 |
+
def test_value_head_not_str(self):
|
| 170 |
+
r"""
|
| 171 |
+
Test if the v-head is added to the model successfully, by passing a non `PretrainedModel` as an argument to
|
| 172 |
+
`from_pretrained`.
|
| 173 |
+
"""
|
| 174 |
+
for model_name in self.all_model_names:
|
| 175 |
+
pretrained_model = self.transformers_model_class.from_pretrained(model_name)
|
| 176 |
+
model = self.trl_model_class.from_pretrained(pretrained_model)
|
| 177 |
+
assert hasattr(model, "v_head")
|
| 178 |
+
|
| 179 |
+
def test_from_save_trl(self):
|
| 180 |
+
"""
|
| 181 |
+
Test if the model can be saved and loaded from a directory and get the same weights, including the
|
| 182 |
+
additional modules (e.g. v_head)
|
| 183 |
+
"""
|
| 184 |
+
for model_name in self.all_model_names:
|
| 185 |
+
model = self.trl_model_class.from_pretrained(model_name)
|
| 186 |
+
|
| 187 |
+
model.save_pretrained(self.tmp_dir)
|
| 188 |
+
|
| 189 |
+
model_from_save = self.trl_model_class.from_pretrained(self.tmp_dir)
|
| 190 |
+
|
| 191 |
+
# Check if the weights are the same
|
| 192 |
+
for key in model_from_save.state_dict():
|
| 193 |
+
torch.testing.assert_close(model_from_save.state_dict()[key], model.state_dict()[key])
|
| 194 |
+
|
| 195 |
+
def test_from_save_trl_sharded(self):
|
| 196 |
+
"""
|
| 197 |
+
Test if the model can be saved and loaded from a directory and get the same weights - sharded case
|
| 198 |
+
"""
|
| 199 |
+
for model_name in self.all_model_names:
|
| 200 |
+
model = self.trl_model_class.from_pretrained(model_name)
|
| 201 |
+
|
| 202 |
+
model.save_pretrained(self.tmp_dir)
|
| 203 |
+
|
| 204 |
+
model_from_save = self.trl_model_class.from_pretrained(self.tmp_dir)
|
| 205 |
+
|
| 206 |
+
# Check if the weights are the same
|
| 207 |
+
for key in model_from_save.state_dict():
|
| 208 |
+
torch.testing.assert_close(model_from_save.state_dict()[key], model.state_dict()[key])
|
| 209 |
+
|
| 210 |
+
def test_from_save_transformers_sharded(self):
|
| 211 |
+
"""
|
| 212 |
+
Test if the model can be saved and loaded using transformers and get the same weights - sharded case
|
| 213 |
+
"""
|
| 214 |
+
for model_name in self.all_model_names:
|
| 215 |
+
transformers_model = self.trl_model_class.transformers_parent_class.from_pretrained(model_name)
|
| 216 |
+
|
| 217 |
+
trl_model = self.trl_model_class.from_pretrained(model_name)
|
| 218 |
+
|
| 219 |
+
trl_model.save_pretrained(self.tmp_dir, max_shard_size="1MB")
|
| 220 |
+
transformers_model_from_save = self.trl_model_class.transformers_parent_class.from_pretrained(
|
| 221 |
+
self.tmp_dir
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
# Check if the weights are the same
|
| 225 |
+
for key in transformers_model.state_dict():
|
| 226 |
+
torch.testing.assert_close(
|
| 227 |
+
transformers_model_from_save.state_dict()[key], transformers_model.state_dict()[key]
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
def test_from_save_transformers(self):
|
| 231 |
+
"""
|
| 232 |
+
Test if the model can be saved and loaded using transformers and get the same weights. We override the test
|
| 233 |
+
of the super class to check if the weights are the same.
|
| 234 |
+
"""
|
| 235 |
+
for model_name in self.all_model_names:
|
| 236 |
+
transformers_model = self.trl_model_class.transformers_parent_class.from_pretrained(model_name)
|
| 237 |
+
|
| 238 |
+
trl_model = self.trl_model_class.from_pretrained(model_name)
|
| 239 |
+
|
| 240 |
+
trl_model.save_pretrained(self.tmp_dir)
|
| 241 |
+
transformers_model_from_save = self.trl_model_class.transformers_parent_class.from_pretrained(
|
| 242 |
+
self.tmp_dir
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# Check if the weights are the same
|
| 246 |
+
for key in transformers_model.state_dict():
|
| 247 |
+
torch.testing.assert_close(
|
| 248 |
+
transformers_model_from_save.state_dict()[key], transformers_model.state_dict()[key]
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
# Check if the trl model has the same keys as the transformers model
|
| 252 |
+
# except the v_head
|
| 253 |
+
for key in trl_model.state_dict():
|
| 254 |
+
if "v_head" not in key:
|
| 255 |
+
assert key in transformers_model.state_dict()
|
| 256 |
+
# check if the weights are the same
|
| 257 |
+
torch.testing.assert_close(trl_model.state_dict()[key], transformers_model.state_dict()[key])
|
| 258 |
+
|
| 259 |
+
# check if they have the same modules
|
| 260 |
+
assert set(transformers_model_from_save.state_dict().keys()) == set(
|
| 261 |
+
transformers_model.state_dict().keys()
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class TestCausalLMValueHeadModel(BaseTester.VHeadModelTester, TrlTestCase):
|
| 266 |
+
"""
|
| 267 |
+
Testing suite for v-head models.
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
all_model_names = ALL_CAUSAL_LM_MODELS
|
| 271 |
+
trl_model_class = AutoModelForCausalLMWithValueHead
|
| 272 |
+
transformers_model_class = AutoModelForCausalLM
|
| 273 |
+
|
| 274 |
+
def teardown_method(self):
|
| 275 |
+
# free memory
|
| 276 |
+
gc.collect()
|
| 277 |
+
|
| 278 |
+
def test_inference(self):
|
| 279 |
+
r"""
|
| 280 |
+
Test if the model can be used for inference and outputs 3 values
|
| 281 |
+
- logits, loss, and value states
|
| 282 |
+
"""
|
| 283 |
+
EXPECTED_OUTPUT_SIZE = 3
|
| 284 |
+
|
| 285 |
+
for model_name in self.all_model_names:
|
| 286 |
+
model = self.trl_model_class.from_pretrained(model_name).to(self.device)
|
| 287 |
+
input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], device=self.device)
|
| 288 |
+
outputs = model(input_ids)
|
| 289 |
+
|
| 290 |
+
# Check if the outputs are of the right size - here
|
| 291 |
+
# we always output 3 values - logits, loss, and value states
|
| 292 |
+
assert len(outputs) == EXPECTED_OUTPUT_SIZE
|
| 293 |
+
|
| 294 |
+
def test_dropout_config(self):
|
| 295 |
+
r"""
|
| 296 |
+
Test if we instantiate a model by adding `summary_drop_prob` to the config it will be added to the v_head
|
| 297 |
+
"""
|
| 298 |
+
for model_name in self.all_model_names:
|
| 299 |
+
pretrained_model = self.transformers_model_class.from_pretrained(model_name)
|
| 300 |
+
pretrained_model.config.summary_dropout_prob = 0.5
|
| 301 |
+
model = self.trl_model_class.from_pretrained(pretrained_model)
|
| 302 |
+
|
| 303 |
+
# Check if v head of the model has the same dropout as the config
|
| 304 |
+
assert model.v_head.dropout.p == pretrained_model.config.summary_dropout_prob
|
| 305 |
+
|
| 306 |
+
def test_dropout_kwargs(self):
|
| 307 |
+
r"""
|
| 308 |
+
Test if we instantiate a model by adding `summary_drop_prob` to the config it will be added to the v_head
|
| 309 |
+
"""
|
| 310 |
+
for model_name in self.all_model_names:
|
| 311 |
+
v_head_kwargs = {"summary_dropout_prob": 0.5}
|
| 312 |
+
|
| 313 |
+
model = self.trl_model_class.from_pretrained(model_name, **v_head_kwargs)
|
| 314 |
+
|
| 315 |
+
# Check if v head of the model has the same dropout as the config
|
| 316 |
+
assert model.v_head.dropout.p == 0.5
|
| 317 |
+
|
| 318 |
+
model = self.trl_model_class.from_pretrained(model_name, summary_dropout_prob=0.5)
|
| 319 |
+
|
| 320 |
+
# Check if v head of the model has the same dropout as the config
|
| 321 |
+
assert model.v_head.dropout.p == 0.5
|
| 322 |
+
|
| 323 |
+
@pytest.mark.parametrize("model_name", ALL_CAUSAL_LM_MODELS)
|
| 324 |
+
def test_generate(self, model_name):
|
| 325 |
+
r"""
|
| 326 |
+
Test if `generate` works for every model
|
| 327 |
+
"""
|
| 328 |
+
generation_config = GenerationConfig(max_new_tokens=9)
|
| 329 |
+
model = self.trl_model_class.from_pretrained(model_name).to(self.device)
|
| 330 |
+
input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], device=self.device)
|
| 331 |
+
|
| 332 |
+
# Just check if the generation works
|
| 333 |
+
_ = model.generate(input_ids, generation_config=generation_config)
|
| 334 |
+
|
| 335 |
+
def test_transformers_bf16_kwargs(self):
|
| 336 |
+
r"""
|
| 337 |
+
Test if the transformers kwargs are correctly passed. Here we check that loading a model in half precision
|
| 338 |
+
works as expected, i.e. the weights of the `pretrained_model` attribute is loaded in half precision and you can
|
| 339 |
+
run a dummy forward pass without any issue.
|
| 340 |
+
"""
|
| 341 |
+
for model_name in self.all_model_names:
|
| 342 |
+
trl_model = self.trl_model_class.from_pretrained(model_name, dtype=torch.bfloat16).to(self.device)
|
| 343 |
+
|
| 344 |
+
lm_head_namings = ["lm_head", "embed_out", "output_layer"]
|
| 345 |
+
|
| 346 |
+
assert any(hasattr(trl_model.pretrained_model, lm_head_naming) for lm_head_naming in lm_head_namings), (
|
| 347 |
+
"Can't test the model because it doesn't have any of the expected lm_head namings"
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
for lm_head_naming in lm_head_namings:
|
| 351 |
+
if hasattr(trl_model.pretrained_model, lm_head_naming):
|
| 352 |
+
assert getattr(trl_model.pretrained_model, lm_head_naming).weight.dtype == torch.bfloat16
|
| 353 |
+
|
| 354 |
+
dummy_input = torch.LongTensor([[0, 1, 0, 1]]).to(self.device)
|
| 355 |
+
|
| 356 |
+
# check dummy forward pass works in half precision
|
| 357 |
+
_ = trl_model(dummy_input)
|
| 358 |
+
|
| 359 |
+
@pytest.mark.skip(reason="This test needs to be run manually due to HF token issue.")
|
| 360 |
+
def test_push_to_hub(self):
|
| 361 |
+
for model_name in self.all_model_names:
|
| 362 |
+
model = AutoModelForCausalLMWithValueHead.from_pretrained(model_name)
|
| 363 |
+
if "sharded" in model_name:
|
| 364 |
+
model.push_to_hub(model_name + "-ppo", use_auth_token=True, max_shard_size="1MB")
|
| 365 |
+
else:
|
| 366 |
+
model.push_to_hub(model_name + "-ppo", use_auth_token=True)
|
| 367 |
+
|
| 368 |
+
model_from_pretrained = AutoModelForCausalLMWithValueHead.from_pretrained(model_name + "-ppo")
|
| 369 |
+
# check all keys
|
| 370 |
+
assert model.state_dict().keys() == model_from_pretrained.state_dict().keys()
|
| 371 |
+
|
| 372 |
+
for name, param in model.state_dict().items():
|
| 373 |
+
(
|
| 374 |
+
torch.testing.assert_close(param, model_from_pretrained.state_dict()[name]),
|
| 375 |
+
(f"Parameter {name} is not the same after push_to_hub and from_pretrained"),
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
class TestSeq2SeqValueHeadModel(BaseTester.VHeadModelTester, TrlTestCase):
|
| 380 |
+
"""
|
| 381 |
+
Testing suite for v-head models.
|
| 382 |
+
"""
|
| 383 |
+
|
| 384 |
+
all_model_names = ALL_SEQ2SEQ_MODELS
|
| 385 |
+
trl_model_class = AutoModelForSeq2SeqLMWithValueHead
|
| 386 |
+
transformers_model_class = AutoModelForSeq2SeqLM
|
| 387 |
+
|
| 388 |
+
def teardown_method(self):
|
| 389 |
+
# free memory
|
| 390 |
+
gc.collect()
|
| 391 |
+
|
| 392 |
+
def test_inference(self):
|
| 393 |
+
r"""
|
| 394 |
+
Test if the model can be used for inference and outputs 3 values
|
| 395 |
+
- logits, loss, and value states
|
| 396 |
+
"""
|
| 397 |
+
EXPECTED_OUTPUT_SIZE = 3
|
| 398 |
+
|
| 399 |
+
for model_name in self.all_model_names:
|
| 400 |
+
model = self.trl_model_class.from_pretrained(model_name).to(self.device)
|
| 401 |
+
input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], device=self.device)
|
| 402 |
+
decoder_input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], device=self.device)
|
| 403 |
+
outputs = model(input_ids, decoder_input_ids=decoder_input_ids)
|
| 404 |
+
|
| 405 |
+
# Check if the outputs are of the right size - here
|
| 406 |
+
# we always output 3 values - logits, loss, and value states
|
| 407 |
+
assert len(outputs) == EXPECTED_OUTPUT_SIZE
|
| 408 |
+
|
| 409 |
+
def test_dropout_config(self):
|
| 410 |
+
r"""
|
| 411 |
+
Test if we instantiate a model by adding `summary_drop_prob` to the config it will be added to the v_head
|
| 412 |
+
"""
|
| 413 |
+
for model_name in self.all_model_names:
|
| 414 |
+
pretrained_model = self.transformers_model_class.from_pretrained(model_name)
|
| 415 |
+
pretrained_model.config.summary_dropout_prob = 0.5
|
| 416 |
+
model = self.trl_model_class.from_pretrained(pretrained_model)
|
| 417 |
+
|
| 418 |
+
# Check if v head of the model has the same dropout as the config
|
| 419 |
+
assert model.v_head.dropout.p == pretrained_model.config.summary_dropout_prob
|
| 420 |
+
|
| 421 |
+
def test_dropout_kwargs(self):
|
| 422 |
+
r"""
|
| 423 |
+
Test if we instantiate a model by adding `summary_drop_prob` to the config it will be added to the v_head
|
| 424 |
+
"""
|
| 425 |
+
for model_name in self.all_model_names:
|
| 426 |
+
v_head_kwargs = {"summary_dropout_prob": 0.5}
|
| 427 |
+
|
| 428 |
+
model = self.trl_model_class.from_pretrained(model_name, **v_head_kwargs)
|
| 429 |
+
|
| 430 |
+
# Check if v head of the model has the same dropout as the config
|
| 431 |
+
assert model.v_head.dropout.p == 0.5
|
| 432 |
+
|
| 433 |
+
model = self.trl_model_class.from_pretrained(model_name, summary_dropout_prob=0.5)
|
| 434 |
+
|
| 435 |
+
# Check if v head of the model has the same dropout as the config
|
| 436 |
+
assert model.v_head.dropout.p == 0.5
|
| 437 |
+
|
| 438 |
+
@pytest.mark.parametrize("model_name", ALL_SEQ2SEQ_MODELS)
|
| 439 |
+
def test_generate(self, model_name):
|
| 440 |
+
r"""
|
| 441 |
+
Test if `generate` works for every model
|
| 442 |
+
"""
|
| 443 |
+
generation_config = GenerationConfig(max_new_tokens=9)
|
| 444 |
+
model = self.trl_model_class.from_pretrained(model_name).to(self.device)
|
| 445 |
+
input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], device=self.device)
|
| 446 |
+
decoder_input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], device=self.device)
|
| 447 |
+
|
| 448 |
+
# Just check if the generation works
|
| 449 |
+
_ = model.generate(input_ids, decoder_input_ids=decoder_input_ids, generation_config=generation_config)
|
| 450 |
+
|
| 451 |
+
@pytest.mark.skip(reason="This test needs to be run manually due to HF token issue.")
|
| 452 |
+
def test_push_to_hub(self):
|
| 453 |
+
for model_name in self.all_model_names:
|
| 454 |
+
model = self.trl_model_class.from_pretrained(model_name)
|
| 455 |
+
if "sharded" in model_name:
|
| 456 |
+
model.push_to_hub(model_name + "-ppo", use_auth_token=True, max_shard_size="1MB")
|
| 457 |
+
else:
|
| 458 |
+
model.push_to_hub(model_name + "-ppo", use_auth_token=True)
|
| 459 |
+
|
| 460 |
+
model_from_pretrained = self.trl_model_class.from_pretrained(model_name + "-ppo")
|
| 461 |
+
# check all keys
|
| 462 |
+
assert model.state_dict().keys() == model_from_pretrained.state_dict().keys()
|
| 463 |
+
|
| 464 |
+
for name, param in model.state_dict().items():
|
| 465 |
+
(
|
| 466 |
+
torch.testing.assert_close(param, model_from_pretrained.state_dict()[name]),
|
| 467 |
+
(f"Parameter {name} is not the same after push_to_hub and from_pretrained"),
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
def test_transformers_bf16_kwargs(self):
|
| 471 |
+
r"""
|
| 472 |
+
Test if the transformers kwargs are correctly passed. Here we check that loading a model in half precision
|
| 473 |
+
works as expected, i.e. the weights of the `pretrained_model` attribute is loaded in half precision and you can
|
| 474 |
+
run a dummy forward pass without any issue.
|
| 475 |
+
"""
|
| 476 |
+
for model_name in self.all_model_names:
|
| 477 |
+
trl_model = self.trl_model_class.from_pretrained(model_name, dtype=torch.bfloat16).to(self.device)
|
| 478 |
+
|
| 479 |
+
lm_head_namings = self.trl_model_class.lm_head_namings
|
| 480 |
+
|
| 481 |
+
assert any(hasattr(trl_model.pretrained_model, lm_head_naming) for lm_head_naming in lm_head_namings)
|
| 482 |
+
|
| 483 |
+
for lm_head_naming in lm_head_namings:
|
| 484 |
+
if hasattr(trl_model.pretrained_model, lm_head_naming):
|
| 485 |
+
assert getattr(trl_model.pretrained_model, lm_head_naming).weight.dtype == torch.bfloat16
|
| 486 |
+
|
| 487 |
+
dummy_input = torch.LongTensor([[0, 1, 0, 1]]).to(self.device)
|
| 488 |
+
|
| 489 |
+
# check dummy forward pass works in half precision
|
| 490 |
+
_ = trl_model(input_ids=dummy_input, decoder_input_ids=dummy_input)
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
@require_peft
|
| 494 |
+
class TestPeftModel(TrlTestCase):
|
| 495 |
+
def setup_method(self):
|
| 496 |
+
self.causal_lm_model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 497 |
+
self.lora_config = LoraConfig(
|
| 498 |
+
r=16,
|
| 499 |
+
lora_alpha=32,
|
| 500 |
+
lora_dropout=0.05,
|
| 501 |
+
bias="none",
|
| 502 |
+
task_type="CAUSAL_LM",
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
def test_create_peft_model(self):
|
| 506 |
+
r"""
|
| 507 |
+
Simply creates a peft model and checks that it can be loaded.
|
| 508 |
+
"""
|
| 509 |
+
causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id)
|
| 510 |
+
pretrained_model = get_peft_model(causal_lm_model, self.lora_config)
|
| 511 |
+
|
| 512 |
+
_ = AutoModelForCausalLMWithValueHead.from_pretrained(pretrained_model)
|
| 513 |
+
|
| 514 |
+
def test_peft_requires_grad(self):
|
| 515 |
+
r"""
|
| 516 |
+
Check that the value head of the returned model has requires_grad=True.
|
| 517 |
+
"""
|
| 518 |
+
causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id)
|
| 519 |
+
pretrained_model = get_peft_model(causal_lm_model, self.lora_config)
|
| 520 |
+
|
| 521 |
+
model = AutoModelForCausalLMWithValueHead.from_pretrained(pretrained_model)
|
| 522 |
+
|
| 523 |
+
# Check that the value head has requires_grad=True
|
| 524 |
+
assert model.v_head.summary.weight.requires_grad
|
| 525 |
+
|
| 526 |
+
def test_check_peft_model_nb_trainable_params(self):
|
| 527 |
+
r"""
|
| 528 |
+
Check that the number of trainable parameters is correct.
|
| 529 |
+
"""
|
| 530 |
+
causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id)
|
| 531 |
+
pretrained_model = get_peft_model(causal_lm_model, self.lora_config)
|
| 532 |
+
|
| 533 |
+
model = AutoModelForCausalLMWithValueHead.from_pretrained(pretrained_model)
|
| 534 |
+
|
| 535 |
+
# Check that the number of trainable parameters is correct
|
| 536 |
+
nb_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 537 |
+
assert nb_trainable_params == 905
|
| 538 |
+
|
| 539 |
+
# Check that the number of trainable param for the non-peft model is correct
|
| 540 |
+
non_peft_model = AutoModelForCausalLMWithValueHead.from_pretrained(self.causal_lm_model_id)
|
| 541 |
+
nb_trainable_params = sum(p.numel() for p in non_peft_model.parameters() if p.requires_grad)
|
| 542 |
+
assert nb_trainable_params == 2428641
|
| 543 |
+
|
| 544 |
+
def test_create_peft_model_from_config(self):
|
| 545 |
+
r"""
|
| 546 |
+
Simply creates a peft model and checks that it can be loaded.
|
| 547 |
+
"""
|
| 548 |
+
trl_model = AutoModelForCausalLMWithValueHead.from_pretrained(
|
| 549 |
+
self.causal_lm_model_id, peft_config=self.lora_config
|
| 550 |
+
)
|
| 551 |
+
# Check that the number of trainable parameters is correct
|
| 552 |
+
nb_trainable_params = sum(p.numel() for p in trl_model.parameters() if p.requires_grad)
|
| 553 |
+
assert nb_trainable_params == 905
|
| 554 |
+
|
| 555 |
+
causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id)
|
| 556 |
+
trl_model = AutoModelForCausalLMWithValueHead.from_pretrained(causal_lm_model, peft_config=self.lora_config)
|
| 557 |
+
# Check that the number of trainable parameters is correct
|
| 558 |
+
nb_trainable_params = sum(p.numel() for p in trl_model.parameters() if p.requires_grad)
|
| 559 |
+
assert nb_trainable_params == 905
|
| 560 |
+
|
| 561 |
+
@require_bitsandbytes
|
| 562 |
+
@require_torch_gpu_if_bnb_not_multi_backend_enabled
|
| 563 |
+
def test_create_bnb_peft_model_from_config(self):
|
| 564 |
+
r"""
|
| 565 |
+
Simply creates a peft model and checks that it can be loaded.
|
| 566 |
+
"""
|
| 567 |
+
from bitsandbytes.nn import Linear8bitLt
|
| 568 |
+
from transformers import BitsAndBytesConfig
|
| 569 |
+
|
| 570 |
+
trl_model = AutoModelForCausalLMWithValueHead.from_pretrained(
|
| 571 |
+
self.causal_lm_model_id,
|
| 572 |
+
peft_config=self.lora_config,
|
| 573 |
+
quantization_config=BitsAndBytesConfig(load_in_8bit=True),
|
| 574 |
+
)
|
| 575 |
+
# Check that the number of trainable parameters is correct
|
| 576 |
+
nb_trainable_params = sum(p.numel() for p in trl_model.parameters() if p.requires_grad)
|
| 577 |
+
assert nb_trainable_params == 905
|
| 578 |
+
assert isinstance(trl_model.pretrained_model.model.model.layers[0].mlp.gate_proj, Linear8bitLt)
|
| 579 |
+
|
| 580 |
+
causal_lm_model = AutoModelForCausalLM.from_pretrained(
|
| 581 |
+
self.causal_lm_model_id, quantization_config=BitsAndBytesConfig(load_in_8bit=True), device_map="auto"
|
| 582 |
+
)
|
| 583 |
+
trl_model = AutoModelForCausalLMWithValueHead.from_pretrained(causal_lm_model, peft_config=self.lora_config)
|
| 584 |
+
# Check that the number of trainable parameters is correct
|
| 585 |
+
nb_trainable_params = sum(p.numel() for p in trl_model.parameters() if p.requires_grad)
|
| 586 |
+
assert nb_trainable_params == 905
|
| 587 |
+
assert isinstance(trl_model.pretrained_model.model.model.layers[0].mlp.gate_proj, Linear8bitLt)
|
| 588 |
+
|
| 589 |
+
def test_save_pretrained_peft(self):
|
| 590 |
+
r"""
|
| 591 |
+
Check that the model can be saved and loaded properly.
|
| 592 |
+
"""
|
| 593 |
+
causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id)
|
| 594 |
+
pretrained_model = get_peft_model(causal_lm_model, self.lora_config)
|
| 595 |
+
|
| 596 |
+
model = AutoModelForCausalLMWithValueHead.from_pretrained(pretrained_model)
|
| 597 |
+
|
| 598 |
+
model.save_pretrained(self.tmp_dir)
|
| 599 |
+
|
| 600 |
+
# check that the files `adapter_model.safetensors` and `adapter_config.json` are in the directory
|
| 601 |
+
assert os.path.isfile(f"{self.tmp_dir}/adapter_model.safetensors"), (
|
| 602 |
+
f"{self.tmp_dir}/adapter_model.safetensors does not exist"
|
| 603 |
+
)
|
| 604 |
+
assert os.path.exists(f"{self.tmp_dir}/adapter_config.json"), (
|
| 605 |
+
f"{self.tmp_dir}/adapter_config.json does not exist"
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
# check also for `pytorch_model.bin` and make sure it only contains `v_head` weights
|
| 609 |
+
assert os.path.exists(f"{self.tmp_dir}/pytorch_model.bin"), f"{self.tmp_dir}/pytorch_model.bin does not exist"
|
| 610 |
+
|
| 611 |
+
# check that only keys that starts with `v_head` are in the dict
|
| 612 |
+
maybe_v_head = torch.load(f"{self.tmp_dir}/pytorch_model.bin", weights_only=True)
|
| 613 |
+
assert all(k.startswith("v_head") for k in maybe_v_head.keys()), (
|
| 614 |
+
f"keys in {self.tmp_dir}/pytorch_model.bin do not start with `v_head`"
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
model_from_pretrained = AutoModelForCausalLMWithValueHead.from_pretrained(self.tmp_dir)
|
| 618 |
+
|
| 619 |
+
# check all the weights are the same
|
| 620 |
+
for p1, p2 in zip(model.named_parameters(), model_from_pretrained.named_parameters(), strict=True):
|
| 621 |
+
torch.testing.assert_close(p1[1], p2[1], msg=f"{p1[0]} != {p2[0]}")
|
| 622 |
+
|
| 623 |
+
def test_load_pretrained_peft(self):
|
| 624 |
+
r"""
|
| 625 |
+
Check that the model saved with peft class interface can be loaded properly.
|
| 626 |
+
"""
|
| 627 |
+
causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id)
|
| 628 |
+
pretrained_model = get_peft_model(causal_lm_model, self.lora_config)
|
| 629 |
+
|
| 630 |
+
model = AutoModelForCausalLMWithValueHead.from_pretrained(pretrained_model)
|
| 631 |
+
|
| 632 |
+
pretrained_model.save_pretrained(self.tmp_dir)
|
| 633 |
+
model_from_pretrained = AutoModelForCausalLMWithValueHead.from_pretrained(self.tmp_dir)
|
| 634 |
+
|
| 635 |
+
# check that the files `adapter_model.safetensors` and `adapter_config.json` are in the directory
|
| 636 |
+
assert os.path.isfile(f"{self.tmp_dir}/adapter_model.safetensors"), (
|
| 637 |
+
f"{self.tmp_dir}/adapter_model.safetensors does not exist"
|
| 638 |
+
)
|
| 639 |
+
assert os.path.exists(f"{self.tmp_dir}/adapter_config.json"), (
|
| 640 |
+
f"{self.tmp_dir}/adapter_config.json does not exist"
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
# check all the weights are the same
|
| 644 |
+
for p1, p2 in zip(model.named_parameters(), model_from_pretrained.named_parameters(), strict=True):
|
| 645 |
+
if p1[0] not in ["v_head.summary.weight", "v_head.summary.bias"]:
|
| 646 |
+
torch.testing.assert_close(p1[1], p2[1], msg=f"{p1[0]} != {p2[0]}")
|
| 647 |
+
|
| 648 |
+
def test_continue_training_peft_model(self):
|
| 649 |
+
r"""
|
| 650 |
+
Load peft and checks that it can continue training.
|
| 651 |
+
"""
|
| 652 |
+
causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id)
|
| 653 |
+
pretrained_model = get_peft_model(causal_lm_model, self.lora_config)
|
| 654 |
+
|
| 655 |
+
pretrained_model.save_pretrained(self.tmp_dir)
|
| 656 |
+
# set is_trainable to True
|
| 657 |
+
model = AutoModelForCausalLMWithValueHead.from_pretrained(self.tmp_dir, is_trainable=True)
|
| 658 |
+
# Check that the number of trainable parameters is correct
|
| 659 |
+
nb_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 660 |
+
assert nb_trainable_params == 905
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
class TestCore(TrlTestCase):
|
| 664 |
+
"""
|
| 665 |
+
A wrapper class for testing core utils functions
|
| 666 |
+
"""
|
| 667 |
+
|
| 668 |
+
def setup_method(self):
|
| 669 |
+
self.test_input = torch.Tensor([1, 2, 3, 4])
|
| 670 |
+
self.test_mask = torch.Tensor([0, 1, 1, 0])
|
| 671 |
+
self.test_input_unmasked = self.test_input[1:3]
|
| 672 |
+
|
| 673 |
+
def test_masked_mean(self):
|
| 674 |
+
assert torch.mean(self.test_input_unmasked) == masked_mean(self.test_input, self.test_mask)
|
| 675 |
+
|
| 676 |
+
def test_masked_var(self):
|
| 677 |
+
assert torch.var(self.test_input_unmasked) == masked_var(self.test_input, self.test_mask)
|
| 678 |
+
|
| 679 |
+
def test_masked_whiten(self):
|
| 680 |
+
def whiten(values: torch.Tensor) -> torch.Tensor:
|
| 681 |
+
mean, var = torch.mean(values), torch.var(values)
|
| 682 |
+
return (values - mean) * torch.rsqrt(var + 1e-8)
|
| 683 |
+
|
| 684 |
+
whiten_unmasked = whiten(self.test_input_unmasked)
|
| 685 |
+
whiten_masked = masked_whiten(self.test_input, self.test_mask)[1:3]
|
| 686 |
+
diffs = (whiten_unmasked - whiten_masked).sum()
|
| 687 |
+
assert abs(diffs.item()) < 0.00001
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
class TestPPOTrainer(TrlTestCase):
|
| 691 |
+
def setup_method(self):
|
| 692 |
+
# Set up the models and tokenizer using the test model
|
| 693 |
+
self.model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 694 |
+
self.model = AutoModelForCausalLM.from_pretrained(self.model_id, dtype="float32")
|
| 695 |
+
self.ref_model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 696 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id, padding_side="left")
|
| 697 |
+
self.tokenizer.add_special_tokens({"pad_token": "[PAD]"})
|
| 698 |
+
|
| 699 |
+
# Add reward and value models as in ppo.py
|
| 700 |
+
reward_model_id = "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"
|
| 701 |
+
self.value_model = AutoModelForSequenceClassification.from_pretrained(reward_model_id, num_labels=1)
|
| 702 |
+
self.reward_model = AutoModelForSequenceClassification.from_pretrained(reward_model_id, num_labels=1)
|
| 703 |
+
|
| 704 |
+
# Load dataset
|
| 705 |
+
raw_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only")
|
| 706 |
+
|
| 707 |
+
def tokenize(example, tokenizer):
|
| 708 |
+
tokenized = tokenizer(text=example["prompt"])
|
| 709 |
+
if tokenizer.eos_token_id is not None and tokenized["input_ids"][-1] != tokenizer.eos_token_id:
|
| 710 |
+
tokenized["input_ids"] = tokenized["input_ids"] + [tokenizer.eos_token_id]
|
| 711 |
+
tokenized["attention_mask"] = tokenized["attention_mask"] + [1]
|
| 712 |
+
return tokenized
|
| 713 |
+
|
| 714 |
+
self.raw_dataset = raw_dataset.map(tokenize, fn_kwargs={"tokenizer": self.tokenizer}, remove_columns="prompt")
|
| 715 |
+
|
| 716 |
+
def test_basic_training(self):
|
| 717 |
+
"""Test basic PPO training configuration and verify model updates."""
|
| 718 |
+
# Capture initial weights
|
| 719 |
+
initial_critic_weights = {}
|
| 720 |
+
initial_policy_weights = {}
|
| 721 |
+
for name, param in self.value_model.named_parameters():
|
| 722 |
+
initial_critic_weights[name] = param.clone().detach()
|
| 723 |
+
for name, param in self.model.named_parameters():
|
| 724 |
+
initial_policy_weights[name] = param.clone().detach()
|
| 725 |
+
|
| 726 |
+
# Configure training args similar to example script
|
| 727 |
+
training_args = PPOConfig(
|
| 728 |
+
output_dir=self.tmp_dir,
|
| 729 |
+
per_device_train_batch_size=4,
|
| 730 |
+
per_device_eval_batch_size=2,
|
| 731 |
+
num_ppo_epochs=2, # Decrease number of PPO epochs to speed up test
|
| 732 |
+
report_to="none",
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
# Create trainer
|
| 736 |
+
trainer = PPOTrainer(
|
| 737 |
+
args=training_args,
|
| 738 |
+
processing_class=self.tokenizer,
|
| 739 |
+
model=self.model,
|
| 740 |
+
ref_model=self.ref_model,
|
| 741 |
+
reward_model=self.reward_model,
|
| 742 |
+
value_model=self.value_model,
|
| 743 |
+
train_dataset=self.raw_dataset["train"],
|
| 744 |
+
eval_dataset=self.raw_dataset["test"],
|
| 745 |
+
)
|
| 746 |
+
|
| 747 |
+
# Train
|
| 748 |
+
trainer.train()
|
| 749 |
+
|
| 750 |
+
# Check if critic weights have been updated
|
| 751 |
+
critic_weights_updated = False
|
| 752 |
+
for name, param in trainer.model.value_model.named_parameters():
|
| 753 |
+
if not torch.equal(initial_critic_weights[name], param.to("cpu")):
|
| 754 |
+
critic_weights_updated = True
|
| 755 |
+
break
|
| 756 |
+
|
| 757 |
+
# Check if policy weights have been updated
|
| 758 |
+
policy_weights_updated = False
|
| 759 |
+
for name, param in trainer.model.policy.named_parameters():
|
| 760 |
+
if not torch.equal(initial_policy_weights[name], param.to("cpu")):
|
| 761 |
+
policy_weights_updated = True
|
| 762 |
+
break
|
| 763 |
+
|
| 764 |
+
assert critic_weights_updated, "Critic weights were not updated during training"
|
| 765 |
+
assert policy_weights_updated, "Policy weights were not updated during training"
|
| 766 |
+
|
| 767 |
+
@require_peft
|
| 768 |
+
def test_peft_training(self):
|
| 769 |
+
"""Test PPO training with PEFT configuration and verify model updates."""
|
| 770 |
+
# Capture initial weights
|
| 771 |
+
initial_critic_weights = {}
|
| 772 |
+
initial_policy_weights = {}
|
| 773 |
+
for name, param in self.value_model.named_parameters():
|
| 774 |
+
initial_critic_weights[name] = param.clone().detach()
|
| 775 |
+
for name, param in self.model.named_parameters():
|
| 776 |
+
initial_policy_weights[name] = param.clone().detach()
|
| 777 |
+
|
| 778 |
+
# Configure training args
|
| 779 |
+
training_args = PPOConfig(
|
| 780 |
+
output_dir=self.tmp_dir,
|
| 781 |
+
per_device_train_batch_size=4,
|
| 782 |
+
per_device_eval_batch_size=2,
|
| 783 |
+
num_ppo_epochs=2, # Decrease number of PPO epochs to speed up test
|
| 784 |
+
report_to="none",
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
# Configure PEFT
|
| 788 |
+
peft_config = LoraConfig(
|
| 789 |
+
r=32,
|
| 790 |
+
lora_alpha=16,
|
| 791 |
+
lora_dropout=0.05,
|
| 792 |
+
bias="none",
|
| 793 |
+
task_type="CAUSAL_LM",
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
# Create trainer with PEFT
|
| 797 |
+
trainer = PPOTrainer(
|
| 798 |
+
args=training_args,
|
| 799 |
+
processing_class=self.tokenizer,
|
| 800 |
+
model=self.model,
|
| 801 |
+
ref_model=None,
|
| 802 |
+
reward_model=self.reward_model,
|
| 803 |
+
value_model=self.value_model,
|
| 804 |
+
train_dataset=self.raw_dataset["train"],
|
| 805 |
+
eval_dataset=self.raw_dataset["test"],
|
| 806 |
+
peft_config=peft_config,
|
| 807 |
+
)
|
| 808 |
+
|
| 809 |
+
# Train
|
| 810 |
+
trainer.train()
|
| 811 |
+
|
| 812 |
+
# Check if critic weights have been updated
|
| 813 |
+
critic_weights_updated = False
|
| 814 |
+
for name, param in trainer.model.value_model.named_parameters():
|
| 815 |
+
if name in initial_critic_weights and not torch.equal(initial_critic_weights[name], param.to("cpu")):
|
| 816 |
+
critic_weights_updated = True
|
| 817 |
+
break
|
| 818 |
+
|
| 819 |
+
# Check if policy weights have been updated - for PEFT we check the LoRA weights
|
| 820 |
+
policy_weights_updated = False
|
| 821 |
+
for name, param in trainer.model.policy.named_parameters():
|
| 822 |
+
if "lora" in name.lower() and param.requires_grad: # Only check LoRA weights
|
| 823 |
+
# New weights should be non-zero if they've been updated
|
| 824 |
+
if not torch.allclose(param, torch.zeros_like(param)):
|
| 825 |
+
policy_weights_updated = True
|
| 826 |
+
break
|
| 827 |
+
|
| 828 |
+
assert critic_weights_updated, "Critic weights were not updated during training"
|
| 829 |
+
assert policy_weights_updated, "Policy LoRA weights were not updated during training"
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_prm_trainer.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 MagicMock
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pytest
|
| 19 |
+
import torch
|
| 20 |
+
from datasets import Dataset, load_dataset
|
| 21 |
+
from transformers import AutoModelForTokenClassification, AutoTokenizer, PreTrainedTokenizerBase
|
| 22 |
+
from transformers.utils import is_peft_available
|
| 23 |
+
|
| 24 |
+
from trl.experimental.prm import PRMConfig, PRMTrainer
|
| 25 |
+
from trl.experimental.prm.prm_trainer import compute_accuracy
|
| 26 |
+
|
| 27 |
+
from ..testing_utils import TrlTestCase, require_peft
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_peft_available():
|
| 31 |
+
from peft import LoraConfig, TaskType
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class TestComputeAccuracy(TrlTestCase):
|
| 35 |
+
def test_token_classification_task(self):
|
| 36 |
+
eval_pred = (
|
| 37 |
+
np.array(
|
| 38 |
+
[
|
| 39 |
+
[[0.1, 0.9], [0.8, 0.2]], # Batch 1
|
| 40 |
+
[[0.3, 0.7], [0.6, 0.4]], # Batch 2
|
| 41 |
+
]
|
| 42 |
+
),
|
| 43 |
+
np.array([[0, 1], [1, 0]]),
|
| 44 |
+
)
|
| 45 |
+
expected_accuracy = 0.5 # 2 matches, 2 mismatches
|
| 46 |
+
result = compute_accuracy(eval_pred)
|
| 47 |
+
assert round(abs(result["accuracy"] - expected_accuracy), 7) == 0
|
| 48 |
+
|
| 49 |
+
def test_token_classification_task_with_ignored_tokens_0(self):
|
| 50 |
+
eval_pred = (
|
| 51 |
+
np.array(
|
| 52 |
+
[
|
| 53 |
+
[[0.1, 0.9], [0.8, 0.2]], # Batch 1
|
| 54 |
+
[[0.3, 0.7], [0.6, 0.4]], # Batch 2
|
| 55 |
+
]
|
| 56 |
+
),
|
| 57 |
+
np.array([[1, 0], [1, -100]]),
|
| 58 |
+
)
|
| 59 |
+
expected_accuracy = 1.0 # All non-ignored tokens match
|
| 60 |
+
result = compute_accuracy(eval_pred)
|
| 61 |
+
assert round(abs(result["accuracy"] - expected_accuracy), 7) == 0
|
| 62 |
+
|
| 63 |
+
def test_token_classification_task_with_ignored_tokens_1(self):
|
| 64 |
+
eval_pred = (
|
| 65 |
+
np.array(
|
| 66 |
+
[
|
| 67 |
+
[[0.1, 0.9], [0.8, 0.2]], # Batch 1
|
| 68 |
+
[[0.3, 0.7], [0.6, 0.4]], # Batch 2
|
| 69 |
+
]
|
| 70 |
+
),
|
| 71 |
+
np.array([[1, 1], [0, -100]]),
|
| 72 |
+
)
|
| 73 |
+
expected_accuracy = 1 / 3 # 1 match, 2 mismatch, 1 ignored
|
| 74 |
+
result = compute_accuracy(eval_pred)
|
| 75 |
+
assert round(abs(result["accuracy"] - expected_accuracy), 7) == 0
|
| 76 |
+
|
| 77 |
+
def test_rewards_comparison_task(self, caplog):
|
| 78 |
+
eval_pred = (
|
| 79 |
+
np.array(
|
| 80 |
+
[
|
| 81 |
+
[0.9, 0.1], # Batch 1
|
| 82 |
+
[0.6, 0.4], # Batch 2
|
| 83 |
+
[0.5, 0.5], # Batch 3 (equal)
|
| 84 |
+
]
|
| 85 |
+
),
|
| 86 |
+
np.array([0, 1, 1]),
|
| 87 |
+
)
|
| 88 |
+
expected_accuracy = 0.5 # 1 match, 1 mismatch, 1 equal (ignored)
|
| 89 |
+
|
| 90 |
+
with caplog.at_level("WARNING", logger="trl.trainer.utils"):
|
| 91 |
+
result = compute_accuracy(eval_pred)
|
| 92 |
+
|
| 93 |
+
assert round(abs(result["accuracy"] - expected_accuracy), 7) == 0
|
| 94 |
+
expected_warning = (
|
| 95 |
+
"There are 1 out of 3 instances where the predictions for both options are equal. "
|
| 96 |
+
"These instances are ignored in the accuracy computation."
|
| 97 |
+
)
|
| 98 |
+
assert expected_warning in caplog.text
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class TestTokenizeRow(TrlTestCase):
|
| 102 |
+
def setup_method(self):
|
| 103 |
+
# Set up the mock tokenizer with specific behaviors
|
| 104 |
+
self.tokenizer = MagicMock(spec=PreTrainedTokenizerBase)
|
| 105 |
+
self.tokenizer.bos_token_id = 0
|
| 106 |
+
self.tokenizer.eos_token_id = 2
|
| 107 |
+
|
| 108 |
+
def mock_encode(text, add_special_tokens):
|
| 109 |
+
token_map = {
|
| 110 |
+
"Which number is larger, 9.8 or 9.11?": [465, 6766, 318, 298],
|
| 111 |
+
"11 is greater than 8.": [4, 322, 12],
|
| 112 |
+
"Hence, 9.11 > 9.8.": [4995, 11, 22],
|
| 113 |
+
"\n": [1030],
|
| 114 |
+
"\n\n": [1030, 1030],
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
return token_map[text]
|
| 118 |
+
|
| 119 |
+
def mock_tokenizer_call(text, add_special_tokens):
|
| 120 |
+
return {"input_ids": mock_encode(text, add_special_tokens)}
|
| 121 |
+
|
| 122 |
+
self.tokenizer.encode.side_effect = mock_encode
|
| 123 |
+
self.tokenizer.side_effect = mock_tokenizer_call
|
| 124 |
+
|
| 125 |
+
def test_tokenize_row_no_truncation(self):
|
| 126 |
+
# Define the input features
|
| 127 |
+
features = {
|
| 128 |
+
"prompt": "Which number is larger, 9.8 or 9.11?",
|
| 129 |
+
"completions": ["11 is greater than 8.", "Hence, 9.11 > 9.8."],
|
| 130 |
+
"labels": [True, False],
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
# Call the method with no truncation
|
| 134 |
+
result = PRMTrainer.tokenize_row(
|
| 135 |
+
features=features,
|
| 136 |
+
tokenizer=self.tokenizer,
|
| 137 |
+
step_separator="\n",
|
| 138 |
+
max_length=None,
|
| 139 |
+
max_completion_length=None,
|
| 140 |
+
train_on_last_step_only=False,
|
| 141 |
+
is_eval=False,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
assert result == {
|
| 145 |
+
"input_ids": [0, 465, 6766, 318, 298, 4, 322, 12, 1030, 4995, 11, 22, 1030],
|
| 146 |
+
"labels": [-100, -100, -100, -100, -100, -100, -100, -100, 1, -100, -100, -100, 0],
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
def test_tokenize_row_train_on_last_step_only(self):
|
| 150 |
+
# Define the input features
|
| 151 |
+
features = {
|
| 152 |
+
"prompt": "Which number is larger, 9.8 or 9.11?",
|
| 153 |
+
"completions": ["11 is greater than 8.", "Hence, 9.11 > 9.8."],
|
| 154 |
+
"labels": [True, False],
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
result = PRMTrainer.tokenize_row(
|
| 158 |
+
features=features,
|
| 159 |
+
tokenizer=self.tokenizer,
|
| 160 |
+
step_separator="\n",
|
| 161 |
+
max_length=None,
|
| 162 |
+
max_completion_length=None,
|
| 163 |
+
train_on_last_step_only=True,
|
| 164 |
+
is_eval=False,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
assert result == {
|
| 168 |
+
"input_ids": [0, 465, 6766, 318, 298, 4, 322, 12, 1030, 4995, 11, 22, 1030],
|
| 169 |
+
"labels": [-100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, 0],
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
def test_tokenize_row_completion_truncation(self):
|
| 173 |
+
# Define the input features
|
| 174 |
+
features = {
|
| 175 |
+
"prompt": "Which number is larger, 9.8 or 9.11?",
|
| 176 |
+
"completions": ["11 is greater than 8.", "Hence, 9.11 > 9.8."],
|
| 177 |
+
"labels": [True, False],
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
# Call the method with truncation on the completion
|
| 181 |
+
result = PRMTrainer.tokenize_row(
|
| 182 |
+
features=features,
|
| 183 |
+
tokenizer=self.tokenizer,
|
| 184 |
+
step_separator="\n",
|
| 185 |
+
max_length=None,
|
| 186 |
+
max_completion_length=6,
|
| 187 |
+
train_on_last_step_only=False,
|
| 188 |
+
is_eval=False,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
assert result == {
|
| 192 |
+
"input_ids": [0, 465, 6766, 318, 298, 4, 322, 12, 1030, 4995, 11],
|
| 193 |
+
"labels": [-100, -100, -100, -100, -100, -100, -100, -100, 1, -100, -100],
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
def test_tokenize_row_prompt_completion_truncation(self):
|
| 197 |
+
# Define the input features
|
| 198 |
+
features = {
|
| 199 |
+
"prompt": "Which number is larger, 9.8 or 9.11?",
|
| 200 |
+
"completions": ["11 is greater than 8.", "Hence, 9.11 > 9.8."],
|
| 201 |
+
"labels": [True, False],
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
# Call the method with truncation on the prompt and completion
|
| 205 |
+
result = PRMTrainer.tokenize_row(
|
| 206 |
+
features=features,
|
| 207 |
+
tokenizer=self.tokenizer,
|
| 208 |
+
step_separator="\n",
|
| 209 |
+
max_length=9,
|
| 210 |
+
max_completion_length=None,
|
| 211 |
+
train_on_last_step_only=False,
|
| 212 |
+
is_eval=False,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
assert result == {
|
| 216 |
+
"input_ids": [0, 465, 6766, 318, 298, 4, 322, 12, 1030],
|
| 217 |
+
"labels": [-100, -100, -100, -100, -100, -100, -100, -100, 1],
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
def test_tokenize_row_multi_token_separator(self):
|
| 221 |
+
# Define the input features
|
| 222 |
+
features = {
|
| 223 |
+
"prompt": "Which number is larger, 9.8 or 9.11?",
|
| 224 |
+
"completions": ["11 is greater than 8.", "Hence, 9.11 > 9.8."],
|
| 225 |
+
"labels": [True, False],
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
# Call the method using multiple tokens as step_separator
|
| 229 |
+
result = PRMTrainer.tokenize_row(
|
| 230 |
+
features=features,
|
| 231 |
+
tokenizer=self.tokenizer,
|
| 232 |
+
step_separator="\n\n",
|
| 233 |
+
max_length=None,
|
| 234 |
+
max_completion_length=None,
|
| 235 |
+
train_on_last_step_only=False,
|
| 236 |
+
is_eval=False,
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
assert result == {
|
| 240 |
+
"input_ids": [0, 465, 6766, 318, 298, 4, 322, 12, 1030, 1030, 4995, 11, 22, 1030, 1030],
|
| 241 |
+
"labels": [-100, -100, -100, -100, -100, -100, -100, -100, -100, 1, -100, -100, -100, -100, 0],
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class TestPRMTrainer(TrlTestCase):
|
| 246 |
+
def setup_method(self):
|
| 247 |
+
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 248 |
+
self.model = AutoModelForTokenClassification.from_pretrained(model_id, dtype="float32")
|
| 249 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 250 |
+
|
| 251 |
+
@pytest.mark.parametrize("train_on_last_step_only", [True, False])
|
| 252 |
+
def test_train_full(self, train_on_last_step_only):
|
| 253 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_stepwise_supervision", split="train")
|
| 254 |
+
training_args = PRMConfig(
|
| 255 |
+
output_dir=self.tmp_dir,
|
| 256 |
+
report_to="none",
|
| 257 |
+
train_on_last_step_only=train_on_last_step_only,
|
| 258 |
+
)
|
| 259 |
+
trainer = PRMTrainer(
|
| 260 |
+
model=self.model, args=training_args, processing_class=self.tokenizer, train_dataset=dataset
|
| 261 |
+
)
|
| 262 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 263 |
+
trainer.train()
|
| 264 |
+
|
| 265 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 266 |
+
# Check that the params have changed
|
| 267 |
+
for n, param in previous_trainable_params.items():
|
| 268 |
+
new_param = trainer.model.get_parameter(n)
|
| 269 |
+
if param.sum() != 0: # ignore 0 biases
|
| 270 |
+
assert not torch.equal(param, new_param)
|
| 271 |
+
|
| 272 |
+
def test_train_full_pretokenized(self):
|
| 273 |
+
dataset = Dataset.from_dict(
|
| 274 |
+
{
|
| 275 |
+
"labels": [
|
| 276 |
+
[-100, -100, -100, -100, -100, -100, -100, -100, -100, 0, -100, -100, 1],
|
| 277 |
+
[-100, -100, -100, -100, -100, -100, -100, -100, 0, -100, -100, 1, -100, -100, -100, -100, 0],
|
| 278 |
+
[-100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, 0, -100, -100, 1],
|
| 279 |
+
[-100, -100, -100, -100, -100, -100, -100, 1, -100, -100, 1],
|
| 280 |
+
[-100, -100, -100, -100, -100, -100, -100, -100, -100, 1, -100, -100, 0],
|
| 281 |
+
[-100, -100, -100, -100, -100, -100, -100, -100, -100, 1],
|
| 282 |
+
[-100, -100, -100, -100, -100, -100, -100, -100, -100, 0],
|
| 283 |
+
[-100, -100, -100, -100, -100, -100, -100, -100, -100, 1, -100, -100, -100, -100, -100, 0],
|
| 284 |
+
[-100, -100, -100, -100, -100, -100, -100, -100, 0, -100, -100, 0],
|
| 285 |
+
[-100, -100, -100, -100, -100, -100, 0, -100, -100, -100, -100, 0],
|
| 286 |
+
[-100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, 1],
|
| 287 |
+
[-100, -100, -100, -100, -100, -100, 0],
|
| 288 |
+
[-100, -100, -100, -100, -100, -100, -100, -100, 1],
|
| 289 |
+
[-100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, 0],
|
| 290 |
+
],
|
| 291 |
+
"input_ids": [
|
| 292 |
+
[46518, 374, 2664, 1091, 11, 1077, 752, 1744, 1112, 198, 27261, 13, 198],
|
| 293 |
+
[98923, 374, 2664, 1091, 11, 315, 3308, 11, 198, 17995, 13, 198, 1576, 31273, 12850, 13, 198],
|
| 294 |
+
[16374, 374, 2664, 1091, 1112, 1077, 594, 2506, 432, 6770, 11, 198, 6351, 13, 198],
|
| 295 |
+
[31137, 374, 2664, 1091, 979, 4362, 11, 198, 16965, 13, 198],
|
| 296 |
+
[31019, 374, 2664, 1091, 304, 3793, 315, 5944, 11, 198, 24034, 13, 198],
|
| 297 |
+
[98491, 374, 2664, 1091, 1112, 5310, 369, 91494, 13, 198],
|
| 298 |
+
[4418, 2897, 14579, 5310, 979, 3800, 1349, 432, 13, 198],
|
| 299 |
+
[20366, 5048, 7629, 944, 3281, 3322, 11, 7241, 1112, 198, 807, 1795, 279, 5601, 13, 198],
|
| 300 |
+
[15802, 14976, 487, 33327, 1045, 31787, 63443, 11, 198, 52400, 13, 198],
|
| 301 |
+
[13877, 1265, 2581, 1494, 49394, 11, 198, 7241, 20975, 91681, 13, 198],
|
| 302 |
+
[641, 279, 3579, 315, 71768, 11, 25066, 279, 61361, 311, 7942, 13, 198],
|
| 303 |
+
[7039, 374, 2664, 1091, 2937, 13, 198],
|
| 304 |
+
[26155, 374, 3545, 2664, 1091, 34933, 26537, 13, 198],
|
| 305 |
+
[2679, 279, 8129, 374, 4135, 311, 10339, 11, 432, 2578, 387, 264, 1661, 2884, 13, 198],
|
| 306 |
+
],
|
| 307 |
+
}
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
training_args = PRMConfig(output_dir=self.tmp_dir, report_to="none")
|
| 311 |
+
trainer = PRMTrainer(
|
| 312 |
+
model=self.model, args=training_args, processing_class=self.tokenizer, train_dataset=dataset
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 316 |
+
trainer.train()
|
| 317 |
+
|
| 318 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 319 |
+
# Check that the params have changed
|
| 320 |
+
for n, param in previous_trainable_params.items():
|
| 321 |
+
new_param = trainer.model.get_parameter(n)
|
| 322 |
+
if param.sum() != 0: # ignore 0 biases
|
| 323 |
+
assert not torch.equal(param, new_param)
|
| 324 |
+
|
| 325 |
+
@require_peft
|
| 326 |
+
def test_train_lora(self):
|
| 327 |
+
peft_config = LoraConfig(
|
| 328 |
+
task_type=TaskType.TOKEN_CLS,
|
| 329 |
+
inference_mode=False,
|
| 330 |
+
r=8,
|
| 331 |
+
lora_alpha=32,
|
| 332 |
+
lora_dropout=0.1,
|
| 333 |
+
)
|
| 334 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_stepwise_supervision", split="train")
|
| 335 |
+
training_args = PRMConfig(output_dir=self.tmp_dir, max_steps=3, report_to="none")
|
| 336 |
+
trainer = PRMTrainer(
|
| 337 |
+
model=self.model,
|
| 338 |
+
args=training_args,
|
| 339 |
+
processing_class=self.tokenizer,
|
| 340 |
+
train_dataset=dataset,
|
| 341 |
+
peft_config=peft_config,
|
| 342 |
+
)
|
| 343 |
+
previous_trainable_params = {}
|
| 344 |
+
previous_non_trainable_params = {}
|
| 345 |
+
|
| 346 |
+
# due to a change in the way the modules to save are dealt in PEFT.
|
| 347 |
+
trainable_params_name = ["lora", "modules_to_save"]
|
| 348 |
+
|
| 349 |
+
# check gradients are not None
|
| 350 |
+
for n, param in trainer.model.named_parameters():
|
| 351 |
+
if any(t in n for t in trainable_params_name):
|
| 352 |
+
previous_trainable_params[n] = param.clone()
|
| 353 |
+
else:
|
| 354 |
+
previous_non_trainable_params[n] = param.clone()
|
| 355 |
+
|
| 356 |
+
trainer.train()
|
| 357 |
+
|
| 358 |
+
assert trainer.state.log_history[(-1)]["train_loss"] is not None
|
| 359 |
+
|
| 360 |
+
# Check that the params have changed
|
| 361 |
+
for n, param in previous_trainable_params.items():
|
| 362 |
+
new_param = trainer.model.get_parameter(n)
|
| 363 |
+
assert not torch.equal(param, new_param)
|
| 364 |
+
|
| 365 |
+
# Check that the non trainable parameters have not changed
|
| 366 |
+
for n, param in previous_non_trainable_params.items():
|
| 367 |
+
new_param = trainer.model.get_parameter(n)
|
| 368 |
+
torch.testing.assert_close(param, new_param, atol=1e-12, rtol=1e-12)
|
| 369 |
+
|
| 370 |
+
def test_tags(self):
|
| 371 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_stepwise_supervision", split="train")
|
| 372 |
+
training_args = PRMConfig(output_dir=self.tmp_dir, report_to="none")
|
| 373 |
+
trainer = PRMTrainer(
|
| 374 |
+
model=self.model, args=training_args, processing_class=self.tokenizer, train_dataset=dataset
|
| 375 |
+
)
|
| 376 |
+
assert trainer.model.model_tags == trainer._tag_names
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_sdft_trainer.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from datasets import Dataset
|
| 18 |
+
from transformers import TrainerCallback
|
| 19 |
+
from transformers.utils import is_peft_available
|
| 20 |
+
|
| 21 |
+
from trl.experimental.sdft import SDFTConfig, SDFTTrainer
|
| 22 |
+
|
| 23 |
+
from ..testing_utils import TrlTestCase, require_liger_kernel, require_peft, require_torch_accelerator
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if is_peft_available():
|
| 27 |
+
from peft import LoraConfig
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class SelfDistillationCaptureCallback(TrainerCallback):
|
| 31 |
+
def __init__(self):
|
| 32 |
+
self.captured_generation_prompts = None
|
| 33 |
+
self.captured_old_per_token_logps = None
|
| 34 |
+
self.captured_prompt_ids = None
|
| 35 |
+
self.generation_batch_build_count = 0
|
| 36 |
+
|
| 37 |
+
def on_generation_prompts_selected(self, generation_prompts=None, **kwargs):
|
| 38 |
+
if self.captured_generation_prompts is None and generation_prompts is not None:
|
| 39 |
+
self.captured_generation_prompts = generation_prompts
|
| 40 |
+
|
| 41 |
+
def on_self_distillation_batch_prepared(self, old_per_token_logps=None, prompt_ids=None, **kwargs):
|
| 42 |
+
if self.captured_old_per_token_logps is None and old_per_token_logps is not None:
|
| 43 |
+
self.captured_old_per_token_logps = old_per_token_logps.detach().cpu()
|
| 44 |
+
if self.captured_prompt_ids is None and prompt_ids is not None:
|
| 45 |
+
self.captured_prompt_ids = prompt_ids.detach().cpu()
|
| 46 |
+
|
| 47 |
+
def on_generation_batch_built(self, **kwargs):
|
| 48 |
+
self.generation_batch_build_count += 1
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class RecordingTeacherClient:
|
| 52 |
+
"""Stands in for the vLLM server client and records scoring requests."""
|
| 53 |
+
|
| 54 |
+
def __init__(self, response):
|
| 55 |
+
self.response = response
|
| 56 |
+
self.calls = []
|
| 57 |
+
|
| 58 |
+
def get_sequence_logprobs(self, **kwargs):
|
| 59 |
+
self.calls.append(kwargs)
|
| 60 |
+
return self.response
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class TestSDFTTrainer(TrlTestCase):
|
| 64 |
+
@staticmethod
|
| 65 |
+
def _trainable_param_snapshot(model):
|
| 66 |
+
return {name: param.detach().clone() for name, param in model.named_parameters() if param.requires_grad}
|
| 67 |
+
|
| 68 |
+
@staticmethod
|
| 69 |
+
def _assert_any_trainable_param_changed(model, previous_trainable_params):
|
| 70 |
+
assert any(
|
| 71 |
+
not torch.allclose(previous_param, model.get_parameter(name), rtol=1e-12, atol=1e-12)
|
| 72 |
+
for name, previous_param in previous_trainable_params.items()
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
def test_trust_remote_code(self):
|
| 76 |
+
dataset = Dataset.from_dict(
|
| 77 |
+
{
|
| 78 |
+
"prompt": ["Solve 2+2.", "Name the capital of France."],
|
| 79 |
+
"privileged_context": ["Example answer: 4.", "Example answer: Paris."],
|
| 80 |
+
}
|
| 81 |
+
)
|
| 82 |
+
model_id = "trl-internal-testing/tiny-RemoteForCausalLM"
|
| 83 |
+
|
| 84 |
+
with pytest.raises(ValueError, match="custom code"):
|
| 85 |
+
SDFTTrainer(
|
| 86 |
+
model=model_id,
|
| 87 |
+
args=SDFTConfig(output_dir=self.tmp_dir, report_to="none"),
|
| 88 |
+
train_dataset=dataset,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
trainer = SDFTTrainer(
|
| 92 |
+
model=model_id,
|
| 93 |
+
args=SDFTConfig(output_dir=self.tmp_dir, report_to="none", trust_remote_code=True),
|
| 94 |
+
train_dataset=dataset,
|
| 95 |
+
)
|
| 96 |
+
assert type(trainer.model).__name__ == "RemoteForCausalLM"
|
| 97 |
+
|
| 98 |
+
def test_train(self):
|
| 99 |
+
dataset = Dataset.from_dict(
|
| 100 |
+
{
|
| 101 |
+
"prompt": ["Solve 2+2.", "Name the capital of France."],
|
| 102 |
+
"privileged_context": [
|
| 103 |
+
"Example answer: 4.",
|
| 104 |
+
"Example answer: Paris.",
|
| 105 |
+
],
|
| 106 |
+
}
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
training_args = SDFTConfig(
|
| 110 |
+
output_dir=self.tmp_dir,
|
| 111 |
+
learning_rate=0.1,
|
| 112 |
+
per_device_train_batch_size=1,
|
| 113 |
+
max_completion_length=8,
|
| 114 |
+
max_steps=1,
|
| 115 |
+
num_generations=1,
|
| 116 |
+
report_to="none",
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
trainer = SDFTTrainer(
|
| 120 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 121 |
+
args=training_args,
|
| 122 |
+
train_dataset=dataset,
|
| 123 |
+
)
|
| 124 |
+
previous_trainable_params = self._trainable_param_snapshot(trainer.model)
|
| 125 |
+
|
| 126 |
+
trainer.train()
|
| 127 |
+
|
| 128 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 129 |
+
self._assert_any_trainable_param_changed(trainer.model, previous_trainable_params)
|
| 130 |
+
|
| 131 |
+
@require_liger_kernel
|
| 132 |
+
@require_torch_accelerator
|
| 133 |
+
def test_liger_loss_matches_non_liger_loss(self):
|
| 134 |
+
dataset = Dataset.from_dict({"prompt": ["Solve 2+2."], "privileged_context": ["Example answer: 4."]})
|
| 135 |
+
common = dict(
|
| 136 |
+
output_dir=self.tmp_dir,
|
| 137 |
+
report_to="none",
|
| 138 |
+
per_device_train_batch_size=1,
|
| 139 |
+
max_completion_length=3,
|
| 140 |
+
num_generations=1,
|
| 141 |
+
distillation_mode="full_logits",
|
| 142 |
+
distillation_is_clip=None,
|
| 143 |
+
num_loss_tokens_to_skip=1,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
ref_trainer = SDFTTrainer(
|
| 147 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 148 |
+
args=SDFTConfig(use_liger_kernel=False, **common),
|
| 149 |
+
train_dataset=dataset,
|
| 150 |
+
)
|
| 151 |
+
liger_trainer = SDFTTrainer(
|
| 152 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 153 |
+
args=SDFTConfig(use_liger_kernel=True, **common),
|
| 154 |
+
train_dataset=dataset,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
liger_trainer.model.load_state_dict(ref_trainer.model.state_dict())
|
| 158 |
+
torch.manual_seed(0)
|
| 159 |
+
with torch.no_grad():
|
| 160 |
+
for param in ref_trainer.teacher_model.parameters():
|
| 161 |
+
param.add_(0.5 * torch.randn_like(param))
|
| 162 |
+
liger_trainer.teacher_model.load_state_dict(ref_trainer.teacher_model.state_dict())
|
| 163 |
+
|
| 164 |
+
device = next(ref_trainer.model.parameters()).device
|
| 165 |
+
batch = {
|
| 166 |
+
"prompt_ids": torch.tensor([[10, 11], [12, 13]], device=device),
|
| 167 |
+
"prompt_mask": torch.tensor([[1, 1], [1, 1]], device=device),
|
| 168 |
+
"completion_ids": torch.tensor([[14, 15, 16], [17, 18, 19]], device=device),
|
| 169 |
+
"completion_mask": torch.tensor([[1, 1, 0], [1, 1, 1]], device=device),
|
| 170 |
+
"teacher_input_ids": torch.tensor([[20, 21, 22, 14, 15, 16], [23, 24, 25, 17, 18, 19]], device=device),
|
| 171 |
+
"teacher_attention_mask": torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]], device=device),
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
ref_trainer.model.eval()
|
| 175 |
+
liger_trainer.model.eval()
|
| 176 |
+
with torch.no_grad():
|
| 177 |
+
ref_loss = ref_trainer.compute_loss(ref_trainer.model, batch).item()
|
| 178 |
+
liger_loss = liger_trainer.compute_loss(liger_trainer.model, batch).item()
|
| 179 |
+
|
| 180 |
+
torch.testing.assert_close(
|
| 181 |
+
torch.tensor(liger_loss),
|
| 182 |
+
torch.tensor(ref_loss),
|
| 183 |
+
rtol=2e-2,
|
| 184 |
+
atol=1e-6,
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
def test_train_rejects_none_privileged_context(self):
|
| 188 |
+
dataset = Dataset.from_dict(
|
| 189 |
+
{
|
| 190 |
+
"prompt": ["Solve 2+2."],
|
| 191 |
+
"privileged_context": [None],
|
| 192 |
+
}
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
training_args = SDFTConfig(
|
| 196 |
+
output_dir=self.tmp_dir,
|
| 197 |
+
per_device_train_batch_size=1,
|
| 198 |
+
max_completion_length=8,
|
| 199 |
+
max_steps=1,
|
| 200 |
+
num_generations=1,
|
| 201 |
+
report_to="none",
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
trainer = SDFTTrainer(
|
| 205 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 206 |
+
args=training_args,
|
| 207 |
+
train_dataset=dataset,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
with pytest.raises(ValueError, match="`privileged_context` must not be None"):
|
| 211 |
+
trainer.train()
|
| 212 |
+
|
| 213 |
+
def test_train_with_generate_from_teacher(self):
|
| 214 |
+
dataset = Dataset.from_dict(
|
| 215 |
+
{
|
| 216 |
+
"prompt": ["Solve 2+2.", "Solve 3+3."],
|
| 217 |
+
"privileged_context": [
|
| 218 |
+
"Teacher hint: answer with 4 and explain briefly.",
|
| 219 |
+
"Teacher hint: answer with 6 and explain briefly.",
|
| 220 |
+
],
|
| 221 |
+
}
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
training_args = SDFTConfig(
|
| 225 |
+
output_dir=self.tmp_dir,
|
| 226 |
+
learning_rate=0.1,
|
| 227 |
+
per_device_train_batch_size=1,
|
| 228 |
+
max_completion_length=8,
|
| 229 |
+
max_steps=1,
|
| 230 |
+
num_generations=1,
|
| 231 |
+
generate_from_teacher=True,
|
| 232 |
+
report_to="none",
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
capture_callback = SelfDistillationCaptureCallback()
|
| 236 |
+
trainer = SDFTTrainer(
|
| 237 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 238 |
+
args=training_args,
|
| 239 |
+
train_dataset=dataset,
|
| 240 |
+
callbacks=[capture_callback],
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
trainer.train()
|
| 244 |
+
|
| 245 |
+
assert capture_callback.captured_generation_prompts == [
|
| 246 |
+
"Solve 2+2.\n\nTeacher hint: answer with 4 and explain briefly."
|
| 247 |
+
]
|
| 248 |
+
student_prompt_text = trainer.processing_class.decode(
|
| 249 |
+
capture_callback.captured_prompt_ids[0],
|
| 250 |
+
skip_special_tokens=True,
|
| 251 |
+
)
|
| 252 |
+
assert "Teacher hint" not in student_prompt_text
|
| 253 |
+
assert "Solve 2+2." in student_prompt_text
|
| 254 |
+
|
| 255 |
+
def test_train_with_chat_template_kwargs(self):
|
| 256 |
+
dataset = Dataset.from_dict(
|
| 257 |
+
{
|
| 258 |
+
"prompt": [
|
| 259 |
+
[{"role": "user", "content": "Solve 2+2."}],
|
| 260 |
+
[{"role": "user", "content": "Solve 3+3."}],
|
| 261 |
+
],
|
| 262 |
+
"privileged_context": [
|
| 263 |
+
"Teacher hint: answer with 4.",
|
| 264 |
+
"Teacher hint: answer with 6.",
|
| 265 |
+
],
|
| 266 |
+
}
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
training_args = SDFTConfig(
|
| 270 |
+
output_dir=self.tmp_dir,
|
| 271 |
+
learning_rate=0.1,
|
| 272 |
+
per_device_train_batch_size=1,
|
| 273 |
+
max_completion_length=8,
|
| 274 |
+
max_steps=1,
|
| 275 |
+
num_generations=1,
|
| 276 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 277 |
+
report_to="none",
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
trainer = SDFTTrainer(
|
| 281 |
+
model="trl-internal-testing/tiny-Qwen3ForCausalLM",
|
| 282 |
+
args=training_args,
|
| 283 |
+
train_dataset=dataset,
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
previous_trainable_params = self._trainable_param_snapshot(trainer.model)
|
| 287 |
+
|
| 288 |
+
trainer.train()
|
| 289 |
+
|
| 290 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 291 |
+
self._assert_any_trainable_param_changed(trainer.model, previous_trainable_params)
|
| 292 |
+
|
| 293 |
+
@require_peft
|
| 294 |
+
def test_train_with_peft_model(self):
|
| 295 |
+
dataset = Dataset.from_dict(
|
| 296 |
+
{
|
| 297 |
+
"prompt": ["Solve 2+2.", "Name the capital of France."],
|
| 298 |
+
"privileged_context": [
|
| 299 |
+
"Example answer: 4.",
|
| 300 |
+
"Example answer: Paris.",
|
| 301 |
+
],
|
| 302 |
+
}
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
training_args = SDFTConfig(
|
| 306 |
+
output_dir=self.tmp_dir,
|
| 307 |
+
learning_rate=0.1,
|
| 308 |
+
per_device_train_batch_size=1,
|
| 309 |
+
max_completion_length=8,
|
| 310 |
+
max_steps=1,
|
| 311 |
+
num_generations=1,
|
| 312 |
+
report_to="none",
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
trainer = SDFTTrainer(
|
| 316 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 317 |
+
args=training_args,
|
| 318 |
+
train_dataset=dataset,
|
| 319 |
+
peft_config=LoraConfig(
|
| 320 |
+
task_type="CAUSAL_LM",
|
| 321 |
+
target_modules=["q_proj", "v_proj"],
|
| 322 |
+
),
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
previous_trainable_params = self._trainable_param_snapshot(trainer.model)
|
| 326 |
+
|
| 327 |
+
trainer.train()
|
| 328 |
+
|
| 329 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 330 |
+
self._assert_any_trainable_param_changed(trainer.model, previous_trainable_params)
|
| 331 |
+
|
| 332 |
+
@require_peft
|
| 333 |
+
def test_train_with_peft_model_and_ema_teacher_sync(self):
|
| 334 |
+
dataset = Dataset.from_dict(
|
| 335 |
+
{
|
| 336 |
+
"prompt": ["Solve 2+2.", "Name the capital of France."],
|
| 337 |
+
"privileged_context": [
|
| 338 |
+
"Example answer: 4.",
|
| 339 |
+
"Example answer: Paris.",
|
| 340 |
+
],
|
| 341 |
+
}
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
training_args = SDFTConfig(
|
| 345 |
+
output_dir=self.tmp_dir,
|
| 346 |
+
learning_rate=0.1,
|
| 347 |
+
per_device_train_batch_size=1,
|
| 348 |
+
max_completion_length=8,
|
| 349 |
+
max_steps=2,
|
| 350 |
+
num_generations=1,
|
| 351 |
+
teacher_model_kind="ema",
|
| 352 |
+
teacher_update_rate=0.05,
|
| 353 |
+
teacher_sync_steps=1,
|
| 354 |
+
report_to="none",
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
trainer = SDFTTrainer(
|
| 358 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 359 |
+
args=training_args,
|
| 360 |
+
train_dataset=dataset,
|
| 361 |
+
peft_config=LoraConfig(
|
| 362 |
+
task_type="CAUSAL_LM",
|
| 363 |
+
target_modules=["q_proj", "v_proj"],
|
| 364 |
+
),
|
| 365 |
+
)
|
| 366 |
+
previous_trainable_params = self._trainable_param_snapshot(trainer.model)
|
| 367 |
+
|
| 368 |
+
trainer.train()
|
| 369 |
+
|
| 370 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 371 |
+
self._assert_any_trainable_param_changed(trainer.model, previous_trainable_params)
|
| 372 |
+
|
| 373 |
+
def test_train_populates_old_log_probs_for_distillation_clipping_when_misaligned(self):
|
| 374 |
+
dataset = Dataset.from_dict(
|
| 375 |
+
{
|
| 376 |
+
"prompt": ["Solve 2+2.", "Solve 3+3."],
|
| 377 |
+
"privileged_context": [
|
| 378 |
+
"Example answer: 4.",
|
| 379 |
+
"Example answer: 6.",
|
| 380 |
+
],
|
| 381 |
+
}
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
training_args = SDFTConfig(
|
| 385 |
+
output_dir=self.tmp_dir,
|
| 386 |
+
learning_rate=0.1,
|
| 387 |
+
per_device_train_batch_size=1,
|
| 388 |
+
gradient_accumulation_steps=3,
|
| 389 |
+
steps_per_generation=2,
|
| 390 |
+
max_completion_length=8,
|
| 391 |
+
max_steps=1,
|
| 392 |
+
num_generations=1,
|
| 393 |
+
report_to="none",
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
capture_callback = SelfDistillationCaptureCallback()
|
| 397 |
+
trainer = SDFTTrainer(
|
| 398 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 399 |
+
args=training_args,
|
| 400 |
+
train_dataset=dataset,
|
| 401 |
+
callbacks=[capture_callback],
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
trainer.train()
|
| 405 |
+
|
| 406 |
+
assert capture_callback.captured_old_per_token_logps is not None
|
| 407 |
+
|
| 408 |
+
def test_train_with_generate_from_teacher_skips_old_log_probs_for_distillation_clipping(self):
|
| 409 |
+
dataset = Dataset.from_dict(
|
| 410 |
+
{
|
| 411 |
+
"prompt": ["Solve 2+2.", "Solve 3+3."],
|
| 412 |
+
"privileged_context": [
|
| 413 |
+
"Teacher hint: answer with 4.",
|
| 414 |
+
"Teacher hint: answer with 6.",
|
| 415 |
+
],
|
| 416 |
+
}
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
training_args = SDFTConfig(
|
| 420 |
+
output_dir=self.tmp_dir,
|
| 421 |
+
learning_rate=0.1,
|
| 422 |
+
per_device_train_batch_size=1,
|
| 423 |
+
gradient_accumulation_steps=3,
|
| 424 |
+
steps_per_generation=2,
|
| 425 |
+
max_completion_length=8,
|
| 426 |
+
max_steps=1,
|
| 427 |
+
num_generations=1,
|
| 428 |
+
generate_from_teacher=True,
|
| 429 |
+
report_to="none",
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
capture_callback = SelfDistillationCaptureCallback()
|
| 433 |
+
trainer = SDFTTrainer(
|
| 434 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 435 |
+
args=training_args,
|
| 436 |
+
train_dataset=dataset,
|
| 437 |
+
callbacks=[capture_callback],
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
trainer.train()
|
| 441 |
+
|
| 442 |
+
assert capture_callback.captured_old_per_token_logps is None
|
| 443 |
+
|
| 444 |
+
def test_train_reuses_buffered_generation_batches(self):
|
| 445 |
+
dataset = Dataset.from_dict(
|
| 446 |
+
{
|
| 447 |
+
"prompt": ["Solve 2+2.", "Solve 3+3."],
|
| 448 |
+
"privileged_context": [
|
| 449 |
+
"Example answer: 4.",
|
| 450 |
+
"Example answer: 6.",
|
| 451 |
+
],
|
| 452 |
+
}
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
training_args = SDFTConfig(
|
| 456 |
+
output_dir=self.tmp_dir,
|
| 457 |
+
learning_rate=0.1,
|
| 458 |
+
per_device_train_batch_size=1,
|
| 459 |
+
steps_per_generation=2,
|
| 460 |
+
max_completion_length=8,
|
| 461 |
+
max_steps=2,
|
| 462 |
+
num_generations=1,
|
| 463 |
+
report_to="none",
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
capture_callback = SelfDistillationCaptureCallback()
|
| 467 |
+
trainer = SDFTTrainer(
|
| 468 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 469 |
+
args=training_args,
|
| 470 |
+
train_dataset=dataset,
|
| 471 |
+
callbacks=[capture_callback],
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
trainer.train()
|
| 475 |
+
|
| 476 |
+
assert capture_callback.generation_batch_build_count == 1
|
| 477 |
+
|
| 478 |
+
def test_server_loss_finite_with_masked_and_padded_rows(self):
|
| 479 |
+
# Drives the teacher-server path through `compute_loss` with a fake server client: row 0 is fully masked
|
| 480 |
+
# (zero-length scored completion) and row 1 has a shorter completion than the padded batch, so the client
|
| 481 |
+
# response is ragged and the padded tail comes back as -inf. Neither may leak NaN or inf.
|
| 482 |
+
dataset = Dataset.from_dict({"prompt": ["Solve 2+2."], "privileged_context": ["Example answer: 4."]})
|
| 483 |
+
training_args = SDFTConfig(
|
| 484 |
+
output_dir=self.tmp_dir,
|
| 485 |
+
per_device_train_batch_size=1,
|
| 486 |
+
max_completion_length=3,
|
| 487 |
+
num_generations=1,
|
| 488 |
+
distillation_mode="topk_logits",
|
| 489 |
+
distillation_topk=2,
|
| 490 |
+
distillation_alpha=0.5,
|
| 491 |
+
distillation_add_tail=True,
|
| 492 |
+
distillation_is_clip=None,
|
| 493 |
+
report_to="none",
|
| 494 |
+
)
|
| 495 |
+
trainer = SDFTTrainer(
|
| 496 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 497 |
+
args=training_args,
|
| 498 |
+
train_dataset=dataset,
|
| 499 |
+
)
|
| 500 |
+
trainer.use_teacher_server = True
|
| 501 |
+
trainer.teacher_client = RecordingTeacherClient(
|
| 502 |
+
{
|
| 503 |
+
"actual_logprobs": [[], [[-1.1], [-0.4]]],
|
| 504 |
+
"logprobs": [[], [[-1.1, -1.5], [-0.4, -0.9]]],
|
| 505 |
+
"logprob_token_ids": [[], [[14, 15], [16, 17]]],
|
| 506 |
+
}
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
device = next(trainer.model.parameters()).device
|
| 510 |
+
batch = {
|
| 511 |
+
"prompt_ids": torch.tensor([[10, 11], [12, 13]], device=device),
|
| 512 |
+
"prompt_mask": torch.tensor([[1, 1], [1, 1]], device=device),
|
| 513 |
+
"completion_ids": torch.tensor([[14, 15, 16], [17, 18, 19]], device=device),
|
| 514 |
+
"completion_mask": torch.tensor([[0, 0, 0], [1, 1, 0]], device=device),
|
| 515 |
+
"teacher_input_ids": torch.tensor([[20, 21, 22, 14, 15, 16], [23, 24, 25, 17, 18, 19]], device=device),
|
| 516 |
+
"teacher_attention_mask": torch.tensor([[1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0]], device=device),
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
loss = trainer.compute_loss(trainer.model, batch)
|
| 520 |
+
|
| 521 |
+
assert torch.isfinite(loss)
|
| 522 |
+
loss.backward()
|
| 523 |
+
assert all(torch.isfinite(p.grad).all() for p in trainer.model.parameters() if p.grad is not None)
|
| 524 |
+
assert trainer.teacher_client.calls[0]["top_logprobs"] == 2
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_sdpo_trainer.py
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import logging
|
| 16 |
+
|
| 17 |
+
import pytest
|
| 18 |
+
import torch
|
| 19 |
+
from datasets import Dataset, load_dataset
|
| 20 |
+
from transformers import TrainerCallback
|
| 21 |
+
|
| 22 |
+
from trl.experimental.sdpo import SDPOConfig, SDPOTrainer
|
| 23 |
+
|
| 24 |
+
from ..testing_utils import TrlTestCase, require_liger_kernel, require_torch_accelerator
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class SelfDistillationCaptureCallback(TrainerCallback):
|
| 28 |
+
def __init__(self):
|
| 29 |
+
self.captured_teacher_input_text = None
|
| 30 |
+
self.captured_teacher_input_texts = []
|
| 31 |
+
self.captured_self_distillation_mask = None
|
| 32 |
+
self.captured_teacher_attention_mask = None
|
| 33 |
+
self.captured_completion_mask = None
|
| 34 |
+
self.captured_old_per_token_logps = None
|
| 35 |
+
|
| 36 |
+
def on_teacher_context_built(
|
| 37 |
+
self,
|
| 38 |
+
processing_class=None,
|
| 39 |
+
teacher_input_ids=None,
|
| 40 |
+
teacher_attention_mask=None,
|
| 41 |
+
completion_mask=None,
|
| 42 |
+
self_distillation_mask=None,
|
| 43 |
+
**kwargs,
|
| 44 |
+
):
|
| 45 |
+
if self.captured_teacher_input_text is None and teacher_input_ids is not None:
|
| 46 |
+
self.captured_teacher_input_text = processing_class.decode(teacher_input_ids[0], skip_special_tokens=True)
|
| 47 |
+
if teacher_input_ids is not None:
|
| 48 |
+
self.captured_teacher_input_texts.extend(
|
| 49 |
+
processing_class.decode(ids, skip_special_tokens=True) for ids in teacher_input_ids
|
| 50 |
+
)
|
| 51 |
+
if self.captured_teacher_attention_mask is None and teacher_attention_mask is not None:
|
| 52 |
+
self.captured_teacher_attention_mask = teacher_attention_mask.detach().cpu()
|
| 53 |
+
if self.captured_completion_mask is None and completion_mask is not None:
|
| 54 |
+
self.captured_completion_mask = completion_mask.detach().cpu()
|
| 55 |
+
if self.captured_self_distillation_mask is None and self_distillation_mask is not None:
|
| 56 |
+
self.captured_self_distillation_mask = self_distillation_mask.detach().cpu()
|
| 57 |
+
|
| 58 |
+
def on_self_distillation_batch_prepared(self, old_per_token_logps=None, **kwargs):
|
| 59 |
+
if self.captured_old_per_token_logps is None and old_per_token_logps is not None:
|
| 60 |
+
self.captured_old_per_token_logps = old_per_token_logps.detach().cpu()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class RecordingTeacherClient:
|
| 64 |
+
"""Stands in for the vLLM server client and records scoring requests."""
|
| 65 |
+
|
| 66 |
+
def __init__(self, response):
|
| 67 |
+
self.response = response
|
| 68 |
+
self.calls = []
|
| 69 |
+
|
| 70 |
+
def get_sequence_logprobs(self, **kwargs):
|
| 71 |
+
self.calls.append(kwargs)
|
| 72 |
+
return self.response
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class TestSDPOTrainer(TrlTestCase):
|
| 76 |
+
def test_trust_remote_code(self):
|
| 77 |
+
dataset = Dataset.from_dict(
|
| 78 |
+
{
|
| 79 |
+
"prompt": ["Solve 2+2.", "Name the capital of France."],
|
| 80 |
+
"privileged_context": ["Example answer: 4.", "Example answer: Paris."],
|
| 81 |
+
}
|
| 82 |
+
)
|
| 83 |
+
model_id = "trl-internal-testing/tiny-RemoteForCausalLM"
|
| 84 |
+
|
| 85 |
+
with pytest.raises(ValueError, match="custom code"):
|
| 86 |
+
SDPOTrainer(
|
| 87 |
+
model=model_id,
|
| 88 |
+
reward_funcs=lambda **kwargs: [0.0] * len(kwargs["prompts"]),
|
| 89 |
+
args=SDPOConfig(output_dir=self.tmp_dir, report_to="none"),
|
| 90 |
+
train_dataset=dataset,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
trainer = SDPOTrainer(
|
| 94 |
+
model=model_id,
|
| 95 |
+
reward_funcs=lambda **kwargs: [0.0] * len(kwargs["prompts"]),
|
| 96 |
+
args=SDPOConfig(output_dir=self.tmp_dir, report_to="none", trust_remote_code=True),
|
| 97 |
+
train_dataset=dataset,
|
| 98 |
+
)
|
| 99 |
+
assert type(trainer.model).__name__ == "RemoteForCausalLM"
|
| 100 |
+
|
| 101 |
+
def test_train_with_positional_config_argument(self):
|
| 102 |
+
dataset = Dataset.from_dict(
|
| 103 |
+
{
|
| 104 |
+
"prompt": ["Solve 2+2."],
|
| 105 |
+
"privileged_context": ["Your earlier answer used the wrong format."],
|
| 106 |
+
}
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
training_args = SDPOConfig(
|
| 110 |
+
output_dir=self.tmp_dir,
|
| 111 |
+
learning_rate=0.1,
|
| 112 |
+
per_device_train_batch_size=1,
|
| 113 |
+
generation_batch_size=2,
|
| 114 |
+
num_generations=2,
|
| 115 |
+
max_completion_length=8,
|
| 116 |
+
include_environment_feedback=True,
|
| 117 |
+
max_steps=1,
|
| 118 |
+
report_to="none",
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
trainer = SDPOTrainer(
|
| 122 |
+
"trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 123 |
+
lambda **kwargs: [0.0] * len(kwargs["prompts"]),
|
| 124 |
+
training_args,
|
| 125 |
+
dataset,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
trainer.train()
|
| 129 |
+
|
| 130 |
+
assert trainer.args.output_dir == self.tmp_dir
|
| 131 |
+
assert trainer.args.include_environment_feedback is True
|
| 132 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 133 |
+
|
| 134 |
+
def test_vllm_config_defaults_match_reference_trainers(self):
|
| 135 |
+
config = SDPOConfig(output_dir=self.tmp_dir)
|
| 136 |
+
|
| 137 |
+
assert config.vllm_mode == "colocate"
|
| 138 |
+
assert config.vllm_model_impl == "vllm"
|
| 139 |
+
|
| 140 |
+
def test_train(self):
|
| 141 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 142 |
+
|
| 143 |
+
training_args = SDPOConfig(
|
| 144 |
+
output_dir=self.tmp_dir,
|
| 145 |
+
learning_rate=0.1,
|
| 146 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 147 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 148 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 149 |
+
distillation_mode="topk_logits",
|
| 150 |
+
distillation_topk=5,
|
| 151 |
+
distillation_is_clip=None,
|
| 152 |
+
report_to="none",
|
| 153 |
+
)
|
| 154 |
+
trainer = SDPOTrainer(
|
| 155 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 156 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 157 |
+
args=training_args,
|
| 158 |
+
train_dataset=dataset,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 162 |
+
|
| 163 |
+
trainer.train()
|
| 164 |
+
|
| 165 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 166 |
+
|
| 167 |
+
for n, param in previous_trainable_params.items():
|
| 168 |
+
new_param = trainer.model.get_parameter(n)
|
| 169 |
+
if param.sum() != 0:
|
| 170 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 171 |
+
|
| 172 |
+
@require_liger_kernel
|
| 173 |
+
@require_torch_accelerator
|
| 174 |
+
def test_liger_loss_matches_non_liger_loss(self):
|
| 175 |
+
dataset = Dataset.from_dict({"prompt": ["Solve 2+2."]})
|
| 176 |
+
common = dict(
|
| 177 |
+
output_dir=self.tmp_dir,
|
| 178 |
+
report_to="none",
|
| 179 |
+
per_device_train_batch_size=1,
|
| 180 |
+
generation_batch_size=2,
|
| 181 |
+
num_generations=2,
|
| 182 |
+
max_completion_length=3,
|
| 183 |
+
distillation_mode="full_logits",
|
| 184 |
+
distillation_is_clip=None,
|
| 185 |
+
distillation_weight=1.0,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
ref_trainer = SDPOTrainer(
|
| 189 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 190 |
+
reward_funcs=lambda **kwargs: [0.0] * len(kwargs["prompts"]),
|
| 191 |
+
args=SDPOConfig(use_liger_kernel=False, **common),
|
| 192 |
+
train_dataset=dataset,
|
| 193 |
+
)
|
| 194 |
+
liger_trainer = SDPOTrainer(
|
| 195 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 196 |
+
reward_funcs=lambda **kwargs: [0.0] * len(kwargs["prompts"]),
|
| 197 |
+
args=SDPOConfig(use_liger_kernel=True, **common),
|
| 198 |
+
train_dataset=dataset,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
liger_trainer.model.load_state_dict(ref_trainer.model.state_dict())
|
| 202 |
+
torch.manual_seed(0)
|
| 203 |
+
with torch.no_grad():
|
| 204 |
+
for param in ref_trainer.teacher_model.parameters():
|
| 205 |
+
param.add_(0.5 * torch.randn_like(param))
|
| 206 |
+
liger_trainer.teacher_model.load_state_dict(ref_trainer.teacher_model.state_dict())
|
| 207 |
+
|
| 208 |
+
device = next(ref_trainer.model.parameters()).device
|
| 209 |
+
batch = {
|
| 210 |
+
"prompt_ids": torch.tensor([[10, 11], [12, 13]], device=device),
|
| 211 |
+
"prompt_mask": torch.tensor([[1, 1], [1, 1]], device=device),
|
| 212 |
+
"completion_ids": torch.tensor([[14, 15, 16], [17, 18, 19]], device=device),
|
| 213 |
+
"completion_mask": torch.tensor([[1, 1, 0], [1, 1, 1]], device=device),
|
| 214 |
+
"teacher_input_ids": torch.tensor([[20, 21, 22, 14, 15, 16], [23, 24, 25, 17, 18, 19]], device=device),
|
| 215 |
+
"teacher_attention_mask": torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]], device=device),
|
| 216 |
+
"self_distillation_mask": torch.tensor([1.0, 0.0], device=device),
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
ref_trainer.model.eval()
|
| 220 |
+
liger_trainer.model.eval()
|
| 221 |
+
with torch.no_grad():
|
| 222 |
+
ref_loss = ref_trainer.compute_loss(ref_trainer.model, batch).item()
|
| 223 |
+
liger_loss = liger_trainer.compute_loss(liger_trainer.model, batch).item()
|
| 224 |
+
|
| 225 |
+
torch.testing.assert_close(
|
| 226 |
+
torch.tensor(liger_loss),
|
| 227 |
+
torch.tensor(ref_loss),
|
| 228 |
+
rtol=2e-2,
|
| 229 |
+
atol=1e-6,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def test_train_without_successful_rollouts(self):
|
| 233 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 234 |
+
|
| 235 |
+
training_args = SDPOConfig(
|
| 236 |
+
output_dir=self.tmp_dir,
|
| 237 |
+
learning_rate=0.1,
|
| 238 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 239 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 240 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 241 |
+
distillation_is_clip=None,
|
| 242 |
+
report_to="none",
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
def zero_reward(**kwargs):
|
| 246 |
+
prompts = kwargs["prompts"]
|
| 247 |
+
return [0.0] * len(prompts)
|
| 248 |
+
|
| 249 |
+
trainer = SDPOTrainer(
|
| 250 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 251 |
+
reward_funcs=zero_reward,
|
| 252 |
+
args=training_args,
|
| 253 |
+
train_dataset=dataset,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
trainer.train()
|
| 257 |
+
|
| 258 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 259 |
+
|
| 260 |
+
def test_train_populates_old_log_probs_for_distillation_clipping_when_misaligned(self):
|
| 261 |
+
dataset = Dataset.from_dict({"prompt": ["Solve 2+2.", "Solve 3+3."]})
|
| 262 |
+
|
| 263 |
+
training_args = SDPOConfig(
|
| 264 |
+
output_dir=self.tmp_dir,
|
| 265 |
+
learning_rate=0.1,
|
| 266 |
+
per_device_train_batch_size=1,
|
| 267 |
+
gradient_accumulation_steps=3,
|
| 268 |
+
steps_per_generation=2,
|
| 269 |
+
num_generations=2,
|
| 270 |
+
max_completion_length=8,
|
| 271 |
+
max_steps=1,
|
| 272 |
+
report_to="none",
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
capture_callback = SelfDistillationCaptureCallback()
|
| 276 |
+
trainer = SDPOTrainer(
|
| 277 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 278 |
+
reward_funcs=lambda **kwargs: [0.0] * len(kwargs["prompts"]),
|
| 279 |
+
args=training_args,
|
| 280 |
+
train_dataset=dataset,
|
| 281 |
+
callbacks=[capture_callback],
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
trainer.train()
|
| 285 |
+
|
| 286 |
+
assert capture_callback.captured_old_per_token_logps is not None
|
| 287 |
+
|
| 288 |
+
def test_evaluation_uses_num_generations_eval_for_teacher_grouping(self):
|
| 289 |
+
eval_dataset = Dataset.from_dict({"prompt": ["Alpha prompt", "Beta prompt", "Gamma prompt", "Delta prompt"]})
|
| 290 |
+
|
| 291 |
+
training_args = SDPOConfig(
|
| 292 |
+
output_dir=self.tmp_dir,
|
| 293 |
+
learning_rate=0.1,
|
| 294 |
+
per_device_train_batch_size=1,
|
| 295 |
+
per_device_eval_batch_size=4,
|
| 296 |
+
generation_batch_size=3,
|
| 297 |
+
num_generations=3,
|
| 298 |
+
num_generations_eval=2,
|
| 299 |
+
max_completion_length=8,
|
| 300 |
+
success_reward_threshold=0.5,
|
| 301 |
+
dont_reprompt_on_self_success=False,
|
| 302 |
+
distillation_is_clip=None,
|
| 303 |
+
max_steps=1,
|
| 304 |
+
report_to="none",
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
def eval_rewards(**kwargs):
|
| 308 |
+
prompts = kwargs["prompts"]
|
| 309 |
+
if len(prompts) == 4 and prompts.count("Alpha prompt") == 2 and prompts.count("Beta prompt") == 2:
|
| 310 |
+
return [1.0, 0.0, 0.0, 0.0]
|
| 311 |
+
return [0.0] * len(prompts)
|
| 312 |
+
|
| 313 |
+
capture_callback = SelfDistillationCaptureCallback()
|
| 314 |
+
trainer = SDPOTrainer(
|
| 315 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 316 |
+
reward_funcs=eval_rewards,
|
| 317 |
+
args=training_args,
|
| 318 |
+
train_dataset=eval_dataset.select(range(1)),
|
| 319 |
+
eval_dataset=eval_dataset,
|
| 320 |
+
callbacks=[capture_callback],
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
trainer.evaluate()
|
| 324 |
+
|
| 325 |
+
assert capture_callback.captured_teacher_input_texts
|
| 326 |
+
alpha_teachers = [text for text in capture_callback.captured_teacher_input_texts if "Alpha prompt" in text]
|
| 327 |
+
beta_teachers = [text for text in capture_callback.captured_teacher_input_texts if "Beta prompt" in text]
|
| 328 |
+
assert alpha_teachers
|
| 329 |
+
assert beta_teachers
|
| 330 |
+
assert any("Correct solution:" in text for text in alpha_teachers)
|
| 331 |
+
assert all("Correct solution:" not in text for text in beta_teachers)
|
| 332 |
+
|
| 333 |
+
def test_teacher_reprompt_preserves_curly_braces_in_solution_and_feedback(self):
|
| 334 |
+
dataset = Dataset.from_dict(
|
| 335 |
+
{
|
| 336 |
+
"prompt": ["Solve f(x) = {x^2}."],
|
| 337 |
+
"privileged_context": ['Feedback: use {"x": 2} as a check.'],
|
| 338 |
+
}
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
training_args = SDPOConfig(
|
| 342 |
+
output_dir=self.tmp_dir,
|
| 343 |
+
learning_rate=0.1,
|
| 344 |
+
per_device_train_batch_size=1,
|
| 345 |
+
generation_batch_size=2,
|
| 346 |
+
num_generations=2,
|
| 347 |
+
max_completion_length=8,
|
| 348 |
+
include_environment_feedback=True,
|
| 349 |
+
success_reward_threshold=0.5,
|
| 350 |
+
dont_reprompt_on_self_success=False,
|
| 351 |
+
max_steps=1,
|
| 352 |
+
report_to="none",
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
def reward_with_one_success(**kwargs):
|
| 356 |
+
prompts = kwargs["prompts"]
|
| 357 |
+
return [1.0, 0.0][: len(prompts)]
|
| 358 |
+
|
| 359 |
+
capture_callback = SelfDistillationCaptureCallback()
|
| 360 |
+
trainer = SDPOTrainer(
|
| 361 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 362 |
+
reward_funcs=reward_with_one_success,
|
| 363 |
+
args=training_args,
|
| 364 |
+
train_dataset=dataset,
|
| 365 |
+
callbacks=[capture_callback],
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
trainer.train()
|
| 369 |
+
|
| 370 |
+
assert capture_callback.captured_teacher_input_text is not None
|
| 371 |
+
assert "Solve f(x) = {x^2}." in capture_callback.captured_teacher_input_text
|
| 372 |
+
assert 'Feedback: use {"x": 2} as a check.' in capture_callback.captured_teacher_input_text
|
| 373 |
+
assert "{{" not in capture_callback.captured_teacher_input_text
|
| 374 |
+
assert "}}" not in capture_callback.captured_teacher_input_text
|
| 375 |
+
|
| 376 |
+
def test_train_with_conversational_prompts_preserves_context(self):
|
| 377 |
+
dataset = Dataset.from_dict(
|
| 378 |
+
{
|
| 379 |
+
"prompt": [
|
| 380 |
+
[
|
| 381 |
+
{"role": "system", "content": "You are a careful assistant."},
|
| 382 |
+
{"role": "user", "content": "Solve 2+2."},
|
| 383 |
+
]
|
| 384 |
+
]
|
| 385 |
+
}
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
training_args = SDPOConfig(
|
| 389 |
+
output_dir=self.tmp_dir,
|
| 390 |
+
learning_rate=0.1,
|
| 391 |
+
per_device_train_batch_size=1,
|
| 392 |
+
generation_batch_size=2,
|
| 393 |
+
num_generations=2,
|
| 394 |
+
max_completion_length=8,
|
| 395 |
+
distillation_is_clip=None,
|
| 396 |
+
success_reward_threshold=0.5,
|
| 397 |
+
max_steps=1,
|
| 398 |
+
report_to="none",
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
def first_only_reward(**kwargs):
|
| 402 |
+
"""Only the first sample in each group succeeds — exercises dont_reprompt_on_self_success default."""
|
| 403 |
+
return [1.0, 0.0][: len(kwargs["prompts"])]
|
| 404 |
+
|
| 405 |
+
capture_callback = SelfDistillationCaptureCallback()
|
| 406 |
+
trainer = SDPOTrainer(
|
| 407 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 408 |
+
reward_funcs=first_only_reward,
|
| 409 |
+
args=training_args,
|
| 410 |
+
train_dataset=dataset,
|
| 411 |
+
callbacks=[capture_callback],
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
trainer.train()
|
| 415 |
+
|
| 416 |
+
# With dont_reprompt_on_self_success=True (default), sample 0 skips itself,
|
| 417 |
+
# but sample 1 finds sample 0's success and gets a teacher reprompt.
|
| 418 |
+
assert capture_callback.captured_teacher_input_text is not None
|
| 419 |
+
assert "careful assistant" in capture_callback.captured_teacher_input_text
|
| 420 |
+
assert "Solve 2+2" in capture_callback.captured_teacher_input_text
|
| 421 |
+
assert capture_callback.captured_self_distillation_mask is not None
|
| 422 |
+
|
| 423 |
+
def test_train_with_feedback_only_reprompts_teacher(self):
|
| 424 |
+
dataset = Dataset.from_dict(
|
| 425 |
+
{
|
| 426 |
+
"prompt": [
|
| 427 |
+
[
|
| 428 |
+
{"role": "system", "content": "You are a careful assistant."},
|
| 429 |
+
{"role": "user", "content": "Try the puzzle again."},
|
| 430 |
+
]
|
| 431 |
+
],
|
| 432 |
+
"privileged_context": ["Your earlier answer violated the format requirements."],
|
| 433 |
+
}
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
training_args = SDPOConfig(
|
| 437 |
+
output_dir=self.tmp_dir,
|
| 438 |
+
learning_rate=0.1,
|
| 439 |
+
per_device_train_batch_size=1,
|
| 440 |
+
generation_batch_size=2,
|
| 441 |
+
num_generations=2,
|
| 442 |
+
max_completion_length=8,
|
| 443 |
+
distillation_is_clip=None,
|
| 444 |
+
include_environment_feedback=True,
|
| 445 |
+
max_steps=1,
|
| 446 |
+
report_to="none",
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
def zero_reward(**kwargs):
|
| 450 |
+
prompts = kwargs["prompts"]
|
| 451 |
+
return [0.0] * len(prompts)
|
| 452 |
+
|
| 453 |
+
capture_callback = SelfDistillationCaptureCallback()
|
| 454 |
+
trainer = SDPOTrainer(
|
| 455 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 456 |
+
reward_funcs=zero_reward,
|
| 457 |
+
args=training_args,
|
| 458 |
+
train_dataset=dataset,
|
| 459 |
+
callbacks=[capture_callback],
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
trainer.train()
|
| 463 |
+
|
| 464 |
+
assert capture_callback.captured_teacher_input_text is not None
|
| 465 |
+
assert "format requirements" in capture_callback.captured_teacher_input_text
|
| 466 |
+
assert capture_callback.captured_self_distillation_mask is not None
|
| 467 |
+
assert capture_callback.captured_self_distillation_mask[0].item() == 1.0
|
| 468 |
+
|
| 469 |
+
def test_train_warns_when_sdpo_rewards_are_flat(self, caplog):
|
| 470 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 471 |
+
|
| 472 |
+
training_args = SDPOConfig(
|
| 473 |
+
output_dir=self.tmp_dir,
|
| 474 |
+
learning_rate=0.1,
|
| 475 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 476 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 477 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 478 |
+
diagnostics_warning_interval=2,
|
| 479 |
+
max_steps=2,
|
| 480 |
+
report_to="none",
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
def zero_reward(**kwargs):
|
| 484 |
+
return [0.0] * len(kwargs["prompts"])
|
| 485 |
+
|
| 486 |
+
trainer = SDPOTrainer(
|
| 487 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 488 |
+
reward_funcs=zero_reward,
|
| 489 |
+
args=training_args,
|
| 490 |
+
train_dataset=dataset,
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
with caplog.at_level(logging.WARNING):
|
| 494 |
+
trainer.train()
|
| 495 |
+
|
| 496 |
+
assert "Observed flat SDPO rewards across all sampled generations" in caplog.text
|
| 497 |
+
assert "SDPO self-distillation is inactive because no reprompted samples were constructed" in caplog.text
|
| 498 |
+
|
| 499 |
+
def test_train_preserves_teacher_completion_attention_mask(self):
|
| 500 |
+
dataset = Dataset.from_dict({"prompt": ["Solve 2+2."]})
|
| 501 |
+
|
| 502 |
+
training_args = SDPOConfig(
|
| 503 |
+
output_dir=self.tmp_dir,
|
| 504 |
+
learning_rate=0.1,
|
| 505 |
+
per_device_train_batch_size=1,
|
| 506 |
+
generation_batch_size=2,
|
| 507 |
+
num_generations=2,
|
| 508 |
+
max_completion_length=8,
|
| 509 |
+
success_reward_threshold=0.5,
|
| 510 |
+
max_steps=1,
|
| 511 |
+
report_to="none",
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
def first_only_reward(**kwargs):
|
| 515 |
+
return [1.0, 0.0][: len(kwargs["prompts"])]
|
| 516 |
+
|
| 517 |
+
capture_callback = SelfDistillationCaptureCallback()
|
| 518 |
+
trainer = SDPOTrainer(
|
| 519 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 520 |
+
reward_funcs=first_only_reward,
|
| 521 |
+
args=training_args,
|
| 522 |
+
train_dataset=dataset,
|
| 523 |
+
callbacks=[capture_callback],
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
trainer.train()
|
| 527 |
+
|
| 528 |
+
assert capture_callback.captured_teacher_attention_mask is not None
|
| 529 |
+
assert capture_callback.captured_completion_mask is not None
|
| 530 |
+
|
| 531 |
+
completion_length = capture_callback.captured_completion_mask.shape[1]
|
| 532 |
+
teacher_completion_attention = capture_callback.captured_teacher_attention_mask[0, -completion_length:]
|
| 533 |
+
assert torch.equal(teacher_completion_attention, capture_callback.captured_completion_mask[0])
|
| 534 |
+
|
| 535 |
+
def test_server_loss_finite_with_masked_and_padded_rows(self):
|
| 536 |
+
# Drives the teacher-server path through `compute_loss` with a fake server client: row 0 is fully masked
|
| 537 |
+
# (zero-length scored completion) and row 1 has a shorter completion than the padded batch, so the client
|
| 538 |
+
# response is ragged and the padded tail comes back as -inf. Neither may leak NaN or inf.
|
| 539 |
+
dataset = Dataset.from_dict({"prompt": ["Solve 2+2."], "privileged_context": ["Example answer: 4."]})
|
| 540 |
+
training_args = SDPOConfig(
|
| 541 |
+
output_dir=self.tmp_dir,
|
| 542 |
+
per_device_train_batch_size=1,
|
| 543 |
+
max_completion_length=3,
|
| 544 |
+
num_generations=1,
|
| 545 |
+
distillation_mode="topk_logits",
|
| 546 |
+
distillation_topk=2,
|
| 547 |
+
distillation_alpha=0.5,
|
| 548 |
+
distillation_add_tail=True,
|
| 549 |
+
distillation_is_clip=None,
|
| 550 |
+
report_to="none",
|
| 551 |
+
)
|
| 552 |
+
trainer = SDPOTrainer(
|
| 553 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 554 |
+
reward_funcs=lambda **kwargs: [0.0] * len(kwargs["prompts"]),
|
| 555 |
+
args=training_args,
|
| 556 |
+
train_dataset=dataset,
|
| 557 |
+
)
|
| 558 |
+
trainer.use_teacher_server = True
|
| 559 |
+
trainer.teacher_client = RecordingTeacherClient(
|
| 560 |
+
{
|
| 561 |
+
"actual_logprobs": [[], [[-1.1], [-0.4]]],
|
| 562 |
+
"logprobs": [[], [[-1.1, -1.5], [-0.4, -0.9]]],
|
| 563 |
+
"logprob_token_ids": [[], [[14, 15], [16, 17]]],
|
| 564 |
+
}
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
device = next(trainer.model.parameters()).device
|
| 568 |
+
batch = {
|
| 569 |
+
"prompt_ids": torch.tensor([[10, 11], [12, 13]], device=device),
|
| 570 |
+
"prompt_mask": torch.tensor([[1, 1], [1, 1]], device=device),
|
| 571 |
+
"completion_ids": torch.tensor([[14, 15, 16], [17, 18, 19]], device=device),
|
| 572 |
+
"completion_mask": torch.tensor([[0, 0, 0], [1, 1, 0]], device=device),
|
| 573 |
+
"teacher_input_ids": torch.tensor([[20, 21, 22, 14, 15, 16], [23, 24, 25, 17, 18, 19]], device=device),
|
| 574 |
+
"teacher_attention_mask": torch.tensor([[1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0]], device=device),
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
loss = trainer.compute_loss(trainer.model, batch)
|
| 578 |
+
|
| 579 |
+
assert torch.isfinite(loss)
|
| 580 |
+
loss.backward()
|
| 581 |
+
assert all(torch.isfinite(p.grad).all() for p in trainer.model.parameters() if p.grad is not None)
|
| 582 |
+
assert trainer.teacher_client.calls[0]["top_logprobs"] == 2
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_self_distillation_trainer_behavior.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import logging
|
| 16 |
+
from collections import defaultdict
|
| 17 |
+
from types import SimpleNamespace
|
| 18 |
+
|
| 19 |
+
import pytest
|
| 20 |
+
import torch
|
| 21 |
+
from datasets import Dataset
|
| 22 |
+
from transformers import AutoModelForCausalLM, TrainerControl, TrainerState, TrainingArguments
|
| 23 |
+
from transformers.utils import is_peft_available
|
| 24 |
+
|
| 25 |
+
from trl.experimental.sdft import SDFTConfig, SDFTTrainer
|
| 26 |
+
from trl.experimental.sdft.loss_utils import (
|
| 27 |
+
apply_importance_sampling_clipping,
|
| 28 |
+
compute_full_logit_self_distillation_loss,
|
| 29 |
+
compute_sampled_token_self_distillation_loss,
|
| 30 |
+
compute_topk_self_distillation_loss,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
from ..testing_utils import TrlTestCase
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if is_peft_available():
|
| 37 |
+
from peft import LoraConfig, get_peft_model, get_peft_model_state_dict
|
| 38 |
+
|
| 39 |
+
from trl.experimental.sdft.teacher_sync import PEFTAdapterEMACallback
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class TestSelfDistillationTrainerBehavior(TrlTestCase):
|
| 43 |
+
@staticmethod
|
| 44 |
+
def _make_loss_test_trainer(**args_overrides):
|
| 45 |
+
trainer = object.__new__(SDFTTrainer)
|
| 46 |
+
args = {
|
| 47 |
+
"distillation_mode": "sampled_token",
|
| 48 |
+
"distillation_topk": None,
|
| 49 |
+
"distillation_alpha": 1.0,
|
| 50 |
+
"distillation_add_tail": False,
|
| 51 |
+
"distillation_is_clip": None,
|
| 52 |
+
}
|
| 53 |
+
args.update(args_overrides)
|
| 54 |
+
trainer.args = SimpleNamespace(**args)
|
| 55 |
+
trainer.accelerator = SimpleNamespace(gather=lambda tensor: tensor)
|
| 56 |
+
trainer._metrics = {
|
| 57 |
+
"train": defaultdict(list),
|
| 58 |
+
"eval": defaultdict(list),
|
| 59 |
+
}
|
| 60 |
+
trainer._name = "SDFT"
|
| 61 |
+
return trainer
|
| 62 |
+
|
| 63 |
+
def test_full_logit_loss_matches_forward_kl(self):
|
| 64 |
+
student_probs = torch.tensor([[[0.8, 0.2]]], dtype=torch.float32)
|
| 65 |
+
teacher_probs = torch.tensor([[[0.5, 0.5]]], dtype=torch.float32)
|
| 66 |
+
|
| 67 |
+
loss = compute_full_logit_self_distillation_loss(
|
| 68 |
+
student_probs.log(),
|
| 69 |
+
teacher_probs.log(),
|
| 70 |
+
distillation_alpha=0.0,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
expected_loss = teacher_probs[0, 0, 0] * (
|
| 74 |
+
teacher_probs[0, 0, 0].log() - student_probs[0, 0, 0].log()
|
| 75 |
+
) + teacher_probs[0, 0, 1] * (teacher_probs[0, 0, 1].log() - student_probs[0, 0, 1].log())
|
| 76 |
+
torch.testing.assert_close(loss, expected_loss.reshape(1, 1))
|
| 77 |
+
|
| 78 |
+
def test_sampled_token_loss_uses_selected_completion_ids(self):
|
| 79 |
+
student_probs = torch.tensor([[[0.1, 0.9], [0.7, 0.3]]], dtype=torch.float32)
|
| 80 |
+
teacher_probs = torch.tensor([[[0.4, 0.6], [0.2, 0.8]]], dtype=torch.float32)
|
| 81 |
+
completion_ids = torch.tensor([[1, 0]])
|
| 82 |
+
|
| 83 |
+
loss = compute_sampled_token_self_distillation_loss(
|
| 84 |
+
student_probs.log(),
|
| 85 |
+
teacher_probs.log(),
|
| 86 |
+
completion_ids,
|
| 87 |
+
distillation_alpha=1.0,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
expected_student_logps = torch.tensor([[0.9, 0.7]], dtype=torch.float32).log()
|
| 91 |
+
expected_teacher_logps = torch.tensor([[0.6, 0.2]], dtype=torch.float32).log()
|
| 92 |
+
expected_loss = (expected_student_logps - expected_teacher_logps) * expected_student_logps
|
| 93 |
+
torch.testing.assert_close(loss, expected_loss)
|
| 94 |
+
|
| 95 |
+
def test_topk_loss_renormalizes_selected_student_support(self):
|
| 96 |
+
student_probs = torch.tensor([[[0.5, 0.3, 0.2]]], dtype=torch.float32)
|
| 97 |
+
teacher_probs = torch.tensor([[[0.2, 0.6, 0.2]]], dtype=torch.float32)
|
| 98 |
+
|
| 99 |
+
loss = compute_topk_self_distillation_loss(
|
| 100 |
+
student_probs.log(),
|
| 101 |
+
teacher_probs.log(),
|
| 102 |
+
distillation_topk=2,
|
| 103 |
+
distillation_alpha=0.0,
|
| 104 |
+
distillation_add_tail=False,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
student_topk = torch.tensor([0.5, 0.3], dtype=torch.float32)
|
| 108 |
+
student_topk = student_topk / student_topk.sum()
|
| 109 |
+
teacher_topk = torch.tensor([0.2, 0.6], dtype=torch.float32)
|
| 110 |
+
teacher_topk = teacher_topk / teacher_topk.sum()
|
| 111 |
+
expected_loss = (teacher_topk * (teacher_topk.log() - student_topk.log())).sum()
|
| 112 |
+
torch.testing.assert_close(loss, expected_loss.reshape(1, 1))
|
| 113 |
+
|
| 114 |
+
def test_topk_loss_can_include_tail_bucket(self):
|
| 115 |
+
student_probs = torch.tensor([[[0.5, 0.3, 0.2]]], dtype=torch.float32)
|
| 116 |
+
teacher_probs = torch.tensor([[[0.2, 0.6, 0.2]]], dtype=torch.float32)
|
| 117 |
+
|
| 118 |
+
loss = compute_topk_self_distillation_loss(
|
| 119 |
+
student_probs.log(),
|
| 120 |
+
teacher_probs.log(),
|
| 121 |
+
distillation_topk=2,
|
| 122 |
+
distillation_alpha=0.0,
|
| 123 |
+
distillation_add_tail=True,
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
student_with_tail = torch.tensor([0.5, 0.3, 0.2], dtype=torch.float32)
|
| 127 |
+
teacher_with_tail = torch.tensor([0.2, 0.6, 0.2], dtype=torch.float32)
|
| 128 |
+
expected_loss = (teacher_with_tail * (teacher_with_tail.log() - student_with_tail.log())).sum()
|
| 129 |
+
torch.testing.assert_close(loss, expected_loss.reshape(1, 1))
|
| 130 |
+
|
| 131 |
+
def test_importance_sampling_clipping_caps_token_ratio(self):
|
| 132 |
+
per_token_loss = torch.tensor([[1.0, 2.0]])
|
| 133 |
+
student_log_probs = torch.tensor([[0.4, 0.3]], dtype=torch.float32).log()
|
| 134 |
+
old_log_probs = torch.tensor([[0.1, 0.2]], dtype=torch.float32).log()
|
| 135 |
+
|
| 136 |
+
loss = apply_importance_sampling_clipping(
|
| 137 |
+
per_token_loss,
|
| 138 |
+
student_log_probs,
|
| 139 |
+
old_log_probs,
|
| 140 |
+
clip_coeff=2.0,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
torch.testing.assert_close(loss, torch.tensor([[2.0, 3.0]]))
|
| 144 |
+
|
| 145 |
+
def test_teacher_model_kind_live_uses_student_model(self):
|
| 146 |
+
dataset = Dataset.from_dict({"prompt": ["Solve 2+2."]})
|
| 147 |
+
training_args = SDFTConfig(
|
| 148 |
+
output_dir=self.tmp_dir,
|
| 149 |
+
per_device_train_batch_size=1,
|
| 150 |
+
max_completion_length=8,
|
| 151 |
+
max_steps=1,
|
| 152 |
+
num_generations=1,
|
| 153 |
+
teacher_model_kind="live",
|
| 154 |
+
report_to="none",
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
trainer = SDFTTrainer(
|
| 158 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 159 |
+
args=training_args,
|
| 160 |
+
train_dataset=dataset,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
assert trainer.teacher_model is trainer.model
|
| 164 |
+
|
| 165 |
+
@pytest.mark.skipif(not is_peft_available(), reason="PEFT is required for this test")
|
| 166 |
+
def test_warns_when_initial_student_already_has_a_peft_adapter(self, caplog):
|
| 167 |
+
dataset = Dataset.from_dict({"prompt": ["Solve 2+2."]})
|
| 168 |
+
training_args = SDFTConfig(
|
| 169 |
+
output_dir=self.tmp_dir,
|
| 170 |
+
per_device_train_batch_size=1,
|
| 171 |
+
max_completion_length=8,
|
| 172 |
+
max_steps=1,
|
| 173 |
+
num_generations=1,
|
| 174 |
+
teacher_model_kind="base",
|
| 175 |
+
report_to="none",
|
| 176 |
+
)
|
| 177 |
+
model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
|
| 178 |
+
model = get_peft_model(
|
| 179 |
+
model,
|
| 180 |
+
LoraConfig(
|
| 181 |
+
r=4,
|
| 182 |
+
lora_alpha=8,
|
| 183 |
+
target_modules=["q_proj", "v_proj"],
|
| 184 |
+
bias="none",
|
| 185 |
+
task_type="CAUSAL_LM",
|
| 186 |
+
),
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
with caplog.at_level(logging.WARNING, logger="trl.experimental.sdft.sdft_trainer"):
|
| 190 |
+
SDFTTrainer(
|
| 191 |
+
model=model,
|
| 192 |
+
args=training_args,
|
| 193 |
+
train_dataset=dataset,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
assert "already contains a PEFT adapter" in caplog.text
|
| 197 |
+
assert "`teacher_model_kind='base'` may refer to the underlying base weights" in caplog.text
|
| 198 |
+
|
| 199 |
+
@pytest.mark.skipif(not is_peft_available(), reason="PEFT is required for this test")
|
| 200 |
+
def test_peft_adapter_ema_callback_updates_teacher_adapter(self):
|
| 201 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 202 |
+
"trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 203 |
+
device_map="cpu",
|
| 204 |
+
)
|
| 205 |
+
model = get_peft_model(
|
| 206 |
+
model,
|
| 207 |
+
LoraConfig(
|
| 208 |
+
task_type="CAUSAL_LM",
|
| 209 |
+
target_modules=["q_proj", "v_proj"],
|
| 210 |
+
r=8,
|
| 211 |
+
),
|
| 212 |
+
adapter_name="default",
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
update_rate = 0.5
|
| 216 |
+
callback = PEFTAdapterEMACallback(
|
| 217 |
+
model=model,
|
| 218 |
+
teacher_adapter_name="teacher",
|
| 219 |
+
update_rate=update_rate,
|
| 220 |
+
sync_steps=1,
|
| 221 |
+
)
|
| 222 |
+
args = TrainingArguments(output_dir=self.tmp_dir, report_to="none")
|
| 223 |
+
state = TrainerState(global_step=0)
|
| 224 |
+
control = TrainerControl()
|
| 225 |
+
|
| 226 |
+
callback.on_train_begin(args, state, control)
|
| 227 |
+
|
| 228 |
+
assert "teacher" in model.peft_config
|
| 229 |
+
assert callback.shadow_weights is not None
|
| 230 |
+
teacher_state = get_peft_model_state_dict(model, adapter_name="teacher")
|
| 231 |
+
for key, param in teacher_state.items():
|
| 232 |
+
assert torch.all(param == 0), f"Teacher param {key} should be zero-initialized"
|
| 233 |
+
|
| 234 |
+
student_state = {
|
| 235 |
+
key: value.clone() for key, value in get_peft_model_state_dict(model, adapter_name="default").items()
|
| 236 |
+
}
|
| 237 |
+
assert set(callback.shadow_weights.keys()) == set(student_state.keys())
|
| 238 |
+
|
| 239 |
+
state.global_step = 1
|
| 240 |
+
callback.on_step_end(args, state, control)
|
| 241 |
+
|
| 242 |
+
for key in callback.shadow_weights:
|
| 243 |
+
expected = update_rate * student_state[key]
|
| 244 |
+
torch.testing.assert_close(callback.shadow_weights[key], expected)
|
| 245 |
+
|
| 246 |
+
teacher_state = get_peft_model_state_dict(model, adapter_name="teacher")
|
| 247 |
+
for key in teacher_state:
|
| 248 |
+
torch.testing.assert_close(teacher_state[key].float(), callback.shadow_weights[key])
|
| 249 |
+
|
| 250 |
+
@pytest.mark.parametrize("teacher_model_kind", ["base", "ema"])
|
| 251 |
+
def test_teacher_model_kind_base_and_ema_use_frozen_teacher_copy(self, teacher_model_kind):
|
| 252 |
+
dataset = Dataset.from_dict({"prompt": ["Solve 2+2."]})
|
| 253 |
+
training_args = SDFTConfig(
|
| 254 |
+
output_dir=self.tmp_dir,
|
| 255 |
+
per_device_train_batch_size=1,
|
| 256 |
+
max_completion_length=8,
|
| 257 |
+
max_steps=1,
|
| 258 |
+
num_generations=1,
|
| 259 |
+
teacher_model_kind=teacher_model_kind,
|
| 260 |
+
report_to="none",
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
trainer = SDFTTrainer(
|
| 264 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 265 |
+
args=training_args,
|
| 266 |
+
train_dataset=dataset,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
assert trainer.teacher_model is not trainer.model
|
| 270 |
+
assert trainer.teacher_model.training is False
|
| 271 |
+
|
| 272 |
+
student_param = next(trainer.model.parameters())
|
| 273 |
+
teacher_param = next(trainer.teacher_model.parameters())
|
| 274 |
+
assert teacher_param.requires_grad is False
|
| 275 |
+
assert teacher_param.data_ptr() != student_param.data_ptr()
|
| 276 |
+
|
| 277 |
+
def test_compute_self_distillation_loss_ignores_masked_completion_tokens(self):
|
| 278 |
+
trainer = self._make_loss_test_trainer(
|
| 279 |
+
distillation_mode="full_logits",
|
| 280 |
+
distillation_alpha=0.0,
|
| 281 |
+
)
|
| 282 |
+
model = SimpleNamespace(training=True)
|
| 283 |
+
|
| 284 |
+
student_probs = torch.tensor([[[0.8, 0.2], [0.01, 0.99]]], dtype=torch.float32)
|
| 285 |
+
teacher_probs = torch.tensor([[[0.5, 0.5], [0.99, 0.01]]], dtype=torch.float32)
|
| 286 |
+
distillation_logits = SimpleNamespace(
|
| 287 |
+
completion_ids=torch.tensor([[0, 1]], dtype=torch.long),
|
| 288 |
+
loss_mask=torch.tensor([[1, 0]], dtype=torch.long),
|
| 289 |
+
student_logits=student_probs.log(),
|
| 290 |
+
teacher_logits=teacher_probs.log(),
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
loss = trainer._compute_self_distillation_loss(model, {}, distillation_logits)
|
| 294 |
+
|
| 295 |
+
expected_active_token_loss = teacher_probs[0, 0, 0] * (
|
| 296 |
+
teacher_probs[0, 0, 0].log() - student_probs[0, 0, 0].log()
|
| 297 |
+
) + teacher_probs[0, 0, 1] * (teacher_probs[0, 0, 1].log() - student_probs[0, 0, 1].log())
|
| 298 |
+
torch.testing.assert_close(loss, expected_active_token_loss)
|
| 299 |
+
torch.testing.assert_close(
|
| 300 |
+
torch.tensor(trainer._metrics["train"]["self_distillation/distillation_loss"]),
|
| 301 |
+
expected_active_token_loss.unsqueeze(0),
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
def test_compute_self_distillation_loss_applies_importance_sampling_clip(self):
|
| 305 |
+
trainer = self._make_loss_test_trainer(distillation_is_clip=2.0)
|
| 306 |
+
model = SimpleNamespace(training=True)
|
| 307 |
+
|
| 308 |
+
student_token_probs = torch.tensor([[0.2, 0.4]], dtype=torch.float32)
|
| 309 |
+
teacher_token_probs = torch.tensor([[0.5, 0.5]], dtype=torch.float32)
|
| 310 |
+
old_token_probs = torch.tensor([[0.05, 0.4]], dtype=torch.float32)
|
| 311 |
+
clip_coeff = trainer.args.distillation_is_clip
|
| 312 |
+
|
| 313 |
+
distillation_logits = SimpleNamespace(
|
| 314 |
+
completion_ids=torch.tensor([[0, 1]], dtype=torch.long),
|
| 315 |
+
loss_mask=torch.tensor([[1, 1]], dtype=torch.long),
|
| 316 |
+
student_logits=torch.log(torch.tensor([[[0.2, 0.8], [0.6, 0.4]]], dtype=torch.float32)),
|
| 317 |
+
teacher_logits=torch.log(torch.tensor([[[0.5, 0.5], [0.5, 0.5]]], dtype=torch.float32)),
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
loss = trainer._compute_self_distillation_loss(
|
| 321 |
+
model,
|
| 322 |
+
{"old_per_token_logps": old_token_probs.log()},
|
| 323 |
+
distillation_logits,
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
raw_per_token_loss = (student_token_probs.log() - teacher_token_probs.log()) * student_token_probs.log()
|
| 327 |
+
clipped_ratio = torch.minimum(
|
| 328 |
+
student_token_probs / old_token_probs, torch.full_like(student_token_probs, clip_coeff)
|
| 329 |
+
)
|
| 330 |
+
expected_loss = (raw_per_token_loss * clipped_ratio).mean()
|
| 331 |
+
|
| 332 |
+
torch.testing.assert_close(loss, expected_loss)
|
| 333 |
+
torch.testing.assert_close(
|
| 334 |
+
torch.tensor(trainer._metrics["train"]["self_distillation/distillation_loss"]),
|
| 335 |
+
expected_loss.unsqueeze(0),
|
| 336 |
+
)
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_ssd_trainer.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 pytest
|
| 16 |
+
from datasets import load_dataset
|
| 17 |
+
from transformers.utils import is_peft_available
|
| 18 |
+
|
| 19 |
+
from trl.experimental.ssd import SSDConfig, SSDTrainer
|
| 20 |
+
|
| 21 |
+
from ..testing_utils import TrlTestCase, require_peft
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if is_peft_available():
|
| 25 |
+
from peft import LoraConfig
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TestSSDTrainer(TrlTestCase):
|
| 29 |
+
def test_vllm_config_defaults_match_reference_trainers(self):
|
| 30 |
+
config = SSDConfig(output_dir=self.tmp_dir)
|
| 31 |
+
|
| 32 |
+
assert config.vllm_mode == "colocate"
|
| 33 |
+
assert config.vllm_model_impl == "vllm"
|
| 34 |
+
|
| 35 |
+
def test_train_with_string_prompts(self):
|
| 36 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 37 |
+
|
| 38 |
+
training_args = SSDConfig(
|
| 39 |
+
output_dir=self.tmp_dir,
|
| 40 |
+
learning_rate=0.1,
|
| 41 |
+
per_device_train_batch_size=1,
|
| 42 |
+
max_completion_length=8,
|
| 43 |
+
max_steps=1,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
trainer = SSDTrainer(
|
| 47 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 48 |
+
args=training_args,
|
| 49 |
+
train_dataset=dataset,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
trainer.train()
|
| 53 |
+
|
| 54 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 55 |
+
|
| 56 |
+
def test_trust_remote_code(self):
|
| 57 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 58 |
+
model_id = "trl-internal-testing/tiny-RemoteForCausalLM"
|
| 59 |
+
|
| 60 |
+
with pytest.raises(ValueError, match="custom code"):
|
| 61 |
+
SSDTrainer(
|
| 62 |
+
model=model_id,
|
| 63 |
+
args=SSDConfig(output_dir=self.tmp_dir, report_to="none"),
|
| 64 |
+
train_dataset=dataset,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
trainer = SSDTrainer(
|
| 68 |
+
model=model_id,
|
| 69 |
+
args=SSDConfig(output_dir=self.tmp_dir, report_to="none", trust_remote_code=True),
|
| 70 |
+
train_dataset=dataset,
|
| 71 |
+
)
|
| 72 |
+
assert type(trainer.model).__name__ == "RemoteForCausalLM"
|
| 73 |
+
|
| 74 |
+
def test_train_with_chat_prompts(self):
|
| 75 |
+
dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train")
|
| 76 |
+
|
| 77 |
+
training_args = SSDConfig(
|
| 78 |
+
output_dir=self.tmp_dir,
|
| 79 |
+
learning_rate=0.1,
|
| 80 |
+
per_device_train_batch_size=1,
|
| 81 |
+
max_completion_length=8,
|
| 82 |
+
max_steps=1,
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
trainer = SSDTrainer(
|
| 86 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 87 |
+
args=training_args,
|
| 88 |
+
train_dataset=dataset,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
trainer.train()
|
| 92 |
+
|
| 93 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 94 |
+
|
| 95 |
+
def test_train_with_temperature_and_truncation(self):
|
| 96 |
+
"""Test with SSD-paper-style hyperparameters: T_train=0.6, top_k=20, top_p=0.95."""
|
| 97 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 98 |
+
|
| 99 |
+
training_args = SSDConfig(
|
| 100 |
+
output_dir=self.tmp_dir,
|
| 101 |
+
learning_rate=5e-6,
|
| 102 |
+
per_device_train_batch_size=1,
|
| 103 |
+
max_completion_length=16,
|
| 104 |
+
max_steps=1,
|
| 105 |
+
temperature=0.6,
|
| 106 |
+
top_k=20,
|
| 107 |
+
top_p=0.95,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
trainer = SSDTrainer(
|
| 111 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 112 |
+
args=training_args,
|
| 113 |
+
train_dataset=dataset,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
trainer.train()
|
| 117 |
+
|
| 118 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 119 |
+
|
| 120 |
+
def test_train_reuses_buffered_generation_batches(self):
|
| 121 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 122 |
+
|
| 123 |
+
training_args = SSDConfig(
|
| 124 |
+
output_dir=self.tmp_dir,
|
| 125 |
+
learning_rate=0.1,
|
| 126 |
+
per_device_train_batch_size=1,
|
| 127 |
+
steps_per_generation=2,
|
| 128 |
+
max_completion_length=8,
|
| 129 |
+
max_steps=2,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
trainer = SSDTrainer(
|
| 133 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 134 |
+
args=training_args,
|
| 135 |
+
train_dataset=dataset,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
trainer.train()
|
| 139 |
+
|
| 140 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 141 |
+
|
| 142 |
+
def test_train_with_filter_empty_disabled(self):
|
| 143 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 144 |
+
|
| 145 |
+
training_args = SSDConfig(
|
| 146 |
+
output_dir=self.tmp_dir,
|
| 147 |
+
learning_rate=0.1,
|
| 148 |
+
per_device_train_batch_size=1,
|
| 149 |
+
max_completion_length=8,
|
| 150 |
+
max_steps=1,
|
| 151 |
+
filter_empty=False,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
trainer = SSDTrainer(
|
| 155 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 156 |
+
args=training_args,
|
| 157 |
+
train_dataset=dataset,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
trainer.train()
|
| 161 |
+
|
| 162 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 163 |
+
|
| 164 |
+
def test_train_logs_ssd_metrics(self):
|
| 165 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 166 |
+
|
| 167 |
+
training_args = SSDConfig(
|
| 168 |
+
output_dir=self.tmp_dir,
|
| 169 |
+
learning_rate=0.1,
|
| 170 |
+
per_device_train_batch_size=1,
|
| 171 |
+
max_completion_length=8,
|
| 172 |
+
max_steps=1,
|
| 173 |
+
logging_steps=1,
|
| 174 |
+
report_to="none",
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
trainer = SSDTrainer(
|
| 178 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 179 |
+
args=training_args,
|
| 180 |
+
train_dataset=dataset,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
trainer.train()
|
| 184 |
+
|
| 185 |
+
# The log() override merges _metrics into log_history and clears the buffer.
|
| 186 |
+
last_log = trainer.state.log_history[-2]
|
| 187 |
+
assert "ssd/cross_entropy_loss" in last_log
|
| 188 |
+
assert "ssd/active_sample_ratio" in last_log
|
| 189 |
+
assert "completions/mean_length" in last_log
|
| 190 |
+
|
| 191 |
+
@require_peft
|
| 192 |
+
def test_train_with_peft_model(self):
|
| 193 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 194 |
+
|
| 195 |
+
training_args = SSDConfig(
|
| 196 |
+
output_dir=self.tmp_dir,
|
| 197 |
+
learning_rate=0.1,
|
| 198 |
+
per_device_train_batch_size=1,
|
| 199 |
+
max_completion_length=8,
|
| 200 |
+
max_steps=1,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
trainer = SSDTrainer(
|
| 204 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 205 |
+
args=training_args,
|
| 206 |
+
train_dataset=dataset,
|
| 207 |
+
peft_config=LoraConfig(
|
| 208 |
+
task_type="CAUSAL_LM",
|
| 209 |
+
target_modules=["q_proj", "v_proj"],
|
| 210 |
+
),
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
trainer.train()
|
| 214 |
+
|
| 215 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 216 |
+
|
| 217 |
+
def test_train_with_disable_dropout_false(self):
|
| 218 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 219 |
+
|
| 220 |
+
training_args = SSDConfig(
|
| 221 |
+
output_dir=self.tmp_dir,
|
| 222 |
+
learning_rate=0.1,
|
| 223 |
+
per_device_train_batch_size=1,
|
| 224 |
+
max_completion_length=8,
|
| 225 |
+
max_steps=1,
|
| 226 |
+
disable_dropout=False,
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
trainer = SSDTrainer(
|
| 230 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 231 |
+
args=training_args,
|
| 232 |
+
train_dataset=dataset,
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
trainer.train()
|
| 236 |
+
|
| 237 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/experimental/test_tpo_trainer.py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from datasets import load_dataset
|
| 18 |
+
from transformers.utils import is_peft_available
|
| 19 |
+
|
| 20 |
+
from trl.experimental.tpo import TPOConfig, TPOTrainer
|
| 21 |
+
from trl.experimental.tpo.tpo_trainer import DataCollatorForTriplePreference
|
| 22 |
+
|
| 23 |
+
from ..testing_utils import TrlTestCase, require_peft
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if is_peft_available():
|
| 27 |
+
from peft import LoraConfig
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _add_reference_column(example):
|
| 31 |
+
"""Synthesize a `reference` (gold) completion for tests by reusing the chosen completion."""
|
| 32 |
+
example["reference"] = example["chosen"]
|
| 33 |
+
return example
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class TestDataCollatorForTriplePreference(TrlTestCase):
|
| 37 |
+
def test_padding_and_masks(self):
|
| 38 |
+
collator = DataCollatorForTriplePreference(pad_token_id=0)
|
| 39 |
+
examples = [
|
| 40 |
+
{"prompt_ids": [1, 2, 3], "chosen_ids": [4, 5], "rejected_ids": [6], "reference_ids": [7, 8]},
|
| 41 |
+
{"prompt_ids": [9, 10], "chosen_ids": [11], "rejected_ids": [12, 13], "reference_ids": [14]},
|
| 42 |
+
]
|
| 43 |
+
result = collator(examples)
|
| 44 |
+
|
| 45 |
+
expected_input_ids = torch.tensor(
|
| 46 |
+
[
|
| 47 |
+
[1, 2, 3, 4, 5], # prompt + chosen (example 1)
|
| 48 |
+
[9, 10, 11, 0, 0], # prompt + chosen (example 2, padded)
|
| 49 |
+
[1, 2, 3, 6, 0], # prompt + rejected (example 1, padded)
|
| 50 |
+
[9, 10, 12, 13, 0], # prompt + rejected (example 2, padded)
|
| 51 |
+
[1, 2, 3, 7, 8], # prompt + reference (example 1)
|
| 52 |
+
[9, 10, 14, 0, 0], # prompt + reference (example 2, padded)
|
| 53 |
+
]
|
| 54 |
+
)
|
| 55 |
+
expected_attention_mask = torch.tensor(
|
| 56 |
+
[
|
| 57 |
+
[1, 1, 1, 1, 1],
|
| 58 |
+
[1, 1, 1, 0, 0],
|
| 59 |
+
[1, 1, 1, 1, 0],
|
| 60 |
+
[1, 1, 1, 1, 0],
|
| 61 |
+
[1, 1, 1, 1, 1],
|
| 62 |
+
[1, 1, 1, 0, 0],
|
| 63 |
+
]
|
| 64 |
+
)
|
| 65 |
+
expected_completion_mask = torch.tensor(
|
| 66 |
+
[
|
| 67 |
+
[0, 0, 0, 1, 1],
|
| 68 |
+
[0, 0, 1, 0, 0],
|
| 69 |
+
[0, 0, 0, 1, 0],
|
| 70 |
+
[0, 0, 1, 1, 0],
|
| 71 |
+
[0, 0, 0, 1, 1],
|
| 72 |
+
[0, 0, 1, 0, 0],
|
| 73 |
+
]
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
assert set(result.keys()) == {"input_ids", "attention_mask", "completion_mask"}
|
| 77 |
+
torch.testing.assert_close(result["input_ids"], expected_input_ids)
|
| 78 |
+
torch.testing.assert_close(result["attention_mask"], expected_attention_mask)
|
| 79 |
+
torch.testing.assert_close(result["completion_mask"], expected_completion_mask)
|
| 80 |
+
|
| 81 |
+
def test_exclude_reference(self):
|
| 82 |
+
# When `include_reference=False`, the collator only emits the chosen/rejected halves so the per-step
|
| 83 |
+
# compute/memory cost matches DPO's `DataCollatorForPreference`. This is the layout used by
|
| 84 |
+
# `TPOTrainer` when `tpo_alpha=0.0`.
|
| 85 |
+
collator = DataCollatorForTriplePreference(pad_token_id=0, include_reference=False)
|
| 86 |
+
examples = [
|
| 87 |
+
{"prompt_ids": [1, 2, 3], "chosen_ids": [4, 5], "rejected_ids": [6], "reference_ids": [7, 8]},
|
| 88 |
+
{"prompt_ids": [9, 10], "chosen_ids": [11], "rejected_ids": [12, 13], "reference_ids": [14]},
|
| 89 |
+
]
|
| 90 |
+
result = collator(examples)
|
| 91 |
+
|
| 92 |
+
expected_input_ids = torch.tensor(
|
| 93 |
+
[
|
| 94 |
+
[1, 2, 3, 4, 5], # prompt + chosen (example 1)
|
| 95 |
+
[9, 10, 11, 0, 0], # prompt + chosen (example 2, padded)
|
| 96 |
+
[1, 2, 3, 6, 0], # prompt + rejected (example 1, padded)
|
| 97 |
+
[9, 10, 12, 13, 0], # prompt + rejected (example 2, padded)
|
| 98 |
+
]
|
| 99 |
+
)
|
| 100 |
+
assert result["input_ids"].shape == (4, 5) # 2 * B rows, no reference branch
|
| 101 |
+
torch.testing.assert_close(result["input_ids"], expected_input_ids)
|
| 102 |
+
assert set(result.keys()) == {"input_ids", "attention_mask", "completion_mask"}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class TestTPOTrainer(TrlTestCase):
|
| 106 |
+
def test_train(self):
|
| 107 |
+
# Get the dataset and synthesize a reference (gold) completion
|
| 108 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 109 |
+
dataset = dataset.map(_add_reference_column)
|
| 110 |
+
|
| 111 |
+
training_args = TPOConfig(
|
| 112 |
+
output_dir=self.tmp_dir,
|
| 113 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 114 |
+
report_to="none",
|
| 115 |
+
)
|
| 116 |
+
trainer = TPOTrainer(
|
| 117 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 118 |
+
args=training_args,
|
| 119 |
+
train_dataset=dataset,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 123 |
+
|
| 124 |
+
trainer.train()
|
| 125 |
+
|
| 126 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 127 |
+
|
| 128 |
+
# Check that the params have changed
|
| 129 |
+
for n, param in previous_trainable_params.items():
|
| 130 |
+
new_param = trainer.model.get_parameter(n)
|
| 131 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 132 |
+
|
| 133 |
+
def test_trust_remote_code(self):
|
| 134 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 135 |
+
dataset = dataset.map(_add_reference_column)
|
| 136 |
+
model_id = "trl-internal-testing/tiny-RemoteForCausalLM"
|
| 137 |
+
|
| 138 |
+
with pytest.raises(ValueError, match="custom code"):
|
| 139 |
+
TPOTrainer(
|
| 140 |
+
model=model_id,
|
| 141 |
+
args=TPOConfig(output_dir=self.tmp_dir, report_to="none"),
|
| 142 |
+
train_dataset=dataset,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
trainer = TPOTrainer(
|
| 146 |
+
model=model_id,
|
| 147 |
+
args=TPOConfig(output_dir=self.tmp_dir, report_to="none", trust_remote_code=True),
|
| 148 |
+
train_dataset=dataset,
|
| 149 |
+
)
|
| 150 |
+
assert type(trainer.model).__name__ == "RemoteForCausalLM"
|
| 151 |
+
|
| 152 |
+
@pytest.mark.parametrize("loss_type", ["sigmoid", "hinge", "ipo", "tpo-l"])
|
| 153 |
+
def test_train_loss_types(self, loss_type):
|
| 154 |
+
# Get the dataset and synthesize a reference (gold) completion
|
| 155 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference")
|
| 156 |
+
dataset = dataset.map(_add_reference_column)
|
| 157 |
+
|
| 158 |
+
training_args = TPOConfig(
|
| 159 |
+
output_dir=self.tmp_dir,
|
| 160 |
+
loss_type=loss_type,
|
| 161 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 162 |
+
report_to="none",
|
| 163 |
+
eval_strategy="steps",
|
| 164 |
+
eval_steps=3,
|
| 165 |
+
)
|
| 166 |
+
trainer = TPOTrainer(
|
| 167 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 168 |
+
args=training_args,
|
| 169 |
+
train_dataset=dataset["train"],
|
| 170 |
+
eval_dataset=dataset["test"],
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 174 |
+
|
| 175 |
+
trainer.train()
|
| 176 |
+
|
| 177 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 178 |
+
|
| 179 |
+
# Check that the params have changed
|
| 180 |
+
for n, param in previous_trainable_params.items():
|
| 181 |
+
new_param = trainer.model.get_parameter(n)
|
| 182 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 183 |
+
|
| 184 |
+
def test_train_conversational(self):
|
| 185 |
+
# Get the dataset and synthesize a reference (gold) completion
|
| 186 |
+
dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train")
|
| 187 |
+
dataset = dataset.map(_add_reference_column)
|
| 188 |
+
|
| 189 |
+
training_args = TPOConfig(
|
| 190 |
+
output_dir=self.tmp_dir,
|
| 191 |
+
learning_rate=0.1,
|
| 192 |
+
report_to="none",
|
| 193 |
+
)
|
| 194 |
+
trainer = TPOTrainer(
|
| 195 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 196 |
+
args=training_args,
|
| 197 |
+
train_dataset=dataset,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 201 |
+
|
| 202 |
+
trainer.train()
|
| 203 |
+
|
| 204 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 205 |
+
|
| 206 |
+
# Check that the params have changed
|
| 207 |
+
for n, param in previous_trainable_params.items():
|
| 208 |
+
new_param = trainer.model.get_parameter(n)
|
| 209 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 210 |
+
|
| 211 |
+
def test_train_without_nll(self):
|
| 212 |
+
# Setting tpo_alpha=0.0 disables the NLL term, skips the corresponding cross-entropy, and also drops the
|
| 213 |
+
# reference branch from the collated batch so the model doesn't pay the extra forward-pass cost.
|
| 214 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 215 |
+
dataset = dataset.map(_add_reference_column)
|
| 216 |
+
|
| 217 |
+
training_args = TPOConfig(
|
| 218 |
+
output_dir=self.tmp_dir,
|
| 219 |
+
tpo_alpha=0.0,
|
| 220 |
+
learning_rate=0.1,
|
| 221 |
+
report_to="none",
|
| 222 |
+
)
|
| 223 |
+
trainer = TPOTrainer(
|
| 224 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 225 |
+
args=training_args,
|
| 226 |
+
train_dataset=dataset,
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
# The default collator should drop the reference branch entirely when `tpo_alpha=0.0`.
|
| 230 |
+
assert isinstance(trainer.data_collator, DataCollatorForTriplePreference)
|
| 231 |
+
assert trainer.data_collator.include_reference is False
|
| 232 |
+
|
| 233 |
+
# Verify the collated batch is 2 * per_device_train_batch_size (chosen + rejected only), not 3 * B.
|
| 234 |
+
batch = trainer.data_collator(list(trainer.train_dataset.select(range(2))))
|
| 235 |
+
assert batch["input_ids"].shape[0] == 4 # 2 branches * 2 examples
|
| 236 |
+
|
| 237 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 238 |
+
|
| 239 |
+
trainer.train()
|
| 240 |
+
|
| 241 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 242 |
+
for n, param in previous_trainable_params.items():
|
| 243 |
+
new_param = trainer.model.get_parameter(n)
|
| 244 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 245 |
+
|
| 246 |
+
def test_train_implicit_prompt(self):
|
| 247 |
+
# Implicit-prompt variant: no `prompt` column, the prompt is embedded in `chosen`/`rejected` and (for TPO)
|
| 248 |
+
# also in `reference`. Regression test for the `extract_prompt` bug where the reference column was left
|
| 249 |
+
# untouched, silently doubling the prompt in the reference branch.
|
| 250 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 251 |
+
|
| 252 |
+
# Synthesize a reference column that shares the same implicit prompt as chosen/rejected
|
| 253 |
+
dataset = dataset.map(_add_reference_column)
|
| 254 |
+
|
| 255 |
+
training_args = TPOConfig(
|
| 256 |
+
output_dir=self.tmp_dir,
|
| 257 |
+
learning_rate=0.1,
|
| 258 |
+
report_to="none",
|
| 259 |
+
)
|
| 260 |
+
trainer = TPOTrainer(
|
| 261 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 262 |
+
args=training_args,
|
| 263 |
+
train_dataset=dataset,
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 267 |
+
|
| 268 |
+
trainer.train()
|
| 269 |
+
|
| 270 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 271 |
+
for n, param in previous_trainable_params.items():
|
| 272 |
+
new_param = trainer.model.get_parameter(n)
|
| 273 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 274 |
+
|
| 275 |
+
def test_implicit_prompt_mismatched_reference_raises(self):
|
| 276 |
+
# When the dataset has no `prompt` column and the `reference` completion does not share the implicit
|
| 277 |
+
# prompt prefix of `chosen`/`rejected`, the trainer must raise a clear error rather than silently
|
| 278 |
+
# corrupting the reference branch.
|
| 279 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 280 |
+
|
| 281 |
+
def _set_unrelated_reference(example):
|
| 282 |
+
example["reference"] = "unrelated completion without the shared prompt prefix."
|
| 283 |
+
return example
|
| 284 |
+
|
| 285 |
+
dataset = dataset.map(_set_unrelated_reference)
|
| 286 |
+
|
| 287 |
+
training_args = TPOConfig(output_dir=self.tmp_dir, report_to="none")
|
| 288 |
+
with pytest.raises(ValueError, match="implicit prompt"):
|
| 289 |
+
TPOTrainer(
|
| 290 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 291 |
+
args=training_args,
|
| 292 |
+
train_dataset=dataset,
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
def test_missing_reference_column_raises(self):
|
| 296 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 297 |
+
|
| 298 |
+
training_args = TPOConfig(output_dir=self.tmp_dir, report_to="none")
|
| 299 |
+
with pytest.raises(ValueError, match="reference"):
|
| 300 |
+
TPOTrainer(
|
| 301 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 302 |
+
args=training_args,
|
| 303 |
+
train_dataset=dataset,
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
@require_peft
|
| 307 |
+
def test_train_with_peft(self):
|
| 308 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 309 |
+
dataset = dataset.map(_add_reference_column)
|
| 310 |
+
|
| 311 |
+
training_args = TPOConfig(
|
| 312 |
+
output_dir=self.tmp_dir,
|
| 313 |
+
learning_rate=0.1,
|
| 314 |
+
report_to="none",
|
| 315 |
+
)
|
| 316 |
+
trainer = TPOTrainer(
|
| 317 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 318 |
+
args=training_args,
|
| 319 |
+
train_dataset=dataset,
|
| 320 |
+
peft_config=LoraConfig(),
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 324 |
+
|
| 325 |
+
trainer.train()
|
| 326 |
+
|
| 327 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 328 |
+
|
| 329 |
+
for n, param in previous_trainable_params.items():
|
| 330 |
+
if "lora" in n:
|
| 331 |
+
new_param = trainer.model.get_parameter(n)
|
| 332 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
tasks/tasksmith-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/tests/source/tests/invariant/references/dpo.json
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-b71e9e0a47b6/tests/source/tests/invariant/references/sft.json
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
| 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 |
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
|
| 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.14.0",
|
| 23 |
+
"torch": "2.10.0+cu128",
|
| 24 |
+
"transformers": "5.12.1",
|
| 25 |
+
"trl": "b58947c7e3f6a3ccddc56771f4bfa65c0d72bb41",
|
| 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.31194496154785
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"step": 2,
|
| 37 |
+
"loss": 1.5329023599624634,
|
| 38 |
+
"grad_norm": 18.577106475830078
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"step": 3,
|
| 42 |
+
"loss": 1.3667995929718018,
|
| 43 |
+
"grad_norm": 15.29236125946045
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"step": 4,
|
| 47 |
+
"loss": 2.432100296020508,
|
| 48 |
+
"grad_norm": 10.477559089660645
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"step": 5,
|
| 52 |
+
"loss": 1.4821819067001343,
|
| 53 |
+
"grad_norm": 12.838624954223633
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"step": 6,
|
| 57 |
+
"loss": 1.2035114765167236,
|
| 58 |
+
"grad_norm": 9.587946891784668
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"step": 7,
|
| 62 |
+
"loss": 1.4986138343811035,
|
| 63 |
+
"grad_norm": 9.106823921203613
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"step": 8,
|
| 67 |
+
"loss": 1.3387559652328491,
|
| 68 |
+
"grad_norm": 9.543354034423828
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"step": 9,
|
| 72 |
+
"loss": 1.7545020580291748,
|
| 73 |
+
"grad_norm": 8.437145233154297
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"step": 10,
|
| 77 |
+
"loss": 1.604130744934082,
|
| 78 |
+
"grad_norm": 45.08439636230469
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"step": 11,
|
| 82 |
+
"loss": 1.3063030242919922,
|
| 83 |
+
"grad_norm": 7.061337947845459
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"step": 12,
|
| 87 |
+
"loss": 1.4820657968521118,
|
| 88 |
+
"grad_norm": 7.337648391723633
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"step": 13,
|
| 92 |
+
"loss": 1.0585386753082275,
|
| 93 |
+
"grad_norm": 9.335886001586914
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"step": 14,
|
| 97 |
+
"loss": 1.2921745777130127,
|
| 98 |
+
"grad_norm": 6.186776161193848
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"step": 15,
|
| 102 |
+
"loss": 1.3104896545410156,
|
| 103 |
+
"grad_norm": 9.37338924407959
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"step": 16,
|
| 107 |
+
"loss": 1.5219330787658691,
|
| 108 |
+
"grad_norm": 9.168572425842285
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"step": 17,
|
| 112 |
+
"loss": 1.5855588912963867,
|
| 113 |
+
"grad_norm": 14.43403148651123
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"step": 18,
|
| 117 |
+
"loss": 0.731721818447113,
|
| 118 |
+
"grad_norm": 12.131467819213867
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"step": 19,
|
| 122 |
+
"loss": 1.6662267446517944,
|
| 123 |
+
"grad_norm": 6.035709381103516
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"step": 20,
|
| 127 |
+
"loss": 1.0886207818984985,
|
| 128 |
+
"grad_norm": 9.489429473876953
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"step": 21,
|
| 132 |
+
"loss": 1.1482083797454834,
|
| 133 |
+
"grad_norm": 8.50695514678955
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"step": 22,
|
| 137 |
+
"loss": 1.0655895471572876,
|
| 138 |
+
"grad_norm": 6.936838150024414
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"step": 23,
|
| 142 |
+
"loss": 1.3867775201797485,
|
| 143 |
+
"grad_norm": 9.368760108947754
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"step": 24,
|
| 147 |
+
"loss": 1.888922095298767,
|
| 148 |
+
"grad_norm": 19.709505081176758
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"step": 25,
|
| 152 |
+
"loss": 1.9733335971832275,
|
| 153 |
+
"grad_norm": 7.740928649902344
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"step": 26,
|
| 157 |
+
"loss": 2.064484119415283,
|
| 158 |
+
"grad_norm": 6.624837398529053
|
| 159 |
+
},
|
| 160 |
+
{
|
| 161 |
+
"step": 27,
|
| 162 |
+
"loss": 0.67816162109375,
|
| 163 |
+
"grad_norm": 5.390377521514893
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"step": 28,
|
| 167 |
+
"loss": 1.41758131980896,
|
| 168 |
+
"grad_norm": 11.643660545349121
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"step": 29,
|
| 172 |
+
"loss": 2.0091347694396973,
|
| 173 |
+
"grad_norm": 8.343645095825195
|
| 174 |
+
},
|
| 175 |
+
{
|
| 176 |
+
"step": 30,
|
| 177 |
+
"loss": 1.5923049449920654,
|
| 178 |
+
"grad_norm": 7.833315849304199
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"step": 31,
|
| 182 |
+
"loss": 1.4399499893188477,
|
| 183 |
+
"grad_norm": 6.47890567779541
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"step": 32,
|
| 187 |
+
"loss": 1.1694945096969604,
|
| 188 |
+
"grad_norm": 7.235599517822266
|
| 189 |
+
},
|
| 190 |
+
{
|
| 191 |
+
"step": 33,
|
| 192 |
+
"loss": 1.8836697340011597,
|
| 193 |
+
"grad_norm": 16.655620574951172
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
"step": 34,
|
| 197 |
+
"loss": 1.7419353723526,
|
| 198 |
+
"grad_norm": 10.752205848693848
|
| 199 |
+
},
|
| 200 |
+
{
|
| 201 |
+
"step": 35,
|
| 202 |
+
"loss": 1.484404444694519,
|
| 203 |
+
"grad_norm": 7.342534065246582
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
"step": 36,
|
| 207 |
+
"loss": 1.2079955339431763,
|
| 208 |
+
"grad_norm": 9.161640167236328
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"step": 37,
|
| 212 |
+
"loss": 1.4994128942489624,
|
| 213 |
+
"grad_norm": 6.655267238616943
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"step": 38,
|
| 217 |
+
"loss": 1.1862525939941406,
|
| 218 |
+
"grad_norm": 6.461650848388672
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"step": 39,
|
| 222 |
+
"loss": 1.463683009147644,
|
| 223 |
+
"grad_norm": 8.37391185760498
|
| 224 |
+
},
|
| 225 |
+
{
|
| 226 |
+
"step": 40,
|
| 227 |
+
"loss": 1.8926860094070435,
|
| 228 |
+
"grad_norm": 6.237414836883545
|
| 229 |
+
},
|
| 230 |
+
{
|
| 231 |
+
"step": 41,
|
| 232 |
+
"loss": 1.6285597085952759,
|
| 233 |
+
"grad_norm": 8.78761100769043
|
| 234 |
+
},
|
| 235 |
+
{
|
| 236 |
+
"step": 42,
|
| 237 |
+
"loss": 1.6035821437835693,
|
| 238 |
+
"grad_norm": 8.460630416870117
|
| 239 |
+
},
|
| 240 |
+
{
|
| 241 |
+
"step": 43,
|
| 242 |
+
"loss": 1.4722487926483154,
|
| 243 |
+
"grad_norm": 8.564600944519043
|
| 244 |
+
},
|
| 245 |
+
{
|
| 246 |
+
"step": 44,
|
| 247 |
+
"loss": 2.4026732444763184,
|
| 248 |
+
"grad_norm": 8.871479988098145
|
| 249 |
+
},
|
| 250 |
+
{
|
| 251 |
+
"step": 45,
|
| 252 |
+
"loss": 2.15500545501709,
|
| 253 |
+
"grad_norm": 8.206993103027344
|
| 254 |
+
},
|
| 255 |
+
{
|
| 256 |
+
"step": 46,
|
| 257 |
+
"loss": 1.3589471578598022,
|
| 258 |
+
"grad_norm": 8.473345756530762
|
| 259 |
+
},
|
| 260 |
+
{
|
| 261 |
+
"step": 47,
|
| 262 |
+
"loss": 1.2295477390289307,
|
| 263 |
+
"grad_norm": 24.53108787536621
|
| 264 |
+
},
|
| 265 |
+
{
|
| 266 |
+
"step": 48,
|
| 267 |
+
"loss": 1.878961443901062,
|
| 268 |
+
"grad_norm": 6.903346538543701
|
| 269 |
+
},
|
| 270 |
+
{
|
| 271 |
+
"step": 49,
|
| 272 |
+
"loss": 0.6936798691749573,
|
| 273 |
+
"grad_norm": 7.316105365753174
|
| 274 |
+
},
|
| 275 |
+
{
|
| 276 |
+
"step": 50,
|
| 277 |
+
"loss": 0.9757086038589478,
|
| 278 |
+
"grad_norm": 12.083908081054688
|
| 279 |
+
}
|
| 280 |
+
]
|
| 281 |
+
}
|
tasks/tasksmith-b71e9e0a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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_type not pinned; this class exercises the current SFTConfig default ("chunked_nll").
|
| 208 |
+
# Loss is much tighter than grad_norm under FA2+bf16 (grad_norm absorbs bf16 + FA varlen kernel noise).
|
| 209 |
+
# The grad_norm tol (5.0) is intentionally ~50× looser than the non-FA2 sft class (0.1): it is sized to the
|
| 210 |
+
# FA2 varlen kernel noise observed in practice, not a regression budget. Do not tighten it without re-running
|
| 211 |
+
# the class and confirming the new gap; see https://github.com/huggingface/trl/pull/5842#issuecomment-4539190615
|
| 212 |
+
"tol": {"loss": 1.5e-2, "grad_norm": 5.0},
|
| 213 |
+
"residual_tol": {"loss": 1e-3, "grad_norm": 2.5e-1},
|
| 214 |
+
"members": [
|
| 215 |
+
_build(
|
| 216 |
+
"sft_fa2",
|
| 217 |
+
"sft",
|
| 218 |
+
SFT_DATASET,
|
| 219 |
+
attn="kernels-community/flash-attn2", # to avoid cross-contamination between samples when padding_free=True
|
| 220 |
+
bf16=True, # required for FA2 kernels, which are bfloat16-only
|
| 221 |
+
max_length=None, # Required when padding_free=True
|
| 222 |
+
per_device_train_batch_size=2,
|
| 223 |
+
),
|
| 224 |
+
_build(
|
| 225 |
+
"sft_fa2_padfree",
|
| 226 |
+
"sft",
|
| 227 |
+
SFT_DATASET,
|
| 228 |
+
attn="kernels-community/flash-attn2", # to avoid cross-contamination between samples when padding_free=True
|
| 229 |
+
bf16=True, # required for FA2 kernels, which are bfloat16-only
|
| 230 |
+
max_length=None, # Required when padding_free=True
|
| 231 |
+
per_device_train_batch_size=2,
|
| 232 |
+
padding_free=True,
|
| 233 |
+
),
|
| 234 |
+
],
|
| 235 |
+
},
|
| 236 |
+
"dpo": {
|
| 237 |
+
"tol": {"loss": 1e-4, "grad_norm": 1e-2},
|
| 238 |
+
"residual_tol": {"loss": 1e-5, "grad_norm": 1e-3},
|
| 239 |
+
"members": [
|
| 240 |
+
_build("dpo_default", "dpo", DPO_DATASET),
|
| 241 |
+
_build("dpo_pdb1_gas8", "dpo", DPO_DATASET, per_device_train_batch_size=1, gradient_accumulation_steps=8),
|
| 242 |
+
_build("dpo_no_grad_ckpt", "dpo", DPO_DATASET, gradient_checkpointing=False),
|
| 243 |
+
_build("dpo_ddp2", "dpo", DPO_DATASET, per_device_train_batch_size=4, num_processes=2),
|
| 244 |
+
],
|
| 245 |
+
},
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
_ALL = [(klass, c) for klass, ec in EQUIVALENCE_CLASSES.items() for c in ec["members"]]
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@pytest.mark.invariant
|
| 253 |
+
@pytest.mark.parametrize("klass,config", _ALL, ids=[c.name for _, c in _ALL])
|
| 254 |
+
def test_invariant(klass, config):
|
| 255 |
+
ref_path = REFERENCES_DIR / f"{klass}.json"
|
| 256 |
+
if not ref_path.exists():
|
| 257 |
+
pytest.fail(f"no reference at {ref_path}; record it with `python {Path(__file__).name}`")
|
| 258 |
+
|
| 259 |
+
if config.num_processes > 1 and torch.cuda.device_count() < config.num_processes:
|
| 260 |
+
pytest.skip(f"requires {config.num_processes} GPUs, got {torch.cuda.device_count()}")
|
| 261 |
+
|
| 262 |
+
trajectory = run(config)
|
| 263 |
+
reference = load(ref_path)
|
| 264 |
+
ec = EQUIVALENCE_CLASSES[klass]
|
| 265 |
+
errors = compare_scalars(trajectory, reference, tol=ec["tol"], residual_tol=ec["residual_tol"])
|
| 266 |
+
assert not errors, f"'{config.name}' diverges from class '{klass}' reference:\n " + "\n ".join(errors)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
if __name__ == "__main__":
|
| 270 |
+
import argparse
|
| 271 |
+
|
| 272 |
+
parser = argparse.ArgumentParser(description="Record canonical reference trajectories for the invariant tests.")
|
| 273 |
+
parser.add_argument(
|
| 274 |
+
"klass",
|
| 275 |
+
nargs="*",
|
| 276 |
+
choices=list(EQUIVALENCE_CLASSES),
|
| 277 |
+
help="Equivalence class(es) to record. Default: all.",
|
| 278 |
+
)
|
| 279 |
+
parser.add_argument(
|
| 280 |
+
"--allow-dirty",
|
| 281 |
+
action="store_true",
|
| 282 |
+
help="Allow recording from a dirty working tree (snapshot will pin an irreproducible state).",
|
| 283 |
+
)
|
| 284 |
+
cli_args = parser.parse_args()
|
| 285 |
+
|
| 286 |
+
if _trl_commit().endswith("-dirty") and not cli_args.allow_dirty:
|
| 287 |
+
sys.exit(
|
| 288 |
+
"Refusing to record from a dirty working tree: the snapshot would pin a state that can't be "
|
| 289 |
+
"reproduced from a commit SHA. Commit your changes first, or pass --allow-dirty to override."
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
classes = cli_args.klass or list(EQUIVALENCE_CLASSES)
|
| 293 |
+
for klass in classes:
|
| 294 |
+
canonical = EQUIVALENCE_CLASSES[klass]["members"][0]
|
| 295 |
+
print(f"recording '{klass}' from canonical config '{canonical.name}'") # noqa: T201
|
| 296 |
+
trajectory = run(canonical)
|
| 297 |
+
ref_path = REFERENCES_DIR / f"{klass}.json"
|
| 298 |
+
save(trajectory, ref_path)
|
| 299 |
+
print(f" → {ref_path}") # noqa: T201
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/tasksmith_behavior.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import pickle
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# ---------------------------------------------------------------------------
|
| 7 |
+
# Adjacent behavior: accuracy_reward already exists on the starting code.
|
| 8 |
+
# These tests pass before and after the PR.
|
| 9 |
+
# ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
def test_accuracy_reward_correct_answer():
|
| 12 |
+
from trl.rewards import accuracy_reward
|
| 13 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}]]
|
| 14 |
+
solution = [r"\frac{1}{3}"]
|
| 15 |
+
rewards = accuracy_reward(completions, solution)
|
| 16 |
+
assert rewards == [1.0]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_accuracy_reward_wrong_answer():
|
| 20 |
+
from trl.rewards import accuracy_reward
|
| 21 |
+
completions = [[{"content": r"\boxed{\frac{1}{2}}"}]]
|
| 22 |
+
solution = [r"\frac{1}{3}"]
|
| 23 |
+
rewards = accuracy_reward(completions, solution)
|
| 24 |
+
assert rewards == [0.0]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
# New behavior: get_cosine_scaled_reward (fails on starting code).
|
| 29 |
+
# Each test imports inside the function so collection never fails.
|
| 30 |
+
# ---------------------------------------------------------------------------
|
| 31 |
+
|
| 32 |
+
def test_importable_from_trl_rewards():
|
| 33 |
+
from trl.rewards import get_cosine_scaled_reward
|
| 34 |
+
fn = get_cosine_scaled_reward(max_len=100)
|
| 35 |
+
assert callable(fn)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_midpoint_values_default_bounds():
|
| 39 |
+
"""At progress=0.5 (cosine=0): correct->0.75, wrong->-0.75."""
|
| 40 |
+
from trl.rewards import get_cosine_scaled_reward
|
| 41 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 42 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}], [{"content": r"\boxed{\frac{1}{2}}"}]]
|
| 43 |
+
solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
|
| 44 |
+
completion_ids = [[1] * 50, [1] * 50]
|
| 45 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 46 |
+
assert rewards == [pytest.approx(0.75), pytest.approx(-0.75)]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_correct_shorter_rewarded_more():
|
| 50 |
+
"""Shorter correct completions receive a higher reward."""
|
| 51 |
+
from trl.rewards import get_cosine_scaled_reward
|
| 52 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 53 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}], [{"content": r"\boxed{\frac{1}{3}}"}]]
|
| 54 |
+
solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
|
| 55 |
+
completion_ids = [[1] * 25, [1] * 75]
|
| 56 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 57 |
+
assert rewards[0] > rewards[1]
|
| 58 |
+
assert rewards[0] == pytest.approx(0.92678, abs=1e-4)
|
| 59 |
+
assert rewards[1] == pytest.approx(0.57322, abs=1e-4)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_wrong_longer_penalized_less():
|
| 63 |
+
"""Longer wrong completions are penalized less (closer to zero)."""
|
| 64 |
+
from trl.rewards import get_cosine_scaled_reward
|
| 65 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 66 |
+
completions = [[{"content": r"\boxed{\frac{1}{2}}"}], [{"content": r"\boxed{\frac{1}{2}}"}]]
|
| 67 |
+
solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
|
| 68 |
+
completion_ids = [[1] * 25, [1] * 75]
|
| 69 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 70 |
+
assert rewards[1] > rewards[0]
|
| 71 |
+
assert rewards[0] == pytest.approx(-0.92678, abs=1e-4)
|
| 72 |
+
assert rewards[1] == pytest.approx(-0.57322, abs=1e-4)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_correct_boundary_values():
|
| 76 |
+
"""Correct: empty (0 tokens) -> max_value_correct=1.0; full (max_len) -> min_value_correct=0.5."""
|
| 77 |
+
from trl.rewards import get_cosine_scaled_reward
|
| 78 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 79 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}], [{"content": r"\boxed{\frac{1}{3}}"}]]
|
| 80 |
+
solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
|
| 81 |
+
completion_ids = [[], [1] * 100]
|
| 82 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 83 |
+
assert rewards == [pytest.approx(1.0), pytest.approx(0.5)]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_wrong_boundary_values():
|
| 87 |
+
"""Wrong: empty (0 tokens) -> min_value_wrong=-1.0; full (max_len) -> max_value_wrong=-0.5."""
|
| 88 |
+
from trl.rewards import get_cosine_scaled_reward
|
| 89 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 90 |
+
completions = [[{"content": r"\boxed{\frac{1}{2}}"}], [{"content": r"\boxed{\frac{1}{2}}"}]]
|
| 91 |
+
solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
|
| 92 |
+
completion_ids = [[], [1] * 100]
|
| 93 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 94 |
+
assert rewards == [pytest.approx(-1.0), pytest.approx(-0.5)]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_length_exceeding_max_len_is_clamped():
|
| 98 |
+
"""Completions longer than max_len stay at the long-length bound value."""
|
| 99 |
+
from trl.rewards import get_cosine_scaled_reward
|
| 100 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 101 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}], [{"content": r"\boxed{\frac{1}{2}}"}]]
|
| 102 |
+
solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
|
| 103 |
+
completion_ids = [[1] * 200, [1] * 200] # 2x max_len
|
| 104 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 105 |
+
# same as at exactly max_len
|
| 106 |
+
assert rewards == [pytest.approx(0.5), pytest.approx(-0.5)]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_unparsable_gold_yields_none():
|
| 110 |
+
"""An unparseable gold solution results in None reward for that example."""
|
| 111 |
+
from trl.rewards import get_cosine_scaled_reward
|
| 112 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 113 |
+
completions = [[{"content": r"\boxed{42}"}]]
|
| 114 |
+
solution = ["forty two"] # plain text, not a math expression
|
| 115 |
+
completion_ids = [[1] * 50]
|
| 116 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 117 |
+
assert rewards == [None]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def test_custom_value_bounds():
|
| 121 |
+
"""Custom bounds are applied correctly in the formula."""
|
| 122 |
+
from trl.rewards import get_cosine_scaled_reward
|
| 123 |
+
# At midpoint: 0.0 + 0.5*(2.0-0.0)*(1+0) = 1.0
|
| 124 |
+
reward_fn = get_cosine_scaled_reward(max_len=100, min_value_correct=0.0, max_value_correct=2.0)
|
| 125 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}]]
|
| 126 |
+
solution = [r"\frac{1}{3}"]
|
| 127 |
+
completion_ids = [[1] * 50]
|
| 128 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 129 |
+
assert rewards == [pytest.approx(1.0)]
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def test_nondefault_configuration_and_pickle():
|
| 133 |
+
"""Budgets and all bounds govern fresh evaluations before and after pickling."""
|
| 134 |
+
from trl.rewards import get_cosine_scaled_reward
|
| 135 |
+
|
| 136 |
+
# Rows correspond to progress 0, 1/3, 1/2, 1, and 2 (clamped).
|
| 137 |
+
# Each row contains the independently expected correct and wrong rewards.
|
| 138 |
+
configurations = [
|
| 139 |
+
({}, [(1.0, -1.0), (0.875, -0.875), (0.75, -0.75),
|
| 140 |
+
(0.5, -0.5), (0.5, -0.5)]),
|
| 141 |
+
({"min_value_wrong": -2.0, "max_value_wrong": -0.25,
|
| 142 |
+
"min_value_correct": 0.25, "max_value_correct": 1.25},
|
| 143 |
+
[(1.25, -2.0), (1.0, -1.5625), (0.75, -1.125),
|
| 144 |
+
(0.25, -0.25), (0.25, -0.25)]),
|
| 145 |
+
]
|
| 146 |
+
for budget in (60, 240):
|
| 147 |
+
for bounds, rows in configurations:
|
| 148 |
+
reward_fn = get_cosine_scaled_reward(max_len=budget, **bounds)
|
| 149 |
+
restored = pickle.loads(pickle.dumps(reward_fn))
|
| 150 |
+
for fn in (reward_fn, restored):
|
| 151 |
+
assert fn.__name__ == "cosine_scaled_reward"
|
| 152 |
+
completions = []
|
| 153 |
+
solutions = []
|
| 154 |
+
token_ids = []
|
| 155 |
+
for length in (0, budget // 3, budget // 2, budget, 2 * budget):
|
| 156 |
+
for answer in (r"\boxed{\frac{1}{3}}", r"\boxed{\frac{1}{2}}"):
|
| 157 |
+
completions.append([{"content": answer}])
|
| 158 |
+
solutions.append(r"\frac{1}{3}")
|
| 159 |
+
token_ids.append([7] * length)
|
| 160 |
+
rewards = fn(completions, solutions, token_ids)
|
| 161 |
+
assert isinstance(rewards, list)
|
| 162 |
+
assert rewards == pytest.approx([value for row in rows for value in row])
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def test_mathematical_correctness_not_substring_matching():
|
| 166 |
+
"""Equivalent expressions count; mentioning the gold is not a correct final answer."""
|
| 167 |
+
from trl.rewards import accuracy_reward, get_cosine_scaled_reward
|
| 168 |
+
|
| 169 |
+
cases = [
|
| 170 |
+
(r"\boxed{1+1}", "2", 1.0, 0.75),
|
| 171 |
+
(r"I considered 2, but my final answer is \boxed{3}.", "2", 0.0, -0.75),
|
| 172 |
+
(r"\boxed{\frac{6}{8}}", r"\frac{3}{4}", 1.0, 0.75),
|
| 173 |
+
(r"I considered 5, but my final answer is \boxed{6}.", "5", 0.0, -0.75),
|
| 174 |
+
]
|
| 175 |
+
reward_fn = get_cosine_scaled_reward(max_len=80)
|
| 176 |
+
restored = pickle.loads(pickle.dumps(reward_fn))
|
| 177 |
+
for fn in (reward_fn, restored):
|
| 178 |
+
completions = [[{"content": content}] for content, _, _, _ in cases]
|
| 179 |
+
solutions = [gold for _, gold, _, _ in cases]
|
| 180 |
+
# Validate fixture semantics against the repository's real math-verification API.
|
| 181 |
+
# Expected cosine rewards are independent of this submitted accuracy function.
|
| 182 |
+
assert accuracy_reward(completions, solutions) == [case[2] for case in cases]
|
| 183 |
+
rewards = fn(
|
| 184 |
+
completions=completions,
|
| 185 |
+
solution=solutions,
|
| 186 |
+
completion_ids=[[7] * 40 for _ in cases],
|
| 187 |
+
unused_trainer_metadata=None,
|
| 188 |
+
)
|
| 189 |
+
assert isinstance(rewards, list)
|
| 190 |
+
assert rewards == pytest.approx([case[3] for case in cases])
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_reward_is_picklable():
|
| 194 |
+
"""The reward function survives pickle round-trip with correct behavior and __name__."""
|
| 195 |
+
from trl.rewards import get_cosine_scaled_reward
|
| 196 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 197 |
+
unpickled = pickle.loads(pickle.dumps(reward_fn))
|
| 198 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}]]
|
| 199 |
+
solution = [r"\frac{1}{3}"]
|
| 200 |
+
completion_ids = [[1] * 50]
|
| 201 |
+
assert unpickled(completions, solution, completion_ids) == [pytest.approx(0.75)]
|
| 202 |
+
assert unpickled.__name__ == "cosine_scaled_reward"
|
tasks/tasksmith-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/tests/source/tests/test_chat_template_utils.py
ADDED
|
@@ -0,0 +1,1258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(
|
| 583 |
+
"trl-internal-testing/tiny-Idefics3ForConditionalGeneration", id="idefics3", marks=require_vision
|
| 584 |
+
),
|
| 585 |
+
pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3", id="llama3"),
|
| 586 |
+
pytest.param("trl-internal-testing/tiny-LlavaForConditionalGeneration", id="llava", marks=require_vision),
|
| 587 |
+
pytest.param(
|
| 588 |
+
"trl-internal-testing/tiny-LlavaNextForConditionalGeneration", id="llava_next", marks=require_vision
|
| 589 |
+
),
|
| 590 |
+
pytest.param(
|
| 591 |
+
"trl-internal-testing/tiny-NemotronHForCausalLM-nano",
|
| 592 |
+
id="nemotron_3_nano",
|
| 593 |
+
marks=pytest.mark.skipif(
|
| 594 |
+
Version(transformers.__version__) < Version("5.3.0"),
|
| 595 |
+
reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
|
| 596 |
+
),
|
| 597 |
+
),
|
| 598 |
+
pytest.param(
|
| 599 |
+
"trl-internal-testing/tiny-NemotronHForCausalLM-super",
|
| 600 |
+
id="nemotron_3_super",
|
| 601 |
+
marks=pytest.mark.skipif(
|
| 602 |
+
Version(transformers.__version__) < Version("5.3.0"),
|
| 603 |
+
reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
|
| 604 |
+
),
|
| 605 |
+
),
|
| 606 |
+
pytest.param(
|
| 607 |
+
"trl-internal-testing/tiny-NemotronHForCausalLM-ultra",
|
| 608 |
+
id="nemotron_3_ultra",
|
| 609 |
+
marks=pytest.mark.skipif(
|
| 610 |
+
Version(transformers.__version__) < Version("5.3.0"),
|
| 611 |
+
reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
|
| 612 |
+
),
|
| 613 |
+
),
|
| 614 |
+
pytest.param("trl-internal-testing/tiny-Phi3ForCausalLM-3", id="phi3"),
|
| 615 |
+
pytest.param("trl-internal-testing/tiny-Phi3ForCausalLM-3.5", id="phi3.5"),
|
| 616 |
+
pytest.param("trl-internal-testing/tiny-Qwen2VLForConditionalGeneration", id="qwen2_vl", marks=require_vision),
|
| 617 |
+
pytest.param("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", id="qwen2.5"),
|
| 618 |
+
pytest.param(
|
| 619 |
+
"trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration", id="qwen2.5_vl", marks=require_vision
|
| 620 |
+
),
|
| 621 |
+
pytest.param("trl-internal-testing/tiny-Qwen3MoeForCausalLM", id="qwen3"),
|
| 622 |
+
pytest.param("trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", id="qwen3_instruct_2507"),
|
| 623 |
+
pytest.param(
|
| 624 |
+
"trl-internal-testing/tiny-Qwen3VLForConditionalGeneration",
|
| 625 |
+
id="qwen3_vl",
|
| 626 |
+
marks=[
|
| 627 |
+
require_vision,
|
| 628 |
+
pytest.mark.skipif(
|
| 629 |
+
Version(transformers.__version__) < Version("4.57.0"),
|
| 630 |
+
reason="Qwen3-VL was introduced in transformers-4.57.0",
|
| 631 |
+
),
|
| 632 |
+
],
|
| 633 |
+
),
|
| 634 |
+
pytest.param(
|
| 635 |
+
"trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink",
|
| 636 |
+
id="qwen35-nothink",
|
| 637 |
+
marks=[
|
| 638 |
+
require_vision,
|
| 639 |
+
pytest.mark.skipif(
|
| 640 |
+
Version(transformers.__version__) < Version("5.0.0"),
|
| 641 |
+
reason="Qwen3.5 tokenizer requires transformers>=5.0.0",
|
| 642 |
+
),
|
| 643 |
+
],
|
| 644 |
+
),
|
| 645 |
+
pytest.param(
|
| 646 |
+
"trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-Think",
|
| 647 |
+
id="qwen35-think",
|
| 648 |
+
marks=[
|
| 649 |
+
require_vision,
|
| 650 |
+
pytest.mark.skipif(
|
| 651 |
+
Version(transformers.__version__) < Version("5.0.0"),
|
| 652 |
+
reason="Qwen3.5 tokenizer requires transformers>=5.0.0",
|
| 653 |
+
),
|
| 654 |
+
],
|
| 655 |
+
),
|
| 656 |
+
pytest.param(
|
| 657 |
+
"trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6",
|
| 658 |
+
id="qwen36",
|
| 659 |
+
marks=[
|
| 660 |
+
require_vision,
|
| 661 |
+
pytest.mark.skipif(
|
| 662 |
+
Version(transformers.__version__) < Version("5.0.0"),
|
| 663 |
+
reason="Qwen3.5 tokenizer requires transformers>=5.0.0",
|
| 664 |
+
),
|
| 665 |
+
],
|
| 666 |
+
),
|
| 667 |
+
],
|
| 668 |
+
)
|
| 669 |
+
class TestGetTrainingChatTemplate:
|
| 670 |
+
def _load(self, model_name):
|
| 671 |
+
if "ForCausalLM" in model_name:
|
| 672 |
+
self.is_vlm = False
|
| 673 |
+
processing_class = AutoTokenizer.from_pretrained(model_name)
|
| 674 |
+
elif "ForConditionalGeneration" in model_name:
|
| 675 |
+
self.is_vlm = True
|
| 676 |
+
processing_class = AutoProcessor.from_pretrained(model_name)
|
| 677 |
+
|
| 678 |
+
return processing_class
|
| 679 |
+
|
| 680 |
+
def test_new_chat_template_is_prefix_preserving(self, tokenizer_name):
|
| 681 |
+
tokenizer = self._load(tokenizer_name)
|
| 682 |
+
new_chat_template = get_training_chat_template(tokenizer)
|
| 683 |
+
if new_chat_template is not None:
|
| 684 |
+
tokenizer.chat_template = new_chat_template
|
| 685 |
+
# Prefix-preservation is only meaningful for templates that actually support tool messages — the check
|
| 686 |
+
# itself renders one. Skip the assertion for tool-less templates (e.g. Gemma).
|
| 687 |
+
if not supports_tool_calling(tokenizer):
|
| 688 |
+
pytest.skip("Template does not support tool calling; prefix-preservation check is not applicable.")
|
| 689 |
+
assert is_chat_template_prefix_preserving(tokenizer) is True
|
| 690 |
+
|
| 691 |
+
def test_new_chat_template_trains_stop_token(self, tokenizer_name, request):
|
| 692 |
+
if tokenizer_name in (
|
| 693 |
+
"trl-internal-testing/tiny-LlavaForConditionalGeneration",
|
| 694 |
+
"trl-internal-testing/tiny-LlavaNextForConditionalGeneration",
|
| 695 |
+
):
|
| 696 |
+
reason = f"{tokenizer_name}: the processor returns an all-zero assistant tokens mask"
|
| 697 |
+
request.node.add_marker(pytest.mark.xfail(strict=False, reason=reason))
|
| 698 |
+
tokenizer = self._load(tokenizer_name)
|
| 699 |
+
new_chat_template = get_training_chat_template(tokenizer)
|
| 700 |
+
assert is_chat_template_stop_token_trained(tokenizer, chat_template=new_chat_template) is True
|
| 701 |
+
|
| 702 |
+
def test_behavior_unchanged_single_user_no_generation_prompt(self, tokenizer_name):
|
| 703 |
+
tokenizer = self._load(tokenizer_name)
|
| 704 |
+
messages = [{"role": "user", "content": "What color is the sky?"}]
|
| 705 |
+
if self.is_vlm:
|
| 706 |
+
messages = prepare_multimodal_messages(messages)
|
| 707 |
+
|
| 708 |
+
before = tokenizer.apply_chat_template(messages, tokenize=False)
|
| 709 |
+
new_chat_template = get_training_chat_template(tokenizer)
|
| 710 |
+
after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template)
|
| 711 |
+
assert before == after
|
| 712 |
+
|
| 713 |
+
def test_behavior_unchanged_single_user_with_generation_prompt(self, tokenizer_name):
|
| 714 |
+
tokenizer = self._load(tokenizer_name)
|
| 715 |
+
messages = [{"role": "user", "content": "What color is the sky?"}]
|
| 716 |
+
if self.is_vlm:
|
| 717 |
+
messages = prepare_multimodal_messages(messages)
|
| 718 |
+
|
| 719 |
+
before = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
|
| 720 |
+
new_chat_template = get_training_chat_template(tokenizer)
|
| 721 |
+
after = tokenizer.apply_chat_template(
|
| 722 |
+
messages,
|
| 723 |
+
tokenize=False,
|
| 724 |
+
add_generation_prompt=True,
|
| 725 |
+
chat_template=new_chat_template,
|
| 726 |
+
)
|
| 727 |
+
assert before == after
|
| 728 |
+
|
| 729 |
+
def test_behavior_unchanged_single_user_and_final_assistant_plain_content(self, tokenizer_name):
|
| 730 |
+
tokenizer = self._load(tokenizer_name)
|
| 731 |
+
messages = [
|
| 732 |
+
{"role": "user", "content": "What color is the sky?"},
|
| 733 |
+
{"role": "assistant", "content": "It is blue."},
|
| 734 |
+
]
|
| 735 |
+
if self.is_vlm:
|
| 736 |
+
messages = prepare_multimodal_messages(messages)
|
| 737 |
+
|
| 738 |
+
before = tokenizer.apply_chat_template(messages, tokenize=False)
|
| 739 |
+
new_chat_template = get_training_chat_template(tokenizer)
|
| 740 |
+
after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template)
|
| 741 |
+
if tokenizer_name == "trl-internal-testing/tiny-Glm4MoeForCausalLM":
|
| 742 |
+
# GLM's native template doesn't terminate an assistant turn with an end-of-turn token; the turn is ended
|
| 743 |
+
# by the following message's role marker. The training template appends that terminator to the final
|
| 744 |
+
# assistant turn so the stop token is trained — here the `<|user|>` that would open the next turn.
|
| 745 |
+
assert after == before + "<|user|>"
|
| 746 |
+
else:
|
| 747 |
+
assert before == after
|
| 748 |
+
|
| 749 |
+
def test_behavior_unchanged_final_assistant_with_reasoning_content(self, tokenizer_name):
|
| 750 |
+
tokenizer = self._load(tokenizer_name)
|
| 751 |
+
messages = [
|
| 752 |
+
{"role": "user", "content": "What color is the sky?"},
|
| 753 |
+
{
|
| 754 |
+
"role": "assistant",
|
| 755 |
+
"content": "It is blue.",
|
| 756 |
+
"reasoning_content": "The sky appears blue due to Rayleigh scattering.",
|
| 757 |
+
},
|
| 758 |
+
]
|
| 759 |
+
if self.is_vlm:
|
| 760 |
+
messages = prepare_multimodal_messages(messages)
|
| 761 |
+
|
| 762 |
+
before = tokenizer.apply_chat_template(messages, tokenize=False)
|
| 763 |
+
new_chat_template = get_training_chat_template(tokenizer)
|
| 764 |
+
after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template)
|
| 765 |
+
if tokenizer_name == "trl-internal-testing/tiny-Glm4MoeForCausalLM":
|
| 766 |
+
# GLM's native template doesn't terminate an assistant turn with an end-of-turn token; the turn is ended
|
| 767 |
+
# by the following message's role marker. The training template appends that terminator to the final
|
| 768 |
+
# assistant turn so the stop token is trained — here the `<|user|>` that would open the next turn.
|
| 769 |
+
assert after == before + "<|user|>"
|
| 770 |
+
else:
|
| 771 |
+
assert before == after
|
| 772 |
+
|
| 773 |
+
def test_behavior_unchanged_final_assistant_with_existing_think_tags(self, tokenizer_name):
|
| 774 |
+
tokenizer = self._load(tokenizer_name)
|
| 775 |
+
messages = [
|
| 776 |
+
{"role": "user", "content": "What color is the sky?"},
|
| 777 |
+
{
|
| 778 |
+
"role": "assistant",
|
| 779 |
+
"content": "<think>\nThe sky scatters shorter wavelengths.\n</think>\n\nIt is blue.",
|
| 780 |
+
},
|
| 781 |
+
]
|
| 782 |
+
if self.is_vlm:
|
| 783 |
+
messages = prepare_multimodal_messages(messages)
|
| 784 |
+
|
| 785 |
+
before = tokenizer.apply_chat_template(messages, tokenize=False)
|
| 786 |
+
new_chat_template = get_training_chat_template(tokenizer)
|
| 787 |
+
after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template)
|
| 788 |
+
if tokenizer_name == "trl-internal-testing/tiny-Glm4MoeForCausalLM":
|
| 789 |
+
# GLM's native template doesn't terminate an assistant turn with an end-of-turn token; the turn is ended
|
| 790 |
+
# by the following message's role marker. The training template appends that terminator to the final
|
| 791 |
+
# assistant turn so the stop token is trained — here the `<|user|>` that would open the next turn.
|
| 792 |
+
assert after == before + "<|user|>"
|
| 793 |
+
else:
|
| 794 |
+
assert before == after
|
| 795 |
+
|
| 796 |
+
def test_behavior_unchanged_assistant_with_tool_calls(self, tokenizer_name):
|
| 797 |
+
tokenizer = self._load(tokenizer_name)
|
| 798 |
+
tool_calls = [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}]
|
| 799 |
+
messages = [
|
| 800 |
+
{"role": "user", "content": "Multiply 3 by 4."},
|
| 801 |
+
{"role": "assistant", "content": "I will call a tool.", "tool_calls": tool_calls},
|
| 802 |
+
]
|
| 803 |
+
if self.is_vlm:
|
| 804 |
+
messages = prepare_multimodal_messages(messages)
|
| 805 |
+
|
| 806 |
+
messages_before = copy.deepcopy(messages)
|
| 807 |
+
if tokenizer_name == "trl-internal-testing/tiny-DeepseekV3ForCausalLM":
|
| 808 |
+
# Best-effort fallback for templates that reject dict args (e.g. DeepSeek-V3). This is a chat template
|
| 809 |
+
# bug (see transformers#45419), and the training chat template fixes it to avoid blocking users.
|
| 810 |
+
messages_before[1]["tool_calls"][0]["function"]["arguments"] = '{"a": 3, "b": 4}'
|
| 811 |
+
|
| 812 |
+
before = tokenizer.apply_chat_template(messages_before, tokenize=False)
|
| 813 |
+
new_chat_template = get_training_chat_template(tokenizer)
|
| 814 |
+
after = tokenizer.apply_chat_template(messages, tokenize=False, chat_template=new_chat_template)
|
| 815 |
+
if tokenizer_name == "trl-internal-testing/tiny-Glm4MoeForCausalLM":
|
| 816 |
+
# GLM's native template doesn't terminate an assistant turn with an end-of-turn token; the turn is ended
|
| 817 |
+
# by the following message's role marker. The training template appends that terminator to the final
|
| 818 |
+
# assistant turn so the stop token is trained — here `<|observation|>`, which closes a tool call.
|
| 819 |
+
assert after == before + "<|observation|>"
|
| 820 |
+
else:
|
| 821 |
+
assert before == after
|
| 822 |
+
|
| 823 |
+
def test_behavior_unchanged_with_tools_with_and_without_system_message(self, tokenizer_name):
|
| 824 |
+
tokenizer = self._load(tokenizer_name)
|
| 825 |
+
tools = [
|
| 826 |
+
{
|
| 827 |
+
"type": "function",
|
| 828 |
+
"function": {
|
| 829 |
+
"name": "multiply",
|
| 830 |
+
"description": "Multiply two numbers.",
|
| 831 |
+
"parameters": {
|
| 832 |
+
"type": "object",
|
| 833 |
+
"properties": {
|
| 834 |
+
"a": {"type": "number"},
|
| 835 |
+
"b": {"type": "number"},
|
| 836 |
+
},
|
| 837 |
+
"required": ["a", "b"],
|
| 838 |
+
},
|
| 839 |
+
},
|
| 840 |
+
}
|
| 841 |
+
]
|
| 842 |
+
messages = [{"role": "user", "content": "Multiply 3 by 4."}]
|
| 843 |
+
if self.is_vlm:
|
| 844 |
+
messages = prepare_multimodal_messages(messages)
|
| 845 |
+
|
| 846 |
+
before = tokenizer.apply_chat_template(messages, tokenize=False, tools=tools)
|
| 847 |
+
new_chat_template = get_training_chat_template(tokenizer)
|
| 848 |
+
after = tokenizer.apply_chat_template(messages, tokenize=False, tools=tools, chat_template=new_chat_template)
|
| 849 |
+
assert before == after
|
| 850 |
+
|
| 851 |
+
def test_behavior_unchanged_with_tools_with_system_message(self, tokenizer_name):
|
| 852 |
+
tokenizer = self._load(tokenizer_name)
|
| 853 |
+
if not supports_tool_calling(tokenizer):
|
| 854 |
+
pytest.skip("Template does not support tool calling; skipping tool_calls test.")
|
| 855 |
+
tools = [
|
| 856 |
+
{
|
| 857 |
+
"type": "function",
|
| 858 |
+
"function": {
|
| 859 |
+
"name": "multiply",
|
| 860 |
+
"description": "Multiply two numbers.",
|
| 861 |
+
"parameters": {
|
| 862 |
+
"type": "object",
|
| 863 |
+
"properties": {"a": {"type": "number"}, "b": {"type": "number"}},
|
| 864 |
+
"required": ["a", "b"],
|
| 865 |
+
},
|
| 866 |
+
},
|
| 867 |
+
}
|
| 868 |
+
]
|
| 869 |
+
messages = [
|
| 870 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
| 871 |
+
{"role": "user", "content": "Multiply 3 by 4."},
|
| 872 |
+
]
|
| 873 |
+
if self.is_vlm:
|
| 874 |
+
messages = prepare_multimodal_messages(messages)
|
| 875 |
+
|
| 876 |
+
before = tokenizer.apply_chat_template(messages, tokenize=False, tools=tools)
|
| 877 |
+
new_chat_template = get_training_chat_template(tokenizer)
|
| 878 |
+
after = tokenizer.apply_chat_template(messages, tokenize=False, tools=tools, chat_template=new_chat_template)
|
| 879 |
+
assert before == after
|
| 880 |
+
|
| 881 |
+
def test_behavior_unchanged_generation_prompt_with_enable_thinking_false(self, tokenizer_name):
|
| 882 |
+
tokenizer = self._load(tokenizer_name)
|
| 883 |
+
messages = [{"role": "user", "content": "What color is the sky?"}]
|
| 884 |
+
if self.is_vlm:
|
| 885 |
+
messages = prepare_multimodal_messages(messages)
|
| 886 |
+
|
| 887 |
+
before = tokenizer.apply_chat_template(
|
| 888 |
+
messages, tokenize=False, add_generation_prompt=True, enable_thinking=False
|
| 889 |
+
)
|
| 890 |
+
new_chat_template = get_training_chat_template(tokenizer)
|
| 891 |
+
after = tokenizer.apply_chat_template(
|
| 892 |
+
messages,
|
| 893 |
+
tokenize=False,
|
| 894 |
+
add_generation_prompt=True,
|
| 895 |
+
enable_thinking=False,
|
| 896 |
+
chat_template=new_chat_template,
|
| 897 |
+
)
|
| 898 |
+
assert before == after
|
| 899 |
+
|
| 900 |
+
def test_assistant_masks(self, tokenizer_name, request):
|
| 901 |
+
if tokenizer_name == "trl-internal-testing/tiny-LlavaForConditionalGeneration":
|
| 902 |
+
request.node.add_marker(
|
| 903 |
+
pytest.mark.xfail(
|
| 904 |
+
reason="Llava's official chat template `{% generation %}` markers don't yield assistant masks "
|
| 905 |
+
"through the processor path. It is not a supported training template.",
|
| 906 |
+
strict=True,
|
| 907 |
+
)
|
| 908 |
+
)
|
| 909 |
+
tokenizer = self._load(tokenizer_name)
|
| 910 |
+
messages = [
|
| 911 |
+
{"role": "user", "content": "What color is the sky?"},
|
| 912 |
+
{"role": "assistant", "content": "It is blue."},
|
| 913 |
+
]
|
| 914 |
+
if self.is_vlm:
|
| 915 |
+
messages = prepare_multimodal_messages(messages)
|
| 916 |
+
|
| 917 |
+
chat_template = get_training_chat_template(tokenizer)
|
| 918 |
+
result = tokenizer.apply_chat_template(
|
| 919 |
+
messages, chat_template=chat_template, return_assistant_tokens_mask=True, return_dict=True, tokenize=True
|
| 920 |
+
)
|
| 921 |
+
masks = result["assistant_masks"]
|
| 922 |
+
if self.is_vlm: # VLM processors return batched output
|
| 923 |
+
masks = masks[0]
|
| 924 |
+
assert 1 in masks
|
| 925 |
+
# The first tokens (user turn) should not be masked
|
| 926 |
+
assert masks[0] == 0
|
| 927 |
+
# The last tokens (assistant turn ending with <|im_end|>) should be masked
|
| 928 |
+
assert masks[-1] == 1
|
| 929 |
+
|
| 930 |
+
def test_assistant_masks_multi_turn(self, tokenizer_name, request):
|
| 931 |
+
if tokenizer_name == "trl-internal-testing/tiny-LlavaForConditionalGeneration":
|
| 932 |
+
request.node.add_marker(
|
| 933 |
+
pytest.mark.xfail(
|
| 934 |
+
reason="Llava's official chat template `{% generation %}` markers don't yield assistant masks "
|
| 935 |
+
"through the processor path. It is not a supported training template.",
|
| 936 |
+
strict=True,
|
| 937 |
+
)
|
| 938 |
+
)
|
| 939 |
+
tokenizer = self._load(tokenizer_name)
|
| 940 |
+
messages = [
|
| 941 |
+
{"role": "user", "content": "Hi"},
|
| 942 |
+
{"role": "assistant", "content": "Hello!"},
|
| 943 |
+
{"role": "user", "content": "Bye"},
|
| 944 |
+
{"role": "assistant", "content": "Goodbye!"},
|
| 945 |
+
]
|
| 946 |
+
if self.is_vlm:
|
| 947 |
+
messages = prepare_multimodal_messages(messages)
|
| 948 |
+
|
| 949 |
+
chat_template = get_training_chat_template(tokenizer)
|
| 950 |
+
result = tokenizer.apply_chat_template(
|
| 951 |
+
messages, chat_template=chat_template, return_assistant_tokens_mask=True, return_dict=True, tokenize=True
|
| 952 |
+
)
|
| 953 |
+
masks = result["assistant_masks"]
|
| 954 |
+
if self.is_vlm: # VLM processors return batched output
|
| 955 |
+
masks = masks[0]
|
| 956 |
+
# Should have two masked regions (two assistant turns): 0→1, 1→0, 0→1
|
| 957 |
+
transitions = sum(1 for i in range(1, len(masks)) if masks[i] != masks[i - 1])
|
| 958 |
+
assert transitions == 3
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
@pytest.mark.parametrize(
|
| 962 |
+
"model_name",
|
| 963 |
+
[
|
| 964 |
+
pytest.param("trl-internal-testing/tiny-Glm4MoeForCausalLM", id="glm4moe"),
|
| 965 |
+
pytest.param("trl-internal-testing/tiny-GptOssForCausalLM", id="gptoss"),
|
| 966 |
+
pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.1", id="llama3.1"),
|
| 967 |
+
pytest.param("trl-internal-testing/tiny-LlamaForCausalLM-3.2", id="llama3.2"),
|
| 968 |
+
pytest.param(
|
| 969 |
+
"trl-internal-testing/tiny-NemotronHForCausalLM-nano",
|
| 970 |
+
id="nemotron_3_nano",
|
| 971 |
+
marks=pytest.mark.skipif(
|
| 972 |
+
Version(transformers.__version__) < Version("5.3.0"),
|
| 973 |
+
reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
|
| 974 |
+
),
|
| 975 |
+
),
|
| 976 |
+
pytest.param(
|
| 977 |
+
"trl-internal-testing/tiny-NemotronHForCausalLM-super",
|
| 978 |
+
id="nemotron_3_super",
|
| 979 |
+
marks=pytest.mark.skipif(
|
| 980 |
+
Version(transformers.__version__) < Version("5.3.0"),
|
| 981 |
+
reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
|
| 982 |
+
),
|
| 983 |
+
),
|
| 984 |
+
pytest.param(
|
| 985 |
+
"trl-internal-testing/tiny-NemotronHForCausalLM-ultra",
|
| 986 |
+
id="nemotron_3_ultra",
|
| 987 |
+
marks=pytest.mark.skipif(
|
| 988 |
+
Version(transformers.__version__) < Version("5.3.0"),
|
| 989 |
+
reason="Nemotron 3 tokenizer requires transformers>=5.3.0",
|
| 990 |
+
),
|
| 991 |
+
),
|
| 992 |
+
pytest.param("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", id="qwen2.5"),
|
| 993 |
+
pytest.param("trl-internal-testing/tiny-Qwen3MoeForCausalLM", id="qwen3"),
|
| 994 |
+
pytest.param("trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507", id="qwen3_instruct_2507"),
|
| 995 |
+
pytest.param("trl-internal-testing/tiny-Qwen3VLForConditionalGeneration", id="qwen3_vl"),
|
| 996 |
+
pytest.param("trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink", id="qwen35-nothink"),
|
| 997 |
+
pytest.param("trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-Think", id="qwen35-think"),
|
| 998 |
+
pytest.param("trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6", id="qwen36"),
|
| 999 |
+
pytest.param(
|
| 1000 |
+
"trl-internal-testing/tiny-Gemma4ForConditionalGeneration",
|
| 1001 |
+
id="gemma4",
|
| 1002 |
+
marks=pytest.mark.skipif(
|
| 1003 |
+
Version(transformers.__version__) < Version("5.5.0"),
|
| 1004 |
+
reason="Gemma4 models were introduced in transformers-5.5.0",
|
| 1005 |
+
),
|
| 1006 |
+
),
|
| 1007 |
+
],
|
| 1008 |
+
)
|
| 1009 |
+
@pytest.mark.xfail(
|
| 1010 |
+
condition=Version(transformers.__version__) < Version("5.0.0"),
|
| 1011 |
+
reason="Response parsing is not supported in transformers versions below 5.0.0",
|
| 1012 |
+
strict=True,
|
| 1013 |
+
)
|
| 1014 |
+
@require_jmespath
|
| 1015 |
+
class TestParseResponse:
|
| 1016 |
+
def _load(self, model_name):
|
| 1017 |
+
if "ForCausalLM" in model_name:
|
| 1018 |
+
self.is_vlm = False
|
| 1019 |
+
processing_class = AutoTokenizer.from_pretrained(model_name)
|
| 1020 |
+
response_schema = getattr(processing_class, "response_schema", None)
|
| 1021 |
+
elif "ForConditionalGeneration" in model_name:
|
| 1022 |
+
self.is_vlm = True
|
| 1023 |
+
processing_class = AutoProcessor.from_pretrained(model_name)
|
| 1024 |
+
response_schema = getattr(processing_class.tokenizer, "response_schema", None)
|
| 1025 |
+
|
| 1026 |
+
if response_schema is None:
|
| 1027 |
+
processing_class = add_response_schema(processing_class)
|
| 1028 |
+
|
| 1029 |
+
return processing_class
|
| 1030 |
+
|
| 1031 |
+
def test_parse_response(self, model_name):
|
| 1032 |
+
if model_name in ("trl-internal-testing/tiny-GptOssForCausalLM",) and Version(
|
| 1033 |
+
transformers.__version__
|
| 1034 |
+
) < Version("5.5.0"):
|
| 1035 |
+
pytest.skip("Upstream bug in response parsing (see #5753; fixed in transformers#45166)")
|
| 1036 |
+
processing_class = self._load(model_name)
|
| 1037 |
+
messages = [
|
| 1038 |
+
{"role": "user", "content": "What is 3*4?"},
|
| 1039 |
+
{"role": "assistant", "content": "12"},
|
| 1040 |
+
]
|
| 1041 |
+
expected = messages[-1]
|
| 1042 |
+
messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
|
| 1043 |
+
prefix = processing_class.apply_chat_template(
|
| 1044 |
+
messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True
|
| 1045 |
+
).input_ids
|
| 1046 |
+
text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
|
| 1047 |
+
if self.is_vlm: # VLM processors return batched output
|
| 1048 |
+
prefix = prefix[0]
|
| 1049 |
+
text = text[0]
|
| 1050 |
+
response = text[len(prefix) :]
|
| 1051 |
+
tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
|
| 1052 |
+
parsed = parse_response(tokenizer, response)
|
| 1053 |
+
assert parsed == expected
|
| 1054 |
+
|
| 1055 |
+
def test_parse_response_with_reasoning_content(self, model_name):
|
| 1056 |
+
if model_name in (
|
| 1057 |
+
"trl-internal-testing/tiny-Gemma4ForConditionalGeneration",
|
| 1058 |
+
"trl-internal-testing/tiny-GptOssForCausalLM",
|
| 1059 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.1",
|
| 1060 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.2",
|
| 1061 |
+
"trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1062 |
+
"trl-internal-testing/tiny-Qwen3ForCausalLM-Instruct-2507",
|
| 1063 |
+
"trl-internal-testing/tiny-Qwen3VLForConditionalGeneration",
|
| 1064 |
+
):
|
| 1065 |
+
pytest.skip("This tokenizer doesn't support inline reasoning_content.")
|
| 1066 |
+
|
| 1067 |
+
processing_class = self._load(model_name)
|
| 1068 |
+
messages = [
|
| 1069 |
+
{"role": "user", "content": "What is 3*4?"},
|
| 1070 |
+
{"role": "assistant", "reasoning_content": "Hmmm.", "content": "12"},
|
| 1071 |
+
]
|
| 1072 |
+
expected = messages[-1]
|
| 1073 |
+
messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
|
| 1074 |
+
# enable_thinking=True is required here because the Qwen3.5 NoThink fixture disables thinking by default
|
| 1075 |
+
# for the generation prompt.
|
| 1076 |
+
prefix = processing_class.apply_chat_template(
|
| 1077 |
+
messages[:1], add_generation_prompt=True, enable_thinking=True, tokenize=True, return_dict=True
|
| 1078 |
+
).input_ids
|
| 1079 |
+
text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
|
| 1080 |
+
if self.is_vlm: # VLM processors return batched output
|
| 1081 |
+
prefix = prefix[0]
|
| 1082 |
+
text = text[0]
|
| 1083 |
+
response = text[len(prefix) :]
|
| 1084 |
+
tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
|
| 1085 |
+
parsed = parse_response(tokenizer, response)
|
| 1086 |
+
assert parsed == expected
|
| 1087 |
+
|
| 1088 |
+
def test_parse_response_tool_call(self, model_name):
|
| 1089 |
+
if model_name in (
|
| 1090 |
+
"trl-internal-testing/tiny-GptOssForCausalLM",
|
| 1091 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.1",
|
| 1092 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.2",
|
| 1093 |
+
) and Version(transformers.__version__) < Version("5.5.0"):
|
| 1094 |
+
pytest.skip("Upstream bug in response parsing (see #5753; fixed in transformers#45166)")
|
| 1095 |
+
processing_class = self._load(model_name)
|
| 1096 |
+
tool_calls = [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}]
|
| 1097 |
+
messages = [
|
| 1098 |
+
{"role": "user", "content": "What is 3*4?"},
|
| 1099 |
+
{
|
| 1100 |
+
"role": "assistant",
|
| 1101 |
+
# "content" is required here because VLM processors crash on tokenize=True without it
|
| 1102 |
+
# (KeyError in processing_utils.py). See huggingface/transformers#45290.
|
| 1103 |
+
"content": "",
|
| 1104 |
+
"tool_calls": tool_calls,
|
| 1105 |
+
},
|
| 1106 |
+
]
|
| 1107 |
+
expected = messages[-1]
|
| 1108 |
+
messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
|
| 1109 |
+
prefix = processing_class.apply_chat_template(
|
| 1110 |
+
messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True
|
| 1111 |
+
).input_ids
|
| 1112 |
+
text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
|
| 1113 |
+
if self.is_vlm: # VLM processors return batched output
|
| 1114 |
+
prefix = prefix[0]
|
| 1115 |
+
text = text[0]
|
| 1116 |
+
response = text[len(prefix) :]
|
| 1117 |
+
tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
|
| 1118 |
+
parsed = parse_response(tokenizer, response)
|
| 1119 |
+
assert parsed == expected
|
| 1120 |
+
|
| 1121 |
+
def test_parse_response_tool_call_with_content(self, model_name):
|
| 1122 |
+
if model_name in (
|
| 1123 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.1",
|
| 1124 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.2",
|
| 1125 |
+
):
|
| 1126 |
+
pytest.skip("Llama 3.1 / 3.2 templates only allow a single tool call per assistant turn, with no content.")
|
| 1127 |
+
if model_name in ("trl-internal-testing/tiny-GptOssForCausalLM",) and Version(
|
| 1128 |
+
transformers.__version__
|
| 1129 |
+
) < Version("5.5.0"):
|
| 1130 |
+
pytest.skip("Upstream bug in response parsing (see #5753; fixed in transformers#45166)")
|
| 1131 |
+
processing_class = self._load(model_name)
|
| 1132 |
+
tool_calls = [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}]
|
| 1133 |
+
messages = [
|
| 1134 |
+
{"role": "user", "content": "What is 3*4?"},
|
| 1135 |
+
{"role": "assistant", "content": "Let's call the tool.", "tool_calls": tool_calls},
|
| 1136 |
+
]
|
| 1137 |
+
expected = messages[-1]
|
| 1138 |
+
messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
|
| 1139 |
+
prefix = processing_class.apply_chat_template(
|
| 1140 |
+
messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True
|
| 1141 |
+
).input_ids
|
| 1142 |
+
text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
|
| 1143 |
+
if self.is_vlm: # VLM processors return batched output
|
| 1144 |
+
prefix = prefix[0]
|
| 1145 |
+
text = text[0]
|
| 1146 |
+
response = text[len(prefix) :]
|
| 1147 |
+
tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
|
| 1148 |
+
parsed = parse_response(tokenizer, response)
|
| 1149 |
+
assert parsed == expected
|
| 1150 |
+
|
| 1151 |
+
def test_parse_response_tool_call_without_arguments(self, model_name):
|
| 1152 |
+
if model_name in ("trl-internal-testing/tiny-GptOssForCausalLM",) and Version(
|
| 1153 |
+
transformers.__version__
|
| 1154 |
+
) < Version("5.5.0"):
|
| 1155 |
+
pytest.skip("Upstream bug in response parsing (see #5753; fixed in transformers#45166)")
|
| 1156 |
+
processing_class = self._load(model_name)
|
| 1157 |
+
tool_calls = [{"type": "function", "function": {"name": "ping", "arguments": {}}}]
|
| 1158 |
+
messages = [
|
| 1159 |
+
{"role": "user", "content": "Ping the service."},
|
| 1160 |
+
{
|
| 1161 |
+
"role": "assistant",
|
| 1162 |
+
# "content" is required here because VLM processors crash on tokenize=True without it
|
| 1163 |
+
# (KeyError in processing_utils.py). See huggingface/transformers#45290.
|
| 1164 |
+
"content": "",
|
| 1165 |
+
"tool_calls": tool_calls,
|
| 1166 |
+
},
|
| 1167 |
+
]
|
| 1168 |
+
expected = messages[-1]
|
| 1169 |
+
messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
|
| 1170 |
+
prefix = processing_class.apply_chat_template(
|
| 1171 |
+
messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True
|
| 1172 |
+
).input_ids
|
| 1173 |
+
text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
|
| 1174 |
+
if self.is_vlm: # VLM processors return batched output
|
| 1175 |
+
prefix = prefix[0]
|
| 1176 |
+
text = text[0]
|
| 1177 |
+
response = text[len(prefix) :]
|
| 1178 |
+
tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
|
| 1179 |
+
parsed = parse_response(tokenizer, response)
|
| 1180 |
+
assert parsed == expected
|
| 1181 |
+
|
| 1182 |
+
def test_parse_response_multiple_tool_calls(self, model_name):
|
| 1183 |
+
if model_name in (
|
| 1184 |
+
"trl-internal-testing/tiny-GptOssForCausalLM",
|
| 1185 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.1",
|
| 1186 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.2",
|
| 1187 |
+
):
|
| 1188 |
+
pytest.skip("This template only renders one tool call per assistant message.")
|
| 1189 |
+
processing_class = self._load(model_name)
|
| 1190 |
+
tool_calls = [
|
| 1191 |
+
{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}},
|
| 1192 |
+
{"type": "function", "function": {"name": "addition", "arguments": {"a": 4, "b": 3}}},
|
| 1193 |
+
]
|
| 1194 |
+
messages = [
|
| 1195 |
+
{"role": "user", "content": "What is 3*4?"},
|
| 1196 |
+
{
|
| 1197 |
+
"role": "assistant",
|
| 1198 |
+
# "content" is required here because VLM processors crash on tokenize=True without it
|
| 1199 |
+
# (KeyError in processing_utils.py). See huggingface/transformers#45290.
|
| 1200 |
+
"content": "",
|
| 1201 |
+
"tool_calls": tool_calls,
|
| 1202 |
+
},
|
| 1203 |
+
]
|
| 1204 |
+
expected = messages[-1]
|
| 1205 |
+
messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
|
| 1206 |
+
prefix = processing_class.apply_chat_template(
|
| 1207 |
+
messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True
|
| 1208 |
+
).input_ids
|
| 1209 |
+
text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
|
| 1210 |
+
if self.is_vlm: # VLM processors return batched output
|
| 1211 |
+
prefix = prefix[0]
|
| 1212 |
+
text = text[0]
|
| 1213 |
+
response = text[len(prefix) :]
|
| 1214 |
+
tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
|
| 1215 |
+
parsed = parse_response(tokenizer, response)
|
| 1216 |
+
assert parsed == expected
|
| 1217 |
+
|
| 1218 |
+
def test_parse_response_malformed_tool_call(self, model_name):
|
| 1219 |
+
if model_name != "trl-internal-testing/tiny-Qwen3MoeForCausalLM":
|
| 1220 |
+
pytest.skip("For simplicity, we only test the malformed tool call case on one tokenizer.")
|
| 1221 |
+
processing_class = self._load(model_name)
|
| 1222 |
+
text = '<tool_call>\n{"name": "multiply", "arguments": {"a": 3, "b": 4}\n</tool_call><|im_end|>'
|
| 1223 |
+
assistant_text = processing_class(text)["input_ids"]
|
| 1224 |
+
parsed = parse_response(processing_class, assistant_text)
|
| 1225 |
+
expected = {
|
| 1226 |
+
"role": "assistant",
|
| 1227 |
+
"content": '<tool_call>\n{"name": "multiply", "arguments": {"a": 3, "b": 4}\n</tool_call>',
|
| 1228 |
+
}
|
| 1229 |
+
|
| 1230 |
+
assert parsed == expected
|
| 1231 |
+
|
| 1232 |
+
def test_parse_response_truncated(self, model_name):
|
| 1233 |
+
processing_class = self._load(model_name)
|
| 1234 |
+
# Here we use 2 tool calls as it seems to be a more common source of failure when truncated.
|
| 1235 |
+
# Llama 3.1 / 3.2 templates only allow a single tool call per assistant turn, so fall back to one.
|
| 1236 |
+
tool_calls = [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 3, "b": 4}}}]
|
| 1237 |
+
if model_name not in (
|
| 1238 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.1",
|
| 1239 |
+
"trl-internal-testing/tiny-LlamaForCausalLM-3.2",
|
| 1240 |
+
):
|
| 1241 |
+
tool_calls.append({"type": "function", "function": {"name": "addition", "arguments": {"a": 4, "b": 3}}})
|
| 1242 |
+
messages = [
|
| 1243 |
+
{"role": "user", "content": "What is 3*4?"},
|
| 1244 |
+
{"role": "assistant", "content": "", "tool_calls": tool_calls},
|
| 1245 |
+
]
|
| 1246 |
+
messages = prepare_multimodal_messages(messages) if self.is_vlm else messages
|
| 1247 |
+
prefix = processing_class.apply_chat_template(
|
| 1248 |
+
messages[:1], add_generation_prompt=True, tokenize=True, return_dict=True
|
| 1249 |
+
).input_ids
|
| 1250 |
+
text = processing_class.apply_chat_template(messages, tokenize=True, return_dict=True).input_ids
|
| 1251 |
+
if self.is_vlm: # VLM processors return batched output
|
| 1252 |
+
prefix = prefix[0]
|
| 1253 |
+
text = text[0]
|
| 1254 |
+
response = text[len(prefix) :]
|
| 1255 |
+
tokenizer = processing_class.tokenizer if self.is_vlm else processing_class
|
| 1256 |
+
# Truncate the response mid-tool-call and just check that parsing doesn't crash.
|
| 1257 |
+
for end in range(1, len(response)):
|
| 1258 |
+
parse_response(tokenizer, response[:end])
|
tasks/tasksmith-b71e9e0a47b6/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-b71e9e0a47b6/tests/source/tests/test_cli_utils.py
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-b71e9e0a47b6/tests/source/tests/test_data_utils.py
ADDED
|
@@ -0,0 +1,1335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-b71e9e0a47b6/tests/source/tests/test_dpo_trainer.py
ADDED
|
@@ -0,0 +1,1358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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("precompute_ref_log_probs", [False, True])
|
| 221 |
+
def test_evaluate_with_raw_dataset(self, precompute_ref_log_probs):
|
| 222 |
+
# `evaluate` should accept the same (unprocessed) dataset types as the trainer, e.g. a held-out test set
|
| 223 |
+
# passed directly to `evaluate`. With `precompute_ref_log_probs=True`, the reference log-probs must also be
|
| 224 |
+
# precomputed for the freshly-passed dataset. See https://github.com/huggingface/trl/issues/6115.
|
| 225 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 226 |
+
|
| 227 |
+
training_args = DPOConfig(
|
| 228 |
+
output_dir=self.tmp_dir, precompute_ref_log_probs=precompute_ref_log_probs, report_to="none"
|
| 229 |
+
)
|
| 230 |
+
trainer = DPOTrainer(
|
| 231 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
metrics = trainer.evaluate(eval_dataset=dataset)
|
| 235 |
+
assert metrics["eval_loss"] is not None
|
| 236 |
+
|
| 237 |
+
def test_trust_remote_code(self):
|
| 238 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 239 |
+
model_id = "trl-internal-testing/tiny-RemoteForCausalLM"
|
| 240 |
+
|
| 241 |
+
with pytest.raises(ValueError, match="custom code"):
|
| 242 |
+
DPOTrainer(
|
| 243 |
+
model=model_id,
|
| 244 |
+
args=DPOConfig(output_dir=self.tmp_dir, report_to="none"),
|
| 245 |
+
train_dataset=dataset,
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
trainer = DPOTrainer(
|
| 249 |
+
model=model_id,
|
| 250 |
+
args=DPOConfig(output_dir=self.tmp_dir, report_to="none", trust_remote_code=True),
|
| 251 |
+
train_dataset=dataset,
|
| 252 |
+
)
|
| 253 |
+
assert type(trainer.model).__name__ == "RemoteForCausalLM"
|
| 254 |
+
|
| 255 |
+
@pytest.mark.parametrize(
|
| 256 |
+
"config_name",
|
| 257 |
+
[
|
| 258 |
+
"standard_preference",
|
| 259 |
+
"conversational_preference",
|
| 260 |
+
"standard_implicit_prompt_preference",
|
| 261 |
+
"conversational_implicit_prompt_preference",
|
| 262 |
+
],
|
| 263 |
+
)
|
| 264 |
+
def test_train_dataset_format(self, config_name):
|
| 265 |
+
dataset = load_dataset("trl-internal-testing/zen", config_name, split="train")
|
| 266 |
+
|
| 267 |
+
training_args = DPOConfig(
|
| 268 |
+
output_dir=self.tmp_dir,
|
| 269 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 270 |
+
report_to="none",
|
| 271 |
+
)
|
| 272 |
+
trainer = DPOTrainer(
|
| 273 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 277 |
+
|
| 278 |
+
trainer.train()
|
| 279 |
+
|
| 280 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 281 |
+
|
| 282 |
+
# Check that the params have changed
|
| 283 |
+
for n, param in previous_trainable_params.items():
|
| 284 |
+
new_param = trainer.model.get_parameter(n)
|
| 285 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 286 |
+
|
| 287 |
+
# Special case for harmony
|
| 288 |
+
def test_train_gpt_oss(self):
|
| 289 |
+
dataset = load_dataset("trl-internal-testing/harmony", "preference", split="train")
|
| 290 |
+
|
| 291 |
+
training_args = DPOConfig(
|
| 292 |
+
output_dir=self.tmp_dir,
|
| 293 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 294 |
+
report_to="none",
|
| 295 |
+
)
|
| 296 |
+
trainer = DPOTrainer(
|
| 297 |
+
model="trl-internal-testing/tiny-GptOssForCausalLM", args=training_args, train_dataset=dataset
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 301 |
+
|
| 302 |
+
trainer.train()
|
| 303 |
+
|
| 304 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 305 |
+
|
| 306 |
+
# Check that the params have changed
|
| 307 |
+
for n, param in previous_trainable_params.items():
|
| 308 |
+
new_param = trainer.model.get_parameter(n)
|
| 309 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 310 |
+
|
| 311 |
+
def test_train_model(self):
|
| 312 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 313 |
+
"trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 314 |
+
dtype="float32",
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 318 |
+
|
| 319 |
+
training_args = DPOConfig(
|
| 320 |
+
output_dir=self.tmp_dir,
|
| 321 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 322 |
+
report_to="none",
|
| 323 |
+
)
|
| 324 |
+
trainer = DPOTrainer(model=model, args=training_args, train_dataset=dataset)
|
| 325 |
+
|
| 326 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 327 |
+
|
| 328 |
+
trainer.train()
|
| 329 |
+
|
| 330 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 331 |
+
|
| 332 |
+
# Check that the params have changed
|
| 333 |
+
for n, param in previous_trainable_params.items():
|
| 334 |
+
new_param = trainer.model.get_parameter(n)
|
| 335 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 336 |
+
|
| 337 |
+
@pytest.mark.parametrize(
|
| 338 |
+
"loss_type",
|
| 339 |
+
[
|
| 340 |
+
"sigmoid",
|
| 341 |
+
"hinge",
|
| 342 |
+
"ipo",
|
| 343 |
+
"exo_pair",
|
| 344 |
+
"nca_pair",
|
| 345 |
+
"robust",
|
| 346 |
+
"bco_pair",
|
| 347 |
+
"sppo_hard",
|
| 348 |
+
"aot",
|
| 349 |
+
"aot_unpaired",
|
| 350 |
+
"apo_zero",
|
| 351 |
+
"apo_down",
|
| 352 |
+
"discopop",
|
| 353 |
+
"sft",
|
| 354 |
+
"sigmoid_norm",
|
| 355 |
+
],
|
| 356 |
+
)
|
| 357 |
+
def test_train_loss_types(self, loss_type):
|
| 358 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference")
|
| 359 |
+
|
| 360 |
+
training_args = DPOConfig(
|
| 361 |
+
output_dir=self.tmp_dir,
|
| 362 |
+
loss_type=loss_type,
|
| 363 |
+
label_smoothing=1e-3 if loss_type == "exo_pair" else 0.0,
|
| 364 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 365 |
+
report_to="none",
|
| 366 |
+
eval_strategy="steps",
|
| 367 |
+
eval_steps=3,
|
| 368 |
+
)
|
| 369 |
+
trainer = DPOTrainer(
|
| 370 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 371 |
+
args=training_args,
|
| 372 |
+
train_dataset=dataset["train"],
|
| 373 |
+
eval_dataset=dataset["test"],
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 377 |
+
|
| 378 |
+
trainer.train()
|
| 379 |
+
|
| 380 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 381 |
+
|
| 382 |
+
# Check that the params have changed
|
| 383 |
+
for n, param in previous_trainable_params.items():
|
| 384 |
+
new_param = trainer.model.get_parameter(n)
|
| 385 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 386 |
+
|
| 387 |
+
def test_train_multi_loss_types(self):
|
| 388 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 389 |
+
|
| 390 |
+
training_args = DPOConfig(
|
| 391 |
+
output_dir=self.tmp_dir,
|
| 392 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 393 |
+
loss_type=["sigmoid", "bco_pair", "sft"], # this specific combination is used in MPO
|
| 394 |
+
report_to="none",
|
| 395 |
+
)
|
| 396 |
+
trainer = DPOTrainer(
|
| 397 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 398 |
+
args=training_args,
|
| 399 |
+
train_dataset=dataset,
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 403 |
+
|
| 404 |
+
trainer.train()
|
| 405 |
+
|
| 406 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 407 |
+
|
| 408 |
+
# Check that the params have changed
|
| 409 |
+
for n, param in previous_trainable_params.items():
|
| 410 |
+
new_param = trainer.model.get_parameter(n)
|
| 411 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 412 |
+
|
| 413 |
+
def test_train_with_wpo(self):
|
| 414 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 415 |
+
|
| 416 |
+
training_args = DPOConfig(
|
| 417 |
+
output_dir=self.tmp_dir,
|
| 418 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 419 |
+
report_to="none",
|
| 420 |
+
use_weighting=True,
|
| 421 |
+
)
|
| 422 |
+
trainer = DPOTrainer(
|
| 423 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 424 |
+
args=training_args,
|
| 425 |
+
train_dataset=dataset,
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 429 |
+
|
| 430 |
+
trainer.train()
|
| 431 |
+
|
| 432 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 433 |
+
|
| 434 |
+
# Check that the params have changed
|
| 435 |
+
for n, param in previous_trainable_params.items():
|
| 436 |
+
new_param = trainer.model.get_parameter(n)
|
| 437 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 438 |
+
|
| 439 |
+
def test_train_with_ld(self):
|
| 440 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 441 |
+
|
| 442 |
+
training_args = DPOConfig(
|
| 443 |
+
output_dir=self.tmp_dir,
|
| 444 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 445 |
+
report_to="none",
|
| 446 |
+
ld_alpha=0.5,
|
| 447 |
+
)
|
| 448 |
+
trainer = DPOTrainer(
|
| 449 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 450 |
+
args=training_args,
|
| 451 |
+
train_dataset=dataset,
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 455 |
+
|
| 456 |
+
trainer.train()
|
| 457 |
+
|
| 458 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 459 |
+
|
| 460 |
+
# Check that the params have changed
|
| 461 |
+
for n, param in previous_trainable_params.items():
|
| 462 |
+
new_param = trainer.model.get_parameter(n)
|
| 463 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 464 |
+
|
| 465 |
+
@pytest.mark.parametrize(
|
| 466 |
+
"f_divergence_type",
|
| 467 |
+
["reverse_kl", "forward_kl", "js_divergence", "alpha_divergence"],
|
| 468 |
+
)
|
| 469 |
+
def test_train_with_f_divergence(self, f_divergence_type):
|
| 470 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 471 |
+
|
| 472 |
+
training_args = DPOConfig(
|
| 473 |
+
output_dir=self.tmp_dir,
|
| 474 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 475 |
+
report_to="none",
|
| 476 |
+
f_divergence_type=f_divergence_type,
|
| 477 |
+
)
|
| 478 |
+
trainer = DPOTrainer(
|
| 479 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 480 |
+
args=training_args,
|
| 481 |
+
train_dataset=dataset,
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 485 |
+
|
| 486 |
+
trainer.train()
|
| 487 |
+
|
| 488 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 489 |
+
|
| 490 |
+
# Check that the params have changed
|
| 491 |
+
for n, param in previous_trainable_params.items():
|
| 492 |
+
new_param = trainer.model.get_parameter(n)
|
| 493 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 494 |
+
|
| 495 |
+
def test_train_with_explicit_ref_model(self):
|
| 496 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 497 |
+
|
| 498 |
+
training_args = DPOConfig(
|
| 499 |
+
output_dir=self.tmp_dir,
|
| 500 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 501 |
+
report_to="none",
|
| 502 |
+
)
|
| 503 |
+
# When specifying a ref model, it's usually because we want it to be a different checkpoint, but for testing
|
| 504 |
+
# purposes we will just just use the same checkpoint
|
| 505 |
+
ref_model = AutoModelForCausalLM.from_pretrained(
|
| 506 |
+
"trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32"
|
| 507 |
+
)
|
| 508 |
+
trainer = DPOTrainer(
|
| 509 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 510 |
+
ref_model=ref_model,
|
| 511 |
+
args=training_args,
|
| 512 |
+
train_dataset=dataset,
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 516 |
+
|
| 517 |
+
trainer.train()
|
| 518 |
+
|
| 519 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 520 |
+
|
| 521 |
+
# Check that the params have changed
|
| 522 |
+
for n, param in previous_trainable_params.items():
|
| 523 |
+
new_param = trainer.model.get_parameter(n)
|
| 524 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 525 |
+
new_ref_param = trainer.ref_model.get_parameter(n)
|
| 526 |
+
torch.testing.assert_close(param, new_ref_param, msg=f"Reference model parameter {n} has changed.")
|
| 527 |
+
|
| 528 |
+
def test_train_with_sync_ref_model(self):
|
| 529 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 530 |
+
|
| 531 |
+
training_args = DPOConfig(
|
| 532 |
+
output_dir=self.tmp_dir,
|
| 533 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 534 |
+
sync_ref_model=True,
|
| 535 |
+
ref_model_sync_steps=2, # reduce sync steps to ensure a sync happens
|
| 536 |
+
report_to="none",
|
| 537 |
+
)
|
| 538 |
+
trainer = DPOTrainer(
|
| 539 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 543 |
+
assert trainer.ref_model is not None
|
| 544 |
+
previous_ref_params = {n: param.clone() for n, param in trainer.ref_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 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 554 |
+
new_ref_param = trainer.ref_model.get_parameter(n)
|
| 555 |
+
assert not torch.equal(previous_ref_params[n], new_ref_param), f"Ref Parameter {n} has not changed."
|
| 556 |
+
|
| 557 |
+
def test_train_model_dtype(self):
|
| 558 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 559 |
+
|
| 560 |
+
training_args = DPOConfig(
|
| 561 |
+
output_dir=self.tmp_dir,
|
| 562 |
+
model_init_kwargs={"dtype": torch.float16},
|
| 563 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 564 |
+
report_to="none",
|
| 565 |
+
)
|
| 566 |
+
trainer = DPOTrainer(
|
| 567 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 571 |
+
|
| 572 |
+
trainer.train()
|
| 573 |
+
|
| 574 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 575 |
+
|
| 576 |
+
# Check that the params have changed
|
| 577 |
+
for n, param in previous_trainable_params.items():
|
| 578 |
+
# For some reasonn model.layers.0.input_layernorm.weight doesn't change in GitHub Actions but does
|
| 579 |
+
# locally. We ignore this parameter for now
|
| 580 |
+
if "layernorm" in n:
|
| 581 |
+
continue
|
| 582 |
+
new_param = trainer.model.get_parameter(n)
|
| 583 |
+
# Check the torch dtype
|
| 584 |
+
assert new_param.dtype == torch.float16
|
| 585 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 586 |
+
|
| 587 |
+
@require_peft
|
| 588 |
+
def test_train_dense_with_peft_config_lora(self):
|
| 589 |
+
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 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=1.0, # 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(),
|
| 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_moe_with_peft_config(self):
|
| 624 |
+
model_id = "trl-internal-testing/tiny-GptOssForCausalLM"
|
| 625 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
|
| 626 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 627 |
+
|
| 628 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 629 |
+
|
| 630 |
+
training_args = DPOConfig(
|
| 631 |
+
output_dir=self.tmp_dir,
|
| 632 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 633 |
+
report_to="none",
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
trainer = DPOTrainer(
|
| 637 |
+
model=model_id,
|
| 638 |
+
args=training_args,
|
| 639 |
+
train_dataset=dataset,
|
| 640 |
+
peft_config=LoraConfig(target_parameters=["mlp.experts.down_proj", "mlp.experts.gate_up_proj"]),
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 644 |
+
|
| 645 |
+
trainer.train()
|
| 646 |
+
|
| 647 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 648 |
+
|
| 649 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 650 |
+
for n, param in previous_trainable_params.items():
|
| 651 |
+
new_param = trainer.model.get_parameter(n)
|
| 652 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 653 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 654 |
+
elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
|
| 655 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 656 |
+
|
| 657 |
+
@require_peft
|
| 658 |
+
def test_train_peft_model(self):
|
| 659 |
+
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 660 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
|
| 661 |
+
|
| 662 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 663 |
+
|
| 664 |
+
lora_config = LoraConfig()
|
| 665 |
+
model = get_peft_model(model, lora_config)
|
| 666 |
+
|
| 667 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 668 |
+
|
| 669 |
+
training_args = DPOConfig(
|
| 670 |
+
output_dir=self.tmp_dir,
|
| 671 |
+
learning_rate=1.0, # use higher lr because gradients are tiny and default lr can stall updates
|
| 672 |
+
report_to="none",
|
| 673 |
+
)
|
| 674 |
+
trainer = DPOTrainer(model=model, args=training_args, train_dataset=dataset)
|
| 675 |
+
|
| 676 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 677 |
+
|
| 678 |
+
trainer.train()
|
| 679 |
+
|
| 680 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 681 |
+
|
| 682 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 683 |
+
for n, param in previous_trainable_params.items():
|
| 684 |
+
new_param = trainer.model.get_parameter(n)
|
| 685 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 686 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 687 |
+
elif "base_layer" not in n and "ref" not in n: # and the peft params to be different (except base and ref)
|
| 688 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 689 |
+
|
| 690 |
+
@require_peft
|
| 691 |
+
def test_train_moe_peft_model(self):
|
| 692 |
+
# Regression test for https://github.com/huggingface/trl/issues/5222. PEFT only supports one adapter per model
|
| 693 |
+
# when the LoRA config uses `target_parameters` (see peft#3340), so no "ref" adapter can be created and the
|
| 694 |
+
# reference log probs are computed with adapters disabled instead.
|
| 695 |
+
model_id = "trl-internal-testing/tiny-GptOssForCausalLM"
|
| 696 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
|
| 697 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 698 |
+
|
| 699 |
+
lora_config = LoraConfig(target_parameters=["mlp.experts.down_proj", "mlp.experts.gate_up_proj"])
|
| 700 |
+
model = get_peft_model(model, lora_config)
|
| 701 |
+
|
| 702 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 703 |
+
|
| 704 |
+
training_args = DPOConfig(
|
| 705 |
+
output_dir=self.tmp_dir,
|
| 706 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 707 |
+
report_to="none",
|
| 708 |
+
)
|
| 709 |
+
trainer = DPOTrainer(model=model, args=training_args, train_dataset=dataset)
|
| 710 |
+
|
| 711 |
+
assert "ref" not in trainer.model.peft_config
|
| 712 |
+
|
| 713 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 714 |
+
|
| 715 |
+
trainer.train()
|
| 716 |
+
|
| 717 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 718 |
+
|
| 719 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 720 |
+
for n, param in previous_trainable_params.items():
|
| 721 |
+
new_param = trainer.model.get_parameter(n)
|
| 722 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 723 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 724 |
+
elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
|
| 725 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 726 |
+
|
| 727 |
+
# In practice, this test is the same as `test_train_dense_with_peft_config_lora`, since gradient checkpointing is
|
| 728 |
+
# enabled by default in `DPOTrainer`. We keep it as a regression guard: if the default ever changes, we still
|
| 729 |
+
# explicitly test PEFT + gradient checkpointing, which has caused issues in the past.
|
| 730 |
+
@require_peft
|
| 731 |
+
def test_train_with_peft_config_and_gradient_checkpointing(self):
|
| 732 |
+
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 733 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
|
| 734 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 735 |
+
|
| 736 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 737 |
+
|
| 738 |
+
training_args = DPOConfig(
|
| 739 |
+
output_dir=self.tmp_dir,
|
| 740 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 741 |
+
gradient_checkpointing=True,
|
| 742 |
+
report_to="none",
|
| 743 |
+
)
|
| 744 |
+
|
| 745 |
+
trainer = DPOTrainer(
|
| 746 |
+
model=model_id,
|
| 747 |
+
args=training_args,
|
| 748 |
+
train_dataset=dataset,
|
| 749 |
+
peft_config=LoraConfig(),
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 753 |
+
|
| 754 |
+
trainer.train()
|
| 755 |
+
|
| 756 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 757 |
+
|
| 758 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 759 |
+
for n, param in previous_trainable_params.items():
|
| 760 |
+
new_param = trainer.model.get_parameter(n)
|
| 761 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 762 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 763 |
+
elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
|
| 764 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 765 |
+
|
| 766 |
+
@require_liger_kernel
|
| 767 |
+
def test_train_with_liger(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 |
+
use_liger_kernel=True,
|
| 774 |
+
report_to="none",
|
| 775 |
+
)
|
| 776 |
+
trainer = DPOTrainer(
|
| 777 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 781 |
+
|
| 782 |
+
trainer.train()
|
| 783 |
+
|
| 784 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 785 |
+
|
| 786 |
+
# Check that the params have changed
|
| 787 |
+
for n, param in previous_trainable_params.items():
|
| 788 |
+
new_param = trainer.model.get_parameter(n)
|
| 789 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 790 |
+
|
| 791 |
+
@require_liger_kernel
|
| 792 |
+
@require_peft
|
| 793 |
+
def test_init_fails_with_peft_and_liger(self):
|
| 794 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 795 |
+
|
| 796 |
+
training_args = DPOConfig(
|
| 797 |
+
output_dir=self.tmp_dir,
|
| 798 |
+
use_liger_kernel=True,
|
| 799 |
+
report_to="none",
|
| 800 |
+
)
|
| 801 |
+
|
| 802 |
+
with pytest.raises(NotImplementedError, match="Liger DPO loss is not implemented for PEFT models."):
|
| 803 |
+
DPOTrainer(
|
| 804 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 805 |
+
args=training_args,
|
| 806 |
+
train_dataset=dataset,
|
| 807 |
+
peft_config=LoraConfig(),
|
| 808 |
+
)
|
| 809 |
+
|
| 810 |
+
def test_train_with_iterable_dataset(self):
|
| 811 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train", streaming=True)
|
| 812 |
+
|
| 813 |
+
training_args = DPOConfig(
|
| 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 |
+
max_steps=3,
|
| 817 |
+
report_to="none",
|
| 818 |
+
)
|
| 819 |
+
trainer = DPOTrainer(
|
| 820 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
|
| 821 |
+
)
|
| 822 |
+
|
| 823 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 824 |
+
|
| 825 |
+
trainer.train()
|
| 826 |
+
|
| 827 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 828 |
+
|
| 829 |
+
# Check that the params have changed
|
| 830 |
+
for n, param in previous_trainable_params.items():
|
| 831 |
+
new_param = trainer.model.get_parameter(n)
|
| 832 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 833 |
+
|
| 834 |
+
@require_kernels
|
| 835 |
+
@pytest.mark.skipif(
|
| 836 |
+
not is_ampere_or_newer() and torch_device != "xpu",
|
| 837 |
+
reason="Flash Attention 2 requires Ampere or newer GPU, or XPU",
|
| 838 |
+
)
|
| 839 |
+
def test_train_padding_free(self):
|
| 840 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 841 |
+
|
| 842 |
+
training_args = DPOConfig(
|
| 843 |
+
output_dir=self.tmp_dir,
|
| 844 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 845 |
+
padding_free=True,
|
| 846 |
+
model_init_kwargs={"attn_implementation": "kernels-community/flash-attn2"},
|
| 847 |
+
bf16=True, # flash_attention_2 only supports bf16 and fp16
|
| 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_chat_template_kwargs(self):
|
| 866 |
+
dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train")
|
| 867 |
+
|
| 868 |
+
training_args = DPOConfig(
|
| 869 |
+
output_dir=self.tmp_dir,
|
| 870 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 871 |
+
report_to="none",
|
| 872 |
+
)
|
| 873 |
+
|
| 874 |
+
tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
|
| 875 |
+
# The following template is a simplified version of the Qwen chat template, where an additional argument
|
| 876 |
+
# `role_capital` is used to control the capitalization of roles.
|
| 877 |
+
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 -%}'
|
| 878 |
+
|
| 879 |
+
dataset = dataset.add_column(
|
| 880 |
+
"chat_template_kwargs", [{"role_capital": bool(i % 2)} for i in range(len(dataset))]
|
| 881 |
+
)
|
| 882 |
+
assert "chat_template_kwargs" in dataset.features
|
| 883 |
+
|
| 884 |
+
trainer = DPOTrainer(
|
| 885 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 886 |
+
args=training_args,
|
| 887 |
+
train_dataset=dataset,
|
| 888 |
+
processing_class=tokenizer,
|
| 889 |
+
)
|
| 890 |
+
|
| 891 |
+
assert trainer.processing_class.chat_template == tokenizer.chat_template
|
| 892 |
+
|
| 893 |
+
for i in range(2):
|
| 894 |
+
role = "SYSTEM" if i else "system"
|
| 895 |
+
system_prompt = (
|
| 896 |
+
f"<|im_start|>{role}\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>"
|
| 897 |
+
)
|
| 898 |
+
system_prompt_ids = trainer.processing_class(system_prompt)["input_ids"]
|
| 899 |
+
assert trainer.train_dataset[i]["prompt_ids"][: len(system_prompt_ids)] == system_prompt_ids
|
| 900 |
+
|
| 901 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 902 |
+
|
| 903 |
+
trainer.train()
|
| 904 |
+
|
| 905 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 906 |
+
|
| 907 |
+
# Check that the params have changed
|
| 908 |
+
for n, param in previous_trainable_params.items():
|
| 909 |
+
new_param = trainer.model.get_parameter(n)
|
| 910 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 911 |
+
|
| 912 |
+
def test_train_toolcall_data(self):
|
| 913 |
+
dataset = load_dataset("trl-internal-testing/toolcall", "preference", split="train")
|
| 914 |
+
|
| 915 |
+
training_args = DPOConfig(
|
| 916 |
+
output_dir=self.tmp_dir,
|
| 917 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 918 |
+
per_device_train_batch_size=2, # toolcall sequences are longer than standard data, reduce batch size to avoid OOM
|
| 919 |
+
max_length=512, # toolcall sequences are longer than standard data, limit length to avoid OOM
|
| 920 |
+
report_to="none",
|
| 921 |
+
)
|
| 922 |
+
trainer = DPOTrainer(
|
| 923 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
|
| 924 |
+
)
|
| 925 |
+
|
| 926 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 927 |
+
|
| 928 |
+
trainer.train()
|
| 929 |
+
|
| 930 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 931 |
+
|
| 932 |
+
# Check that the params have changed
|
| 933 |
+
for n, param in previous_trainable_params.items():
|
| 934 |
+
new_param = trainer.model.get_parameter(n)
|
| 935 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 936 |
+
|
| 937 |
+
def test_train_with_eval(self):
|
| 938 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference")
|
| 939 |
+
|
| 940 |
+
training_args = DPOConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none")
|
| 941 |
+
trainer = DPOTrainer(
|
| 942 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 943 |
+
args=training_args,
|
| 944 |
+
train_dataset=dataset["train"],
|
| 945 |
+
eval_dataset=dataset["test"],
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
trainer.train()
|
| 949 |
+
|
| 950 |
+
assert trainer.state.log_history[0]["eval_loss"] is not None
|
| 951 |
+
|
| 952 |
+
def test_train_with_multiple_eval_dataset(self):
|
| 953 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference")
|
| 954 |
+
|
| 955 |
+
training_args = DPOConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none")
|
| 956 |
+
trainer = DPOTrainer(
|
| 957 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 958 |
+
args=training_args,
|
| 959 |
+
train_dataset=dataset["train"],
|
| 960 |
+
eval_dataset={"data1": dataset["test"], "data2": dataset["test"]},
|
| 961 |
+
)
|
| 962 |
+
trainer.train()
|
| 963 |
+
|
| 964 |
+
assert trainer.state.log_history[-3]["eval_data1_loss"] is not None
|
| 965 |
+
assert trainer.state.log_history[-2]["eval_data2_loss"] is not None
|
| 966 |
+
|
| 967 |
+
def test_train_with_compute_metrics(self):
|
| 968 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference")
|
| 969 |
+
|
| 970 |
+
def dummy_compute_metrics(eval_pred):
|
| 971 |
+
return {"my_metric": 0.123}
|
| 972 |
+
|
| 973 |
+
training_args = DPOConfig(
|
| 974 |
+
output_dir=self.tmp_dir,
|
| 975 |
+
eval_strategy="steps",
|
| 976 |
+
eval_steps=3,
|
| 977 |
+
report_to="none",
|
| 978 |
+
)
|
| 979 |
+
trainer = DPOTrainer(
|
| 980 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 981 |
+
args=training_args,
|
| 982 |
+
train_dataset=dataset["train"],
|
| 983 |
+
eval_dataset=dataset["test"],
|
| 984 |
+
compute_metrics=dummy_compute_metrics,
|
| 985 |
+
)
|
| 986 |
+
|
| 987 |
+
trainer.train()
|
| 988 |
+
|
| 989 |
+
assert trainer.state.log_history[-2]["eval_my_metric"] == 0.123
|
| 990 |
+
|
| 991 |
+
# In practice, this test is the same as `test_train`, since gradient checkpointing is enabled by default in
|
| 992 |
+
# `DPOTrainer`. We keep it as a regression guard: if the default ever changes, we still explicitly test gradient
|
| 993 |
+
# checkpointing, which has caused issues in the past.
|
| 994 |
+
def test_train_with_gradient_checkpointing(self):
|
| 995 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 996 |
+
|
| 997 |
+
training_args = DPOConfig(
|
| 998 |
+
output_dir=self.tmp_dir,
|
| 999 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1000 |
+
gradient_checkpointing=True,
|
| 1001 |
+
report_to="none",
|
| 1002 |
+
)
|
| 1003 |
+
trainer = DPOTrainer(
|
| 1004 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
|
| 1005 |
+
)
|
| 1006 |
+
|
| 1007 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1008 |
+
|
| 1009 |
+
trainer.train()
|
| 1010 |
+
|
| 1011 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1012 |
+
|
| 1013 |
+
# Check that the params have changed
|
| 1014 |
+
for n, param in previous_trainable_params.items():
|
| 1015 |
+
new_param = trainer.model.get_parameter(n)
|
| 1016 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1017 |
+
|
| 1018 |
+
def test_tag_added(self):
|
| 1019 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 1020 |
+
|
| 1021 |
+
trainer = DPOTrainer(
|
| 1022 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1023 |
+
train_dataset=dataset,
|
| 1024 |
+
)
|
| 1025 |
+
|
| 1026 |
+
for tag in ["dpo", "trl"]:
|
| 1027 |
+
assert tag in trainer.model.model_tags
|
| 1028 |
+
|
| 1029 |
+
@require_peft
|
| 1030 |
+
def test_tag_added_peft(self):
|
| 1031 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 1032 |
+
|
| 1033 |
+
trainer = DPOTrainer(
|
| 1034 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1035 |
+
train_dataset=dataset,
|
| 1036 |
+
peft_config=LoraConfig(),
|
| 1037 |
+
)
|
| 1038 |
+
|
| 1039 |
+
for tag in ["dpo", "trl"]:
|
| 1040 |
+
assert tag in trainer.model.model_tags
|
| 1041 |
+
|
| 1042 |
+
@require_peft
|
| 1043 |
+
@require_bitsandbytes
|
| 1044 |
+
def test_peft_with_quantization(self):
|
| 1045 |
+
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 1046 |
+
|
| 1047 |
+
quantization_config = BitsAndBytesConfig(
|
| 1048 |
+
load_in_4bit=True,
|
| 1049 |
+
bnb_4bit_use_double_quant=True,
|
| 1050 |
+
bnb_4bit_quant_type="nf4",
|
| 1051 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 1052 |
+
)
|
| 1053 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 1054 |
+
model_id,
|
| 1055 |
+
dtype="float32",
|
| 1056 |
+
quantization_config=quantization_config,
|
| 1057 |
+
)
|
| 1058 |
+
|
| 1059 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
|
| 1060 |
+
|
| 1061 |
+
# Initialize the trainer with the already configured PeftModel
|
| 1062 |
+
training_args = DPOConfig(output_dir=self.tmp_dir, learning_rate=0.1, report_to="none")
|
| 1063 |
+
trainer = DPOTrainer(model=model, args=training_args, train_dataset=dataset, peft_config=LoraConfig())
|
| 1064 |
+
|
| 1065 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1066 |
+
|
| 1067 |
+
trainer.train()
|
| 1068 |
+
|
| 1069 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1070 |
+
assert trainer.state.log_history[-1]["mean_token_accuracy"] is not None
|
| 1071 |
+
|
| 1072 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 1073 |
+
for n, param in previous_trainable_params.items():
|
| 1074 |
+
new_param = trainer.model.get_parameter(n)
|
| 1075 |
+
# In bitsandbytes, bias parameters are automatically cast to the input dtype during the forward pass if
|
| 1076 |
+
# their dtype doesn’t match. This causes the module to change unexpectedly during the first forward pass of
|
| 1077 |
+
# the training. To handle this, we cast these specific bias parameters to float32 before comparison.
|
| 1078 |
+
# https://github.com/bitsandbytes-foundation/bitsandbytes/blob/45553f7392e524eacf400b132cfe01261f6477be/bitsandbytes/nn/modules.py#L518
|
| 1079 |
+
# We still need to investigate why the compute dtype ends up being different than for these parameters.
|
| 1080 |
+
if n in [
|
| 1081 |
+
"base_model.model.model.layers.1.self_attn.k_proj.bias",
|
| 1082 |
+
"base_model.model.model.layers.1.self_attn.q_proj.base_layer.bias",
|
| 1083 |
+
"base_model.model.model.layers.1.self_attn.v_proj.base_layer.bias",
|
| 1084 |
+
]:
|
| 1085 |
+
param = param.float()
|
| 1086 |
+
|
| 1087 |
+
if "lora" not in n: # We expect the base model params to be the same
|
| 1088 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 1089 |
+
elif "lora" in n: # We expect the peft params to be different
|
| 1090 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1091 |
+
else:
|
| 1092 |
+
raise ValueError(f"Unexpected parameter {n} in model: {trainer.model}")
|
| 1093 |
+
|
| 1094 |
+
|
| 1095 |
+
@require_vision
|
| 1096 |
+
class TestDPOTrainerVLM(TrlTestCase):
|
| 1097 |
+
@pytest.mark.parametrize(
|
| 1098 |
+
"model_id",
|
| 1099 |
+
[
|
| 1100 |
+
"trl-internal-testing/tiny-Gemma3ForConditionalGeneration",
|
| 1101 |
+
pytest.param(
|
| 1102 |
+
"trl-internal-testing/tiny-Gemma4ForConditionalGeneration",
|
| 1103 |
+
marks=pytest.mark.skipif(
|
| 1104 |
+
Version(transformers.__version__) < Version("5.5.0"),
|
| 1105 |
+
reason="Gemma4 models were introduced in transformers-5.5.0",
|
| 1106 |
+
),
|
| 1107 |
+
),
|
| 1108 |
+
# "trl-internal-testing/tiny-Idefics2ForConditionalGeneration", high memory peak, skipped for now
|
| 1109 |
+
# "trl-internal-testing/tiny-Idefics3ForConditionalGeneration", high memory peak, skipped for now
|
| 1110 |
+
"trl-internal-testing/tiny-LlavaForConditionalGeneration",
|
| 1111 |
+
"trl-internal-testing/tiny-LlavaNextForConditionalGeneration",
|
| 1112 |
+
"trl-internal-testing/tiny-Qwen2VLForConditionalGeneration",
|
| 1113 |
+
"trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 1114 |
+
# "trl-internal-testing/tiny-SmolVLMForConditionalGeneration", seems not to support bf16 properly
|
| 1115 |
+
pytest.param(
|
| 1116 |
+
"trl-internal-testing/tiny-Qwen3VLForConditionalGeneration",
|
| 1117 |
+
marks=[
|
| 1118 |
+
pytest.mark.skipif(
|
| 1119 |
+
Version(transformers.__version__) < Version("4.57.0"),
|
| 1120 |
+
reason="Qwen3-VL series were introduced in transformers-4.57.0",
|
| 1121 |
+
),
|
| 1122 |
+
],
|
| 1123 |
+
),
|
| 1124 |
+
pytest.param(
|
| 1125 |
+
"trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink",
|
| 1126 |
+
marks=pytest.mark.skipif(
|
| 1127 |
+
Version(transformers.__version__) < Version("5.2.0"),
|
| 1128 |
+
reason="Qwen3.5 models were introduced in transformers-5.2.0",
|
| 1129 |
+
),
|
| 1130 |
+
),
|
| 1131 |
+
pytest.param(
|
| 1132 |
+
"trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6",
|
| 1133 |
+
marks=pytest.mark.skipif(
|
| 1134 |
+
Version(transformers.__version__) < Version("5.2.0"),
|
| 1135 |
+
reason="Qwen3.5 models were introduced in transformers-5.2.0",
|
| 1136 |
+
),
|
| 1137 |
+
),
|
| 1138 |
+
],
|
| 1139 |
+
)
|
| 1140 |
+
def test_train_vlm(self, model_id):
|
| 1141 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
|
| 1142 |
+
|
| 1143 |
+
training_args = DPOConfig(
|
| 1144 |
+
output_dir=self.tmp_dir,
|
| 1145 |
+
max_length=None, # for VLMs, truncating can remove image tokens, leading to errors
|
| 1146 |
+
per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 1147 |
+
report_to="none",
|
| 1148 |
+
)
|
| 1149 |
+
trainer = DPOTrainer(model=model_id, args=training_args, train_dataset=dataset)
|
| 1150 |
+
|
| 1151 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1152 |
+
|
| 1153 |
+
trainer.train()
|
| 1154 |
+
|
| 1155 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1156 |
+
|
| 1157 |
+
# Check that the params have changed
|
| 1158 |
+
for n, param in previous_trainable_params.items():
|
| 1159 |
+
new_param = trainer.model.get_parameter(n)
|
| 1160 |
+
# LLaVA & LLaVA-Next: vision_feature_layer=-2 leaves the last encoder layer (layers.1) and
|
| 1161 |
+
# post_layernorm (pooler-only path) without gradient by design. Assert they stay frozen — if they
|
| 1162 |
+
# ever start training, the feature-selection plumbing has likely regressed.
|
| 1163 |
+
if model_id in (
|
| 1164 |
+
"trl-internal-testing/tiny-LlavaForConditionalGeneration",
|
| 1165 |
+
"trl-internal-testing/tiny-LlavaNextForConditionalGeneration",
|
| 1166 |
+
) and ("encoder.layers.1" in n or "post_layernorm" in n):
|
| 1167 |
+
assert torch.equal(param, new_param), f"Param {n} expected frozen by LLaVA design, but changed"
|
| 1168 |
+
else:
|
| 1169 |
+
assert not torch.equal(param, new_param), f"Param {n} is not updated"
|
| 1170 |
+
|
| 1171 |
+
@pytest.mark.parametrize(
|
| 1172 |
+
"model_id",
|
| 1173 |
+
[
|
| 1174 |
+
"trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 1175 |
+
],
|
| 1176 |
+
)
|
| 1177 |
+
@pytest.mark.xfail(
|
| 1178 |
+
parse_version(transformers.__version__) < parse_version("4.57.0"),
|
| 1179 |
+
reason="Mixing text-only and image+text examples is only supported in transformers >= 4.57.0",
|
| 1180 |
+
strict=False,
|
| 1181 |
+
)
|
| 1182 |
+
def test_train_vlm_multi_image(self, model_id):
|
| 1183 |
+
dataset = load_dataset("trl-internal-testing/zen-multi-image", "conversational_preference", split="train")
|
| 1184 |
+
|
| 1185 |
+
training_args = DPOConfig(
|
| 1186 |
+
output_dir=self.tmp_dir,
|
| 1187 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1188 |
+
max_length=None, # for VLMs, truncating can remove image tokens, leading to errors
|
| 1189 |
+
per_device_train_batch_size=1, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 1190 |
+
report_to="none",
|
| 1191 |
+
)
|
| 1192 |
+
trainer = DPOTrainer(
|
| 1193 |
+
model=model_id,
|
| 1194 |
+
args=training_args,
|
| 1195 |
+
train_dataset=dataset,
|
| 1196 |
+
)
|
| 1197 |
+
|
| 1198 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1199 |
+
|
| 1200 |
+
trainer.train()
|
| 1201 |
+
|
| 1202 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1203 |
+
|
| 1204 |
+
# Check that the params have changed
|
| 1205 |
+
for n, param in previous_trainable_params.items():
|
| 1206 |
+
new_param = trainer.model.get_parameter(n)
|
| 1207 |
+
assert not torch.equal(param, new_param), f"Param {n} is not updated"
|
| 1208 |
+
|
| 1209 |
+
@pytest.mark.parametrize(
|
| 1210 |
+
"model_id",
|
| 1211 |
+
[
|
| 1212 |
+
"trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 1213 |
+
],
|
| 1214 |
+
)
|
| 1215 |
+
@pytest.mark.parametrize(
|
| 1216 |
+
"dataset_config",
|
| 1217 |
+
["conversational_preference", "standard_preference"],
|
| 1218 |
+
)
|
| 1219 |
+
def test_train_vlm_text_only_data(self, model_id, dataset_config):
|
| 1220 |
+
dataset = load_dataset("trl-internal-testing/zen", dataset_config, split="train")
|
| 1221 |
+
|
| 1222 |
+
training_args = DPOConfig(output_dir=self.tmp_dir, report_to="none")
|
| 1223 |
+
trainer = DPOTrainer(
|
| 1224 |
+
model=model_id,
|
| 1225 |
+
args=training_args,
|
| 1226 |
+
train_dataset=dataset,
|
| 1227 |
+
)
|
| 1228 |
+
|
| 1229 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1230 |
+
|
| 1231 |
+
trainer.train()
|
| 1232 |
+
|
| 1233 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1234 |
+
|
| 1235 |
+
# Check that the params have changed
|
| 1236 |
+
for n, param in previous_trainable_params.items():
|
| 1237 |
+
new_param = trainer.model.get_parameter(n)
|
| 1238 |
+
if n.startswith("model.visual"):
|
| 1239 |
+
torch.testing.assert_close(param, new_param, rtol=1e-12, atol=1e-12, msg=f"Param {n} is updated")
|
| 1240 |
+
else:
|
| 1241 |
+
assert not torch.equal(param, new_param), f"Param {n} is not updated"
|
| 1242 |
+
|
| 1243 |
+
def test_train_vlm_with_max_length(self):
|
| 1244 |
+
# Regression test for #5283: mm_token_type_ids must be truncated alongside input_ids when max_length is set,
|
| 1245 |
+
# otherwise a shape mismatch crashes the model forward pass.
|
| 1246 |
+
# max_length=37 truncates 1 completion token (total_len=38) while keeping all image tokens (prompt_len=34) safe.
|
| 1247 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
|
| 1248 |
+
training_args = DPOConfig(
|
| 1249 |
+
output_dir=self.tmp_dir,
|
| 1250 |
+
max_length=37, # total_len=38, prompt_len=34 — truncates completion, not image tokens
|
| 1251 |
+
per_device_train_batch_size=2,
|
| 1252 |
+
report_to="none",
|
| 1253 |
+
)
|
| 1254 |
+
trainer = DPOTrainer(
|
| 1255 |
+
model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 1256 |
+
args=training_args,
|
| 1257 |
+
train_dataset=dataset,
|
| 1258 |
+
)
|
| 1259 |
+
trainer.train()
|
| 1260 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1261 |
+
|
| 1262 |
+
def test_train_vlm_keep_end_raises(self):
|
| 1263 |
+
# Regression test for #5285: keep_end with a VLM must raise at init time, not silently corrupt training.
|
| 1264 |
+
# Image tokens live at the start of the sequence (in the prompt); keep_end would drop them.
|
| 1265 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
|
| 1266 |
+
with pytest.warns(FutureWarning, match="keep_end.*deprecated"):
|
| 1267 |
+
training_args = DPOConfig(
|
| 1268 |
+
output_dir=self.tmp_dir,
|
| 1269 |
+
max_length=32,
|
| 1270 |
+
truncation_mode="keep_end",
|
| 1271 |
+
report_to="none",
|
| 1272 |
+
)
|
| 1273 |
+
with pytest.raises(ValueError, match="truncation_mode='keep_end' is not supported for vision-language models"):
|
| 1274 |
+
DPOTrainer(
|
| 1275 |
+
model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 1276 |
+
args=training_args,
|
| 1277 |
+
train_dataset=dataset,
|
| 1278 |
+
)
|
| 1279 |
+
|
| 1280 |
+
def test_vision_dataset_with_text_model_raises(self):
|
| 1281 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
|
| 1282 |
+
training_args = DPOConfig(output_dir=self.tmp_dir, report_to="none")
|
| 1283 |
+
with pytest.raises(ValueError, match="vision-related.*vision-language model"):
|
| 1284 |
+
DPOTrainer(
|
| 1285 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1286 |
+
args=training_args,
|
| 1287 |
+
train_dataset=dataset,
|
| 1288 |
+
)
|
| 1289 |
+
|
| 1290 |
+
def test_precompute_ref_log_probs_raises_for_vision(self):
|
| 1291 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
|
| 1292 |
+
training_args = DPOConfig(output_dir=self.tmp_dir, report_to="none", precompute_ref_log_probs=True)
|
| 1293 |
+
with pytest.raises(ValueError, match="precompute_ref_log_probs.*not supported for vision datasets"):
|
| 1294 |
+
DPOTrainer(
|
| 1295 |
+
model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 1296 |
+
args=training_args,
|
| 1297 |
+
train_dataset=dataset,
|
| 1298 |
+
)
|
| 1299 |
+
|
| 1300 |
+
@require_liger_kernel
|
| 1301 |
+
def test_train_vlm_liger(self):
|
| 1302 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
|
| 1303 |
+
training_args = DPOConfig(
|
| 1304 |
+
output_dir=self.tmp_dir,
|
| 1305 |
+
max_length=None, # for VLMs, truncating can remove image tokens, leading to errors
|
| 1306 |
+
per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 1307 |
+
use_liger_kernel=True,
|
| 1308 |
+
report_to="none",
|
| 1309 |
+
)
|
| 1310 |
+
trainer = DPOTrainer(
|
| 1311 |
+
model="trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 1312 |
+
args=training_args,
|
| 1313 |
+
train_dataset=dataset,
|
| 1314 |
+
)
|
| 1315 |
+
|
| 1316 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1317 |
+
|
| 1318 |
+
trainer.train()
|
| 1319 |
+
|
| 1320 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1321 |
+
|
| 1322 |
+
for n, param in previous_trainable_params.items():
|
| 1323 |
+
new_param = trainer.model.get_parameter(n)
|
| 1324 |
+
assert not torch.equal(param, new_param), f"Param {n} is not updated"
|
| 1325 |
+
|
| 1326 |
+
|
| 1327 |
+
@pytest.mark.slow
|
| 1328 |
+
class TestDPOTrainerSlow(TrlTestCase):
|
| 1329 |
+
# Gemma 3n uses a timm encoder, making it difficult to create a smaller variant for testing.
|
| 1330 |
+
# To ensure coverage, we run tests on the full model but mark them as slow to exclude from default runs.
|
| 1331 |
+
@pytest.mark.skip(reason="Model google/gemma-3n-E2B-it is gated and requires HF token")
|
| 1332 |
+
@require_vision
|
| 1333 |
+
def test_train_vlm_gemma_3n(self):
|
| 1334 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_preference", split="train")
|
| 1335 |
+
|
| 1336 |
+
training_args = DPOConfig(
|
| 1337 |
+
output_dir=self.tmp_dir,
|
| 1338 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1339 |
+
max_length=None, # for VLMs, truncating can remove image tokens, leading to errors
|
| 1340 |
+
per_device_train_batch_size=1, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 1341 |
+
model_init_kwargs={"dtype": "bfloat16"},
|
| 1342 |
+
report_to="none",
|
| 1343 |
+
)
|
| 1344 |
+
trainer = DPOTrainer(model="google/gemma-3n-E2B-it", args=training_args, train_dataset=dataset)
|
| 1345 |
+
|
| 1346 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1347 |
+
|
| 1348 |
+
trainer.train()
|
| 1349 |
+
|
| 1350 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1351 |
+
|
| 1352 |
+
# Check that the params have changed
|
| 1353 |
+
for n, param in previous_trainable_params.items():
|
| 1354 |
+
new_param = trainer.model.get_parameter(n)
|
| 1355 |
+
if "model.audio_tower" in n or "model.embed_audio" in n:
|
| 1356 |
+
# The audio embedding parameters are not updated because this dataset contains no audio data
|
| 1357 |
+
continue
|
| 1358 |
+
assert not torch.equal(param, new_param), f"Param {n} is not updated"
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_grpo_trainer.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-b71e9e0a47b6/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-b71e9e0a47b6/tests/source/tests/test_reward_trainer.py
ADDED
|
@@ -0,0 +1,868 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
# 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 |
+
def test_evaluate_with_raw_dataset(self):
|
| 151 |
+
# `evaluate` should accept the same (unprocessed) dataset types as the trainer, e.g. a held-out test set
|
| 152 |
+
# passed directly to `evaluate`. See https://github.com/huggingface/trl/issues/6115.
|
| 153 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 154 |
+
|
| 155 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
|
| 156 |
+
trainer = RewardTrainer(
|
| 157 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
metrics = trainer.evaluate(eval_dataset=dataset)
|
| 161 |
+
assert metrics["eval_loss"] is not None
|
| 162 |
+
|
| 163 |
+
def test_trust_remote_code(self):
|
| 164 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 165 |
+
model_id = "trl-internal-testing/tiny-RemoteForCausalLM"
|
| 166 |
+
|
| 167 |
+
with pytest.raises(ValueError, match="custom code"):
|
| 168 |
+
RewardTrainer(
|
| 169 |
+
model=model_id,
|
| 170 |
+
args=RewardConfig(output_dir=self.tmp_dir, report_to="none"),
|
| 171 |
+
train_dataset=dataset,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
trainer = RewardTrainer(
|
| 175 |
+
model=model_id,
|
| 176 |
+
args=RewardConfig(output_dir=self.tmp_dir, report_to="none", trust_remote_code=True),
|
| 177 |
+
train_dataset=dataset,
|
| 178 |
+
)
|
| 179 |
+
assert type(trainer.model).__name__ == "RemoteForSequenceClassification"
|
| 180 |
+
|
| 181 |
+
@pytest.mark.parametrize(
|
| 182 |
+
"config_name",
|
| 183 |
+
[
|
| 184 |
+
"standard_preference",
|
| 185 |
+
"conversational_preference",
|
| 186 |
+
"standard_implicit_prompt_preference",
|
| 187 |
+
"conversational_implicit_prompt_preference",
|
| 188 |
+
],
|
| 189 |
+
)
|
| 190 |
+
def test_train_dataset_types(self, config_name):
|
| 191 |
+
dataset = load_dataset("trl-internal-testing/zen", config_name, split="train")
|
| 192 |
+
|
| 193 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
|
| 194 |
+
trainer = RewardTrainer(
|
| 195 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 196 |
+
args=training_args,
|
| 197 |
+
train_dataset=dataset,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 201 |
+
|
| 202 |
+
trainer.train()
|
| 203 |
+
|
| 204 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 205 |
+
|
| 206 |
+
# Check that the params have changed
|
| 207 |
+
for n, param in previous_trainable_params.items():
|
| 208 |
+
new_param = trainer.model.get_parameter(n)
|
| 209 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 210 |
+
|
| 211 |
+
def test_train_model(self):
|
| 212 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 213 |
+
"trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 214 |
+
num_labels=1, # required for reward models
|
| 215 |
+
dtype="float32",
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 219 |
+
|
| 220 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
|
| 221 |
+
trainer = RewardTrainer(model=model, args=training_args, train_dataset=dataset)
|
| 222 |
+
|
| 223 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 224 |
+
|
| 225 |
+
trainer.train()
|
| 226 |
+
|
| 227 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 228 |
+
|
| 229 |
+
# Check that the params have changed
|
| 230 |
+
for n, param in previous_trainable_params.items():
|
| 231 |
+
new_param = trainer.model.get_parameter(n)
|
| 232 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 233 |
+
|
| 234 |
+
def test_train_from_sequence_classification_model(self):
|
| 235 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 236 |
+
|
| 237 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
|
| 238 |
+
trainer = RewardTrainer(
|
| 239 |
+
model="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 240 |
+
args=training_args,
|
| 241 |
+
train_dataset=dataset,
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 245 |
+
|
| 246 |
+
trainer.train()
|
| 247 |
+
|
| 248 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 249 |
+
|
| 250 |
+
# Check that the params have changed
|
| 251 |
+
for n, param in previous_trainable_params.items():
|
| 252 |
+
new_param = trainer.model.get_parameter(n)
|
| 253 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 254 |
+
|
| 255 |
+
def test_train_model_dtype(self):
|
| 256 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 257 |
+
|
| 258 |
+
training_args = RewardConfig(
|
| 259 |
+
output_dir=self.tmp_dir,
|
| 260 |
+
model_init_kwargs={"dtype": torch.float16},
|
| 261 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 262 |
+
report_to="none",
|
| 263 |
+
)
|
| 264 |
+
trainer = RewardTrainer(
|
| 265 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 266 |
+
args=training_args,
|
| 267 |
+
train_dataset=dataset,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 271 |
+
|
| 272 |
+
trainer.train()
|
| 273 |
+
|
| 274 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 275 |
+
|
| 276 |
+
# Check that the params have changed
|
| 277 |
+
for n, param in previous_trainable_params.items():
|
| 278 |
+
# For some reasonn model.layers.0.input_layernorm.weight doesn't change in GitHub Actions but does
|
| 279 |
+
# locally. We ignore this parameter for now
|
| 280 |
+
if "layernorm" in n:
|
| 281 |
+
continue
|
| 282 |
+
new_param = trainer.model.get_parameter(n)
|
| 283 |
+
# Check the torch dtype
|
| 284 |
+
assert new_param.dtype == torch.float16
|
| 285 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 286 |
+
|
| 287 |
+
@require_peft
|
| 288 |
+
def test_train_dense_with_peft_config(self):
|
| 289 |
+
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 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(),
|
| 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_moe_with_peft_config(self):
|
| 320 |
+
model_id = "trl-internal-testing/tiny-Qwen3MoeForCausalLM"
|
| 321 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_id, dtype="float32")
|
| 322 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 323 |
+
|
| 324 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 325 |
+
|
| 326 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
|
| 327 |
+
|
| 328 |
+
trainer = RewardTrainer(
|
| 329 |
+
model=model_id,
|
| 330 |
+
args=training_args,
|
| 331 |
+
train_dataset=dataset,
|
| 332 |
+
peft_config=LoraConfig(target_modules=["gate_proj", "up_proj", "down_proj", "score"]),
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 336 |
+
|
| 337 |
+
trainer.train()
|
| 338 |
+
|
| 339 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 340 |
+
|
| 341 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 342 |
+
for n, param in previous_trainable_params.items():
|
| 343 |
+
new_param = trainer.model.get_parameter(n)
|
| 344 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 345 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 346 |
+
elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
|
| 347 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 348 |
+
|
| 349 |
+
@require_peft
|
| 350 |
+
def test_train_peft_model(self):
|
| 351 |
+
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 352 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 353 |
+
model_id,
|
| 354 |
+
num_labels=1, # required for reward models
|
| 355 |
+
dtype="float32",
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 359 |
+
|
| 360 |
+
lora_config = LoraConfig()
|
| 361 |
+
model = get_peft_model(model, lora_config)
|
| 362 |
+
|
| 363 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 364 |
+
|
| 365 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
|
| 366 |
+
trainer = RewardTrainer(model=model, args=training_args, train_dataset=dataset)
|
| 367 |
+
|
| 368 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 369 |
+
|
| 370 |
+
trainer.train()
|
| 371 |
+
|
| 372 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 373 |
+
|
| 374 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 375 |
+
for n, param in previous_trainable_params.items():
|
| 376 |
+
new_param = trainer.model.get_parameter(n)
|
| 377 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 378 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 379 |
+
elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
|
| 380 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 381 |
+
|
| 382 |
+
# In practice, this test is the same as `test_train_dense_with_peft_config`, since gradient checkpointing is
|
| 383 |
+
# enabled by default in `RewardTrainer`. We keep it as a regression guard: if the default ever changes, we still
|
| 384 |
+
# explicitly test PEFT + gradient checkpointing, which has caused issues in the past.
|
| 385 |
+
@require_peft
|
| 386 |
+
def test_train_with_peft_config_and_gradient_checkpointing(self):
|
| 387 |
+
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 388 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_id, dtype="float32")
|
| 389 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 390 |
+
|
| 391 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 392 |
+
|
| 393 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, gradient_checkpointing=True, report_to="none")
|
| 394 |
+
|
| 395 |
+
trainer = RewardTrainer(
|
| 396 |
+
model=model_id,
|
| 397 |
+
args=training_args,
|
| 398 |
+
train_dataset=dataset,
|
| 399 |
+
peft_config=LoraConfig(),
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 403 |
+
|
| 404 |
+
trainer.train()
|
| 405 |
+
|
| 406 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 407 |
+
|
| 408 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 409 |
+
for n, param in previous_trainable_params.items():
|
| 410 |
+
new_param = trainer.model.get_parameter(n)
|
| 411 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 412 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 413 |
+
elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
|
| 414 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 415 |
+
|
| 416 |
+
@pytest.mark.parametrize("use_reentrant", [True, False])
|
| 417 |
+
@require_peft
|
| 418 |
+
def test_train_with_peft_config_and_gradient_checkpointing_reentrant(self, use_reentrant):
|
| 419 |
+
model_id = "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"
|
| 420 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_id, dtype="float32")
|
| 421 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 422 |
+
|
| 423 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 424 |
+
|
| 425 |
+
training_args = RewardConfig(
|
| 426 |
+
output_dir=self.tmp_dir,
|
| 427 |
+
gradient_checkpointing=True,
|
| 428 |
+
gradient_checkpointing_kwargs={"use_reentrant": use_reentrant},
|
| 429 |
+
report_to="none",
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
trainer = RewardTrainer(
|
| 433 |
+
model=model_id,
|
| 434 |
+
args=training_args,
|
| 435 |
+
train_dataset=dataset,
|
| 436 |
+
peft_config=LoraConfig(),
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 440 |
+
|
| 441 |
+
trainer.train()
|
| 442 |
+
|
| 443 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 444 |
+
|
| 445 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 446 |
+
for n, param in previous_trainable_params.items():
|
| 447 |
+
new_param = trainer.model.get_parameter(n)
|
| 448 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 449 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 450 |
+
elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
|
| 451 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 452 |
+
|
| 453 |
+
@pytest.mark.parametrize(
|
| 454 |
+
"chosen_column,rejected_column,expect_deprecation_warning",
|
| 455 |
+
[
|
| 456 |
+
("chosen_ids", "rejected_ids", False),
|
| 457 |
+
("chosen_input_ids", "rejected_input_ids", True),
|
| 458 |
+
],
|
| 459 |
+
)
|
| 460 |
+
def test_train_with_pretokenized_data(self, chosen_column, rejected_column, expect_deprecation_warning):
|
| 461 |
+
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
|
| 462 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 463 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 464 |
+
|
| 465 |
+
def tokenize_example(example):
|
| 466 |
+
return {
|
| 467 |
+
chosen_column: tokenizer(example["chosen"]).input_ids,
|
| 468 |
+
rejected_column: tokenizer(example["rejected"]).input_ids,
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
# Apply tokenization
|
| 472 |
+
tokenized_dataset = dataset.map(tokenize_example, remove_columns=["chosen", "rejected"])
|
| 473 |
+
|
| 474 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
|
| 475 |
+
if expect_deprecation_warning:
|
| 476 |
+
with pytest.warns(FutureWarning, match=r"will not be supported in v1"):
|
| 477 |
+
trainer = RewardTrainer(model=model_id, args=training_args, train_dataset=tokenized_dataset)
|
| 478 |
+
else:
|
| 479 |
+
trainer = RewardTrainer(model=model_id, args=training_args, train_dataset=tokenized_dataset)
|
| 480 |
+
|
| 481 |
+
assert "chosen_ids" in trainer.train_dataset.column_names
|
| 482 |
+
assert "rejected_ids" in trainer.train_dataset.column_names
|
| 483 |
+
assert "chosen_input_ids" not in trainer.train_dataset.column_names
|
| 484 |
+
assert "rejected_input_ids" not in trainer.train_dataset.column_names
|
| 485 |
+
|
| 486 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 487 |
+
|
| 488 |
+
trainer.train()
|
| 489 |
+
|
| 490 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 491 |
+
|
| 492 |
+
# Check that the params have changed
|
| 493 |
+
for n, param in previous_trainable_params.items():
|
| 494 |
+
new_param = trainer.model.get_parameter(n)
|
| 495 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 496 |
+
|
| 497 |
+
def test_train_with_iterable_dataset(self):
|
| 498 |
+
dataset = load_dataset(
|
| 499 |
+
"trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train", streaming=True
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, max_steps=3, report_to="none")
|
| 503 |
+
trainer = RewardTrainer(
|
| 504 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 505 |
+
args=training_args,
|
| 506 |
+
train_dataset=dataset,
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.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 |
+
|
| 520 |
+
def test_train_with_chat_template_kwargs(self):
|
| 521 |
+
dataset = load_dataset("trl-internal-testing/zen", "conversational_implicit_prompt_preference", split="train")
|
| 522 |
+
|
| 523 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
|
| 524 |
+
|
| 525 |
+
tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5")
|
| 526 |
+
# The following template is a simplified version of the Qwen chat template, where an additional argument
|
| 527 |
+
# `role_capital` is used to control the capitalization of roles.
|
| 528 |
+
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 -%}'
|
| 529 |
+
|
| 530 |
+
dataset = dataset.add_column(
|
| 531 |
+
"chat_template_kwargs", [{"role_capital": bool(i % 2)} for i in range(len(dataset))]
|
| 532 |
+
)
|
| 533 |
+
assert "chat_template_kwargs" in dataset.features
|
| 534 |
+
|
| 535 |
+
trainer = RewardTrainer(
|
| 536 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 537 |
+
args=training_args,
|
| 538 |
+
train_dataset=dataset,
|
| 539 |
+
processing_class=tokenizer,
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
assert trainer.processing_class.chat_template == tokenizer.chat_template
|
| 543 |
+
|
| 544 |
+
for i in range(2):
|
| 545 |
+
role = "SYSTEM" if i else "system"
|
| 546 |
+
system_prompt = (
|
| 547 |
+
f"<|im_start|>{role}\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>"
|
| 548 |
+
)
|
| 549 |
+
system_prompt_ids = trainer.processing_class(system_prompt)["input_ids"]
|
| 550 |
+
assert trainer.train_dataset[i]["chosen_ids"][: len(system_prompt_ids)] == system_prompt_ids
|
| 551 |
+
assert trainer.train_dataset[i]["rejected_ids"][: len(system_prompt_ids)] == system_prompt_ids
|
| 552 |
+
|
| 553 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 554 |
+
|
| 555 |
+
trainer.train()
|
| 556 |
+
|
| 557 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 558 |
+
|
| 559 |
+
# Check that the params have changed
|
| 560 |
+
for n, param in previous_trainable_params.items():
|
| 561 |
+
new_param = trainer.model.get_parameter(n)
|
| 562 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 563 |
+
|
| 564 |
+
def test_train_with_set_chat_template_from_model(self):
|
| 565 |
+
dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train")
|
| 566 |
+
|
| 567 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, chat_template_path="Qwen/Qwen3-4B", report_to="none")
|
| 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 |
+
def test_train_with_set_chat_template_from_path(self, lazy_shared_datadir):
|
| 592 |
+
dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train")
|
| 593 |
+
|
| 594 |
+
training_args = RewardConfig(
|
| 595 |
+
output_dir=self.tmp_dir,
|
| 596 |
+
chat_template_path=str(lazy_shared_datadir / "template.jinja"),
|
| 597 |
+
report_to="none",
|
| 598 |
+
)
|
| 599 |
+
# trl-internal-testing/tiny-GPTNeoXForCausalLM doesn't have a chat template set by default
|
| 600 |
+
trainer = RewardTrainer(
|
| 601 |
+
model="trl-internal-testing/tiny-GPTNeoXForCausalLM",
|
| 602 |
+
args=training_args,
|
| 603 |
+
train_dataset=dataset,
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 607 |
+
|
| 608 |
+
trainer.train()
|
| 609 |
+
|
| 610 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 611 |
+
|
| 612 |
+
# Check that the params have changed
|
| 613 |
+
for n, param in previous_trainable_params.items():
|
| 614 |
+
new_param = trainer.model.get_parameter(n)
|
| 615 |
+
# RewardTrainer uses a mean-free loss that cancels uniform shifts in output scores. Since GPT-NeoX models
|
| 616 |
+
# include a final LayerNorm, its bias consistently receives zero gradient and remains unchanged, so we skip
|
| 617 |
+
# this parameter.
|
| 618 |
+
if n == "gpt_neox.final_layer_norm.bias":
|
| 619 |
+
continue
|
| 620 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 621 |
+
|
| 622 |
+
# Check that the template saved in the output directory is the same as the one used for training
|
| 623 |
+
template_path = pathlib.Path(self.tmp_dir) / "checkpoint-9" / "chat_template.jinja"
|
| 624 |
+
assert template_path.exists(), f"Chat template not found at {template_path}"
|
| 625 |
+
|
| 626 |
+
with open(template_path) as f:
|
| 627 |
+
template_content = f.read()
|
| 628 |
+
with open(training_args.chat_template_path) as f:
|
| 629 |
+
original_template_content = f.read()
|
| 630 |
+
assert template_content == original_template_content, "Chat template content does not match the original"
|
| 631 |
+
|
| 632 |
+
def test_train_toolcall_data(self):
|
| 633 |
+
dataset = load_dataset("trl-internal-testing/toolcall", "preference", split="train")
|
| 634 |
+
|
| 635 |
+
training_args = RewardConfig(
|
| 636 |
+
output_dir=self.tmp_dir,
|
| 637 |
+
per_device_train_batch_size=2, # toolcall sequences are longer than standard data, reduce batch size to avoid OOM
|
| 638 |
+
max_length=512, # toolcall sequences are longer than standard data, limit length to avoid OOM
|
| 639 |
+
report_to="none",
|
| 640 |
+
)
|
| 641 |
+
trainer = RewardTrainer(
|
| 642 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 643 |
+
args=training_args,
|
| 644 |
+
train_dataset=dataset,
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 648 |
+
|
| 649 |
+
trainer.train()
|
| 650 |
+
|
| 651 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 652 |
+
|
| 653 |
+
# Check that the params have changed
|
| 654 |
+
for n, param in previous_trainable_params.items():
|
| 655 |
+
new_param = trainer.model.get_parameter(n)
|
| 656 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 657 |
+
|
| 658 |
+
def test_train_toolcall_data_as_json(self):
|
| 659 |
+
# Tabular backends (Arrow/Parquet) can insert `None` for missing keys in nested structures.
|
| 660 |
+
# If `tools` is stored as a list of dicts and examples use different dict schemas, nulls may
|
| 661 |
+
# be introduced and break tool processing. This test ensures we also support `tools` provided
|
| 662 |
+
# as a list of dicts.
|
| 663 |
+
dataset = load_dataset("trl-internal-testing/toolcall", "preference", split="train")
|
| 664 |
+
|
| 665 |
+
def convert_to_json(example):
|
| 666 |
+
return {"tools": json.loads(example["tools"])}
|
| 667 |
+
|
| 668 |
+
dataset = dataset.map(convert_to_json)
|
| 669 |
+
|
| 670 |
+
training_args = RewardConfig(
|
| 671 |
+
output_dir=self.tmp_dir,
|
| 672 |
+
per_device_train_batch_size=2, # toolcall sequences are longer than standard data, reduce batch size to avoid OOM
|
| 673 |
+
max_length=512, # toolcall sequences are longer than standard data, limit length to avoid OOM
|
| 674 |
+
report_to="none",
|
| 675 |
+
)
|
| 676 |
+
trainer = RewardTrainer(
|
| 677 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 678 |
+
args=training_args,
|
| 679 |
+
train_dataset=dataset,
|
| 680 |
+
)
|
| 681 |
+
|
| 682 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 683 |
+
|
| 684 |
+
trainer.train()
|
| 685 |
+
|
| 686 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 687 |
+
|
| 688 |
+
# Check that the params have changed
|
| 689 |
+
for n, param in previous_trainable_params.items():
|
| 690 |
+
new_param = trainer.model.get_parameter(n)
|
| 691 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 692 |
+
|
| 693 |
+
def test_train_with_eval(self):
|
| 694 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference")
|
| 695 |
+
|
| 696 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none")
|
| 697 |
+
trainer = RewardTrainer(
|
| 698 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 699 |
+
args=training_args,
|
| 700 |
+
train_dataset=dataset["train"],
|
| 701 |
+
eval_dataset=dataset["test"],
|
| 702 |
+
)
|
| 703 |
+
|
| 704 |
+
trainer.train()
|
| 705 |
+
|
| 706 |
+
assert trainer.state.log_history[0]["eval_loss"] is not None
|
| 707 |
+
|
| 708 |
+
def test_train_with_multiple_eval_dataset(self):
|
| 709 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference")
|
| 710 |
+
|
| 711 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=3, report_to="none")
|
| 712 |
+
trainer = RewardTrainer(
|
| 713 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 714 |
+
args=training_args,
|
| 715 |
+
train_dataset=dataset["train"],
|
| 716 |
+
eval_dataset={"data1": dataset["test"], "data2": dataset["test"]},
|
| 717 |
+
)
|
| 718 |
+
trainer.train()
|
| 719 |
+
|
| 720 |
+
assert trainer.state.log_history[-3]["eval_data1_loss"] is not None
|
| 721 |
+
assert trainer.state.log_history[-2]["eval_data2_loss"] is not None
|
| 722 |
+
|
| 723 |
+
def test_train_with_compute_metrics(self):
|
| 724 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference")
|
| 725 |
+
|
| 726 |
+
def dummy_compute_metrics(eval_pred):
|
| 727 |
+
return {"my_metric": 0.123}
|
| 728 |
+
|
| 729 |
+
training_args = RewardConfig(
|
| 730 |
+
output_dir=self.tmp_dir,
|
| 731 |
+
eval_strategy="steps",
|
| 732 |
+
eval_steps=3,
|
| 733 |
+
report_to="none",
|
| 734 |
+
)
|
| 735 |
+
trainer = RewardTrainer(
|
| 736 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 737 |
+
args=training_args,
|
| 738 |
+
train_dataset=dataset["train"],
|
| 739 |
+
eval_dataset=dataset["test"],
|
| 740 |
+
compute_metrics=dummy_compute_metrics,
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
trainer.train()
|
| 744 |
+
|
| 745 |
+
assert trainer.state.log_history[-2]["eval_my_metric"] == 0.123
|
| 746 |
+
|
| 747 |
+
# In practice, this test is the same as `test_train`, since gradient checkpointing is enabled by default in
|
| 748 |
+
# `RewardTrainer`. We keep it as a regression guard: if the default ever changes, we still explicitly test gradient
|
| 749 |
+
# checkpointing, which has caused issues in the past.
|
| 750 |
+
def test_train_with_gradient_checkpointing(self):
|
| 751 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 752 |
+
|
| 753 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, gradient_checkpointing=True, report_to="none")
|
| 754 |
+
trainer = RewardTrainer(
|
| 755 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 756 |
+
args=training_args,
|
| 757 |
+
train_dataset=dataset,
|
| 758 |
+
)
|
| 759 |
+
|
| 760 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 761 |
+
|
| 762 |
+
trainer.train()
|
| 763 |
+
|
| 764 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 765 |
+
|
| 766 |
+
# Check that the params have changed
|
| 767 |
+
for n, param in previous_trainable_params.items():
|
| 768 |
+
new_param = trainer.model.get_parameter(n)
|
| 769 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 770 |
+
|
| 771 |
+
@pytest.mark.parametrize("use_reentrant", [True, False])
|
| 772 |
+
def test_train_with_gradient_checkpointing_reentrant(self, use_reentrant):
|
| 773 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 774 |
+
|
| 775 |
+
training_args = RewardConfig(
|
| 776 |
+
output_dir=self.tmp_dir,
|
| 777 |
+
gradient_checkpointing=True,
|
| 778 |
+
gradient_checkpointing_kwargs={"use_reentrant": use_reentrant},
|
| 779 |
+
report_to="none",
|
| 780 |
+
)
|
| 781 |
+
trainer = RewardTrainer(
|
| 782 |
+
model="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 783 |
+
args=training_args,
|
| 784 |
+
train_dataset=dataset,
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 788 |
+
|
| 789 |
+
trainer.train()
|
| 790 |
+
|
| 791 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 792 |
+
|
| 793 |
+
# Check that the params have changed
|
| 794 |
+
for n, param in previous_trainable_params.items():
|
| 795 |
+
new_param = trainer.model.get_parameter(n)
|
| 796 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 797 |
+
|
| 798 |
+
def test_tag_added(self):
|
| 799 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 800 |
+
|
| 801 |
+
trainer = RewardTrainer(
|
| 802 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 803 |
+
train_dataset=dataset,
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
for tag in ["reward-trainer", "trl"]:
|
| 807 |
+
assert tag in trainer.model.model_tags
|
| 808 |
+
|
| 809 |
+
@require_peft
|
| 810 |
+
def test_tag_added_peft(self):
|
| 811 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 812 |
+
|
| 813 |
+
trainer = RewardTrainer(
|
| 814 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 815 |
+
train_dataset=dataset,
|
| 816 |
+
peft_config=LoraConfig(),
|
| 817 |
+
)
|
| 818 |
+
|
| 819 |
+
for tag in ["reward-trainer", "trl"]:
|
| 820 |
+
assert tag in trainer.model.model_tags
|
| 821 |
+
|
| 822 |
+
def test_train_with_margin(self):
|
| 823 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 824 |
+
|
| 825 |
+
def add_margin(example):
|
| 826 |
+
# dummy margin based on the length of the chosen summary
|
| 827 |
+
return {"margin": len(example["chosen"])}
|
| 828 |
+
|
| 829 |
+
dataset = dataset.map(add_margin)
|
| 830 |
+
|
| 831 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, report_to="none")
|
| 832 |
+
trainer = RewardTrainer(
|
| 833 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 834 |
+
args=training_args,
|
| 835 |
+
train_dataset=dataset,
|
| 836 |
+
)
|
| 837 |
+
|
| 838 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 839 |
+
|
| 840 |
+
trainer.train()
|
| 841 |
+
|
| 842 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 843 |
+
|
| 844 |
+
# Check that the params have changed
|
| 845 |
+
for n, param in previous_trainable_params.items():
|
| 846 |
+
new_param = trainer.model.get_parameter(n)
|
| 847 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 848 |
+
|
| 849 |
+
def test_train_with_center_rewards_coefficient(self):
|
| 850 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
|
| 851 |
+
|
| 852 |
+
training_args = RewardConfig(output_dir=self.tmp_dir, center_rewards_coefficient=0.01, report_to="none")
|
| 853 |
+
trainer = RewardTrainer(
|
| 854 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 855 |
+
args=training_args,
|
| 856 |
+
train_dataset=dataset,
|
| 857 |
+
)
|
| 858 |
+
|
| 859 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 860 |
+
|
| 861 |
+
trainer.train()
|
| 862 |
+
|
| 863 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 864 |
+
|
| 865 |
+
# Check that the params have changed
|
| 866 |
+
for n, param in previous_trainable_params.items():
|
| 867 |
+
new_param = trainer.model.get_parameter(n)
|
| 868 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_rewards.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 pickle
|
| 16 |
+
import threading
|
| 17 |
+
|
| 18 |
+
import pytest
|
| 19 |
+
|
| 20 |
+
from trl.rewards import (
|
| 21 |
+
accuracy_reward,
|
| 22 |
+
get_cosine_scaled_reward,
|
| 23 |
+
get_repetition_penalty_reward,
|
| 24 |
+
get_soft_overlong_punishment,
|
| 25 |
+
reasoning_accuracy_reward,
|
| 26 |
+
think_format_reward,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
from .testing_utils import TrlTestCase, require_math_latex
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TestThinkFormatReward(TrlTestCase):
|
| 33 |
+
def test_valid_format(self):
|
| 34 |
+
completions = [
|
| 35 |
+
"<think>This is my reasoning.</think>This is my answer.", # Simple, one-line reasoning
|
| 36 |
+
"<think>\nThis is my reasoning.\n</think>\nThis is my answer.", # Multiline reasoning
|
| 37 |
+
"<think>\nThis is\nmy reasoning.\n</think>\nThis is my answer.", # Multiline reasoning
|
| 38 |
+
"<think>\nThis is <some tag> my reasoning.</think>\nThis is my answer.", # Reasoning including other tags
|
| 39 |
+
"<think></think>\nThis is my answer.", # Empty reasoning
|
| 40 |
+
]
|
| 41 |
+
completions = [[{"content": completion}] for completion in completions]
|
| 42 |
+
expected_rewards = [1.0, 1.0, 1.0, 1.0, 1.0] # All should be valid
|
| 43 |
+
rewards = think_format_reward(completions)
|
| 44 |
+
assert rewards == expected_rewards
|
| 45 |
+
|
| 46 |
+
def test_invalid_format(self):
|
| 47 |
+
completions = [
|
| 48 |
+
"<think>\nThis is my reasoning.\nThis is my answer.", # No closing </think>
|
| 49 |
+
"<think>This is my reasoning.\nThis is my answer.", # No closing </think>
|
| 50 |
+
"This is my reasoning. This is my answer.", # No <think> tags
|
| 51 |
+
"This is my reasoning.\nThis is my answer.", # No <think> tags
|
| 52 |
+
"This is my reasoning.</think>\nThis is my answer.", # No opening <think>
|
| 53 |
+
"This is my reasoning.</think>This is my answer.", # No opening <think>
|
| 54 |
+
"This<think>is my reasoning.</think>\nThis is my answer.", # <think> tag in the middle
|
| 55 |
+
"<think>This is<think>my reasoning.</think></think>This is my answer.", # Nested <think> tags
|
| 56 |
+
"<think>This is</think>\nmy\n<think>reasoning.</think>\nThis is my answer.", # Multiline <think>
|
| 57 |
+
]
|
| 58 |
+
completions = [[{"content": completion}] for completion in completions]
|
| 59 |
+
expected_rewards = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] # All should be invalid
|
| 60 |
+
rewards = think_format_reward(completions)
|
| 61 |
+
assert rewards == expected_rewards
|
| 62 |
+
|
| 63 |
+
def test_mixed_format(self):
|
| 64 |
+
completions = [
|
| 65 |
+
"<think>This is my reasoning.</think>This is my answer.", # Valid
|
| 66 |
+
"<think>\nThis is my reasoning.\n</think>\nThis is my answer.", # Valid
|
| 67 |
+
"<think>This is my reasoning.\nThis is my answer.", # Invalid
|
| 68 |
+
"This is my reasoning. This is my answer.", # Invalid
|
| 69 |
+
]
|
| 70 |
+
completions = [[{"content": completion}] for completion in completions]
|
| 71 |
+
expected_rewards = [1.0, 1.0, 0.0, 0.0]
|
| 72 |
+
rewards = think_format_reward(completions)
|
| 73 |
+
assert rewards == expected_rewards
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class TestSoftOverlongPunishmentReward:
|
| 77 |
+
def test_soft_overlong_punishment_short_completion(self):
|
| 78 |
+
"""Test soft overlong punishment reward function with a short completion."""
|
| 79 |
+
# length 50, with max=100 and soft cache=20, reward should be 0.
|
| 80 |
+
reward_fn = get_soft_overlong_punishment(max_completion_len=100, soft_punish_cache=20)
|
| 81 |
+
completion_ids = [[1] * 50] # 50 <= 80
|
| 82 |
+
rewards = reward_fn(completion_ids=completion_ids)
|
| 83 |
+
assert rewards == [0]
|
| 84 |
+
|
| 85 |
+
def test_soft_overlong_punishment_long_completion(self):
|
| 86 |
+
"""Test soft overlong punishment reward function with a longer than max completion."""
|
| 87 |
+
# 110 > 100, reward should be -1.
|
| 88 |
+
reward_fn = get_soft_overlong_punishment(max_completion_len=100, soft_punish_cache=20)
|
| 89 |
+
completion_ids = [[1] * 110]
|
| 90 |
+
rewards = reward_fn(completion_ids)
|
| 91 |
+
assert rewards == [-1]
|
| 92 |
+
|
| 93 |
+
def test_soft_overlong_punishment_intermediate_completion(self):
|
| 94 |
+
"""Test soft overlong punishment reward function for intermediate length completion."""
|
| 95 |
+
reward_fn = get_soft_overlong_punishment(max_completion_len=100, soft_punish_cache=20)
|
| 96 |
+
completion_ids = [[1] * 90] # 90 is between 80 and 100
|
| 97 |
+
rewards = reward_fn(completion_ids)
|
| 98 |
+
assert round(abs(rewards[0] - -0.5), 4) == 0
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class TestRepetitionPenaltyReward:
|
| 102 |
+
def test_no_repetition_yields_zero(self):
|
| 103 |
+
"""A completion with only unique n-grams gets no penalty."""
|
| 104 |
+
reward_fn = get_repetition_penalty_reward(ngram_size=2, max_penalty=-1.0)
|
| 105 |
+
completion_ids = [[1, 2, 3, 4]]
|
| 106 |
+
assert reward_fn(completion_ids) == [0.0]
|
| 107 |
+
|
| 108 |
+
def test_full_repetition_approaches_max_penalty(self):
|
| 109 |
+
"""A fully repetitive completion approaches max_penalty."""
|
| 110 |
+
reward_fn = get_repetition_penalty_reward(ngram_size=2, max_penalty=-1.0)
|
| 111 |
+
# [5, 5, 5, 5, 5] -> 4 bigrams, 1 unique -> scaling = 1 - 1/4 = 0.75
|
| 112 |
+
completion_ids = [[5, 5, 5, 5, 5]]
|
| 113 |
+
assert reward_fn(completion_ids) == [pytest.approx(-0.75)]
|
| 114 |
+
|
| 115 |
+
def test_partial_repetition(self):
|
| 116 |
+
reward_fn = get_repetition_penalty_reward(ngram_size=2, max_penalty=-1.0)
|
| 117 |
+
# [1, 2, 1, 2, 1, 2] -> 5 bigrams, 2 unique -> scaling = 1 - 2/5 = 0.6
|
| 118 |
+
completion_ids = [[1, 2, 1, 2, 1, 2]]
|
| 119 |
+
assert reward_fn(completion_ids) == [pytest.approx(-0.6)]
|
| 120 |
+
|
| 121 |
+
def test_completion_shorter_than_ngram_size_yields_zero(self):
|
| 122 |
+
reward_fn = get_repetition_penalty_reward(ngram_size=3, max_penalty=-1.0)
|
| 123 |
+
completion_ids = [[1, 2]] # 2 tokens < ngram_size
|
| 124 |
+
assert reward_fn(completion_ids) == [0.0]
|
| 125 |
+
|
| 126 |
+
def test_completion_exactly_ngram_size_yields_zero(self):
|
| 127 |
+
reward_fn = get_repetition_penalty_reward(ngram_size=3, max_penalty=-1.0)
|
| 128 |
+
completion_ids = [[1, 2, 3]] # a single, unique n-gram
|
| 129 |
+
assert reward_fn(completion_ids) == [0.0]
|
| 130 |
+
|
| 131 |
+
def test_empty_completion_yields_zero(self):
|
| 132 |
+
reward_fn = get_repetition_penalty_reward(ngram_size=3, max_penalty=-1.0)
|
| 133 |
+
completion_ids = [[]]
|
| 134 |
+
assert reward_fn(completion_ids) == [0.0]
|
| 135 |
+
|
| 136 |
+
def test_max_penalty_scales_reward(self):
|
| 137 |
+
reward_fn = get_repetition_penalty_reward(ngram_size=2, max_penalty=-0.5)
|
| 138 |
+
# scaling 0.75 * max_penalty -0.5 = -0.375
|
| 139 |
+
completion_ids = [[5, 5, 5, 5, 5]]
|
| 140 |
+
assert reward_fn(completion_ids) == [pytest.approx(-0.375)]
|
| 141 |
+
|
| 142 |
+
def test_ngram_size_changes_reward(self):
|
| 143 |
+
completion_ids = [[1, 2, 3, 1, 2, 3]]
|
| 144 |
+
# bigrams: 5 total, 3 unique -> 1 - 3/5 = 0.4
|
| 145 |
+
reward_bigram = get_repetition_penalty_reward(ngram_size=2, max_penalty=-1.0)
|
| 146 |
+
assert reward_bigram(completion_ids) == [pytest.approx(-0.4)]
|
| 147 |
+
# trigrams: 4 total, 3 unique -> 1 - 3/4 = 0.25
|
| 148 |
+
reward_trigram = get_repetition_penalty_reward(ngram_size=3, max_penalty=-1.0)
|
| 149 |
+
assert reward_trigram(completion_ids) == [pytest.approx(-0.25)]
|
| 150 |
+
|
| 151 |
+
def test_batch_of_completions(self):
|
| 152 |
+
reward_fn = get_repetition_penalty_reward(ngram_size=2, max_penalty=-1.0)
|
| 153 |
+
completion_ids = [
|
| 154 |
+
[1, 2, 3, 4], # no repetition
|
| 155 |
+
[5, 5, 5, 5, 5], # full repetition
|
| 156 |
+
[9], # shorter than ngram_size
|
| 157 |
+
]
|
| 158 |
+
assert reward_fn(completion_ids) == [pytest.approx(0.0), pytest.approx(-0.75), pytest.approx(0.0)]
|
| 159 |
+
|
| 160 |
+
def test_positive_max_penalty_raises(self):
|
| 161 |
+
with pytest.raises(ValueError):
|
| 162 |
+
get_repetition_penalty_reward(ngram_size=2, max_penalty=0.5)
|
| 163 |
+
|
| 164 |
+
def test_extra_kwargs_are_ignored(self):
|
| 165 |
+
"""Trainers pass prompts/completions/etc. as kwargs; the reward must accept and ignore them."""
|
| 166 |
+
reward_fn = get_repetition_penalty_reward(ngram_size=2, max_penalty=-1.0)
|
| 167 |
+
completion_ids = [[5, 5, 5, 5, 5]]
|
| 168 |
+
rewards = reward_fn(completion_ids, prompts=["x"], completions=[[{"content": "5 5 5 5 5"}]])
|
| 169 |
+
assert rewards == [pytest.approx(-0.75)]
|
| 170 |
+
|
| 171 |
+
def test_reward_is_picklable(self):
|
| 172 |
+
"""The reward must survive pickling for the async GRPO rollout worker."""
|
| 173 |
+
reward_fn = get_repetition_penalty_reward(ngram_size=2, max_penalty=-1.0)
|
| 174 |
+
unpickled = pickle.loads(pickle.dumps(reward_fn))
|
| 175 |
+
completion_ids = [[5, 5, 5, 5, 5]]
|
| 176 |
+
assert unpickled(completion_ids) == [pytest.approx(-0.75)]
|
| 177 |
+
assert unpickled.__name__ == "repetition_penalty_reward"
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class TestAccuracyReward:
|
| 181 |
+
@require_math_latex
|
| 182 |
+
def test_accuracy_reward_correct_answer(self):
|
| 183 |
+
"""Test accuracy_reward with a correct answer."""
|
| 184 |
+
completion = [[{"content": r"\boxed{\frac{63}{400}}"}], [{"content": r"\boxed{\frac{63}{400}}"}]]
|
| 185 |
+
solution = [r"\frac{63}{400}", "63/400"]
|
| 186 |
+
rewards = accuracy_reward(completion, solution)
|
| 187 |
+
assert rewards[0] == 1.0
|
| 188 |
+
assert rewards[1] == 1.0
|
| 189 |
+
|
| 190 |
+
@require_math_latex
|
| 191 |
+
def test_accuracy_reward_wrong_answer(self):
|
| 192 |
+
"""Test accuracy_reward with an incorrect answer."""
|
| 193 |
+
completion = [[{"content": r"\boxed{\frac{64}{400}}"}]]
|
| 194 |
+
solution = [r"\frac{63}{400}"]
|
| 195 |
+
rewards = accuracy_reward(completion, solution)
|
| 196 |
+
assert rewards[0] == 0.0
|
| 197 |
+
|
| 198 |
+
@require_math_latex
|
| 199 |
+
def test_accuracy_reward_wrong_answer_no_latex(self):
|
| 200 |
+
"""Test accuracy_reward with an incorrect answer and gold solution with no latex."""
|
| 201 |
+
completion = [[{"content": r"\boxed{3}"}]]
|
| 202 |
+
solution = ["6"]
|
| 203 |
+
rewards = accuracy_reward(completion, solution)
|
| 204 |
+
assert rewards[0] == 0.0
|
| 205 |
+
|
| 206 |
+
@require_math_latex
|
| 207 |
+
def test_accuracy_reward_unparsable_gold(self):
|
| 208 |
+
"""Test accuracy_reward with an unparsable gold solution."""
|
| 209 |
+
completion = [
|
| 210 |
+
[{"content": "Answer is forty two."}],
|
| 211 |
+
[{"content": r"Some other content. \boxed{43}."}],
|
| 212 |
+
]
|
| 213 |
+
solution = [
|
| 214 |
+
"Answer is forty two.",
|
| 215 |
+
"Answer is forty three.",
|
| 216 |
+
]
|
| 217 |
+
rewards = accuracy_reward(completion, solution)
|
| 218 |
+
assert rewards[0] is None
|
| 219 |
+
assert rewards[1] is None
|
| 220 |
+
|
| 221 |
+
@require_math_latex
|
| 222 |
+
def test_accuracy_reward_in_worker_thread(self):
|
| 223 |
+
"""Test that accuracy_reward works when called from a non-main thread."""
|
| 224 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}]]
|
| 225 |
+
solutions = [r"\frac{1}{3}"]
|
| 226 |
+
results = []
|
| 227 |
+
exceptions = []
|
| 228 |
+
|
| 229 |
+
def target():
|
| 230 |
+
try:
|
| 231 |
+
results.extend(accuracy_reward(completions, solutions))
|
| 232 |
+
except Exception as e:
|
| 233 |
+
exceptions.append(e)
|
| 234 |
+
|
| 235 |
+
t = threading.Thread(target=target)
|
| 236 |
+
t.start()
|
| 237 |
+
t.join()
|
| 238 |
+
|
| 239 |
+
assert not exceptions, f"accuracy_reward raised in worker thread: {exceptions[0]}"
|
| 240 |
+
assert results == [1.0]
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class TestReasoningAccuracyReward:
|
| 244 |
+
@require_math_latex
|
| 245 |
+
def test_correct_answer_yields_unit_reward(self):
|
| 246 |
+
completions = [
|
| 247 |
+
[{"content": r"<think> Reasoning content </think> \boxed{\frac{63}{400}}"}],
|
| 248 |
+
[{"content": r"Reasoning content </think> \boxed{\frac{63}{400}}"}],
|
| 249 |
+
]
|
| 250 |
+
solutions = [r"\frac{63}{400}", r"\frac{63}{400}"]
|
| 251 |
+
rewards = reasoning_accuracy_reward(completions, solutions)
|
| 252 |
+
assert rewards[0] == 1.0
|
| 253 |
+
assert rewards[1] == 1.0
|
| 254 |
+
|
| 255 |
+
@require_math_latex
|
| 256 |
+
def test_correct_answer_with_custom_tags_yields_unit_reward(self):
|
| 257 |
+
completions = [
|
| 258 |
+
[{"content": r"<REASONING_START> Reasoning content </REASONING_END> \boxed{\frac{63}{400}}"}],
|
| 259 |
+
]
|
| 260 |
+
solutions = [
|
| 261 |
+
r"\frac{63}{400}",
|
| 262 |
+
]
|
| 263 |
+
rewards = reasoning_accuracy_reward(completions, solutions, reasoning_delimiters=["</REASONING_END>"])
|
| 264 |
+
assert rewards[0] == 1.0
|
| 265 |
+
|
| 266 |
+
@require_math_latex
|
| 267 |
+
def test_incorrect_answer_yields_zero_reward(self):
|
| 268 |
+
completion = [[{"content": r"<think> Reasoning content </think> \boxed{\frac{64}{400}}"}]]
|
| 269 |
+
solution = [r"\frac{63}{400}"]
|
| 270 |
+
rewards = reasoning_accuracy_reward(completion, solution)
|
| 271 |
+
assert rewards[0] == 0.0
|
| 272 |
+
|
| 273 |
+
@require_math_latex
|
| 274 |
+
def test_correct_answer_in_reasoning_yields_zero_reward(self):
|
| 275 |
+
completions = [
|
| 276 |
+
[{"content": r"<think> My answer is \boxed{42} </think> Some other text."}],
|
| 277 |
+
[{"content": r"<think> The answer is \boxed{42} </think> Here's a wrong answer: \boxed{43}."}],
|
| 278 |
+
]
|
| 279 |
+
solutions = [r"\boxed{42}", r"\boxed{42}"]
|
| 280 |
+
rewards = reasoning_accuracy_reward(completions, solutions)
|
| 281 |
+
assert rewards[0] == 0.0
|
| 282 |
+
assert rewards[1] == 0.0
|
| 283 |
+
|
| 284 |
+
@require_math_latex
|
| 285 |
+
def test_incomplete_reasoning_yields_zero_reward(self):
|
| 286 |
+
completions = [
|
| 287 |
+
[{"content": r"<think> Incomplete reasoning without closing tag"}],
|
| 288 |
+
[{"content": r"Correct answer \frac{63}{400} but completely missing reasoning content"}],
|
| 289 |
+
]
|
| 290 |
+
solutions = [r"\frac{63}{400}", r"\frac{63}{400}"]
|
| 291 |
+
rewards = reasoning_accuracy_reward(completions, solutions)
|
| 292 |
+
assert rewards[0] == 0.0
|
| 293 |
+
assert rewards[1] == 0.0
|
| 294 |
+
|
| 295 |
+
@require_math_latex
|
| 296 |
+
def test_unparsable_gold_solution_yields_none_reward(self):
|
| 297 |
+
completions = [
|
| 298 |
+
[{"content": r"<think> Reasoning content </think> \boxed{42}"}],
|
| 299 |
+
]
|
| 300 |
+
solutions = [
|
| 301 |
+
"forty two",
|
| 302 |
+
]
|
| 303 |
+
rewards = reasoning_accuracy_reward(completions, solutions)
|
| 304 |
+
assert rewards[0] is None
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
class TestCosineScaledReward:
|
| 308 |
+
@require_math_latex
|
| 309 |
+
def test_correct_shorter_rewarded_more(self):
|
| 310 |
+
"""For correct completions, a shorter one gets a higher reward."""
|
| 311 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 312 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}], [{"content": r"\boxed{\frac{1}{3}}"}]]
|
| 313 |
+
solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
|
| 314 |
+
completion_ids = [[1] * 25, [1] * 75]
|
| 315 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 316 |
+
assert rewards[0] > rewards[1]
|
| 317 |
+
assert rewards == [pytest.approx(0.92678, abs=1e-4), pytest.approx(0.57322, abs=1e-4)]
|
| 318 |
+
|
| 319 |
+
@require_math_latex
|
| 320 |
+
def test_wrong_longer_penalized_less(self):
|
| 321 |
+
"""For wrong completions, a longer one is penalized less (closer to zero)."""
|
| 322 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 323 |
+
completions = [[{"content": r"\boxed{\frac{1}{2}}"}], [{"content": r"\boxed{\frac{1}{2}}"}]]
|
| 324 |
+
solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
|
| 325 |
+
completion_ids = [[1] * 25, [1] * 75]
|
| 326 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 327 |
+
assert rewards[1] > rewards[0]
|
| 328 |
+
assert rewards == [pytest.approx(-0.92678, abs=1e-4), pytest.approx(-0.57322, abs=1e-4)]
|
| 329 |
+
|
| 330 |
+
@require_math_latex
|
| 331 |
+
def test_midpoint_values(self):
|
| 332 |
+
"""At half of max_len (cosine = 0), correct -> 0.75 and wrong -> -0.75 with default bounds."""
|
| 333 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 334 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}], [{"content": r"\boxed{\frac{1}{2}}"}]]
|
| 335 |
+
solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
|
| 336 |
+
completion_ids = [[1] * 50, [1] * 50]
|
| 337 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 338 |
+
assert rewards == [pytest.approx(0.75), pytest.approx(-0.75)]
|
| 339 |
+
|
| 340 |
+
@require_math_latex
|
| 341 |
+
def test_correct_boundary_values(self):
|
| 342 |
+
"""Correct: shortest -> max_value_correct (1.0), longest -> min_value_correct (0.5)."""
|
| 343 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 344 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}], [{"content": r"\boxed{\frac{1}{3}}"}]]
|
| 345 |
+
solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
|
| 346 |
+
completion_ids = [[], [1] * 100]
|
| 347 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 348 |
+
assert rewards == [pytest.approx(1.0), pytest.approx(0.5)]
|
| 349 |
+
|
| 350 |
+
@require_math_latex
|
| 351 |
+
def test_wrong_boundary_values(self):
|
| 352 |
+
"""Wrong: shortest -> min_value_wrong (-1.0), longest -> max_value_wrong (-0.5)."""
|
| 353 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 354 |
+
completions = [[{"content": r"\boxed{\frac{1}{2}}"}], [{"content": r"\boxed{\frac{1}{2}}"}]]
|
| 355 |
+
solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
|
| 356 |
+
completion_ids = [[], [1] * 100]
|
| 357 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 358 |
+
assert rewards == [pytest.approx(-1.0), pytest.approx(-0.5)]
|
| 359 |
+
|
| 360 |
+
@require_math_latex
|
| 361 |
+
def test_length_exceeding_max_len_is_clamped(self):
|
| 362 |
+
"""Completions longer than max_len stay at the long-length bound (no climb back up past max_len)."""
|
| 363 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 364 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}], [{"content": r"\boxed{\frac{1}{2}}"}]]
|
| 365 |
+
solution = [r"\frac{1}{3}", r"\frac{1}{3}"]
|
| 366 |
+
completion_ids = [[1] * 200, [1] * 200] # both 2x max_len
|
| 367 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 368 |
+
# correct -> min_value_correct (0.5), wrong -> max_value_wrong (-0.5); same as at exactly max_len
|
| 369 |
+
assert rewards == [pytest.approx(0.5), pytest.approx(-0.5)]
|
| 370 |
+
|
| 371 |
+
@require_math_latex
|
| 372 |
+
def test_unparsable_gold_yields_none(self):
|
| 373 |
+
"""An unparseable gold solution is skipped, as in accuracy_reward."""
|
| 374 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 375 |
+
completions = [[{"content": r"\boxed{42}"}]]
|
| 376 |
+
solution = ["forty two"]
|
| 377 |
+
completion_ids = [[1] * 50]
|
| 378 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 379 |
+
assert rewards == [None]
|
| 380 |
+
|
| 381 |
+
@require_math_latex
|
| 382 |
+
def test_custom_value_bounds(self):
|
| 383 |
+
reward_fn = get_cosine_scaled_reward(max_len=100, min_value_correct=0.0, max_value_correct=2.0)
|
| 384 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}]]
|
| 385 |
+
solution = [r"\frac{1}{3}"]
|
| 386 |
+
completion_ids = [[1] * 50] # progress 0.5, cosine 0 -> 0.0 + 0.5 * (2.0 - 0.0) * 1 = 1.0
|
| 387 |
+
rewards = reward_fn(completions, solution, completion_ids)
|
| 388 |
+
assert rewards == [pytest.approx(1.0)]
|
| 389 |
+
|
| 390 |
+
@require_math_latex
|
| 391 |
+
def test_reward_is_picklable(self):
|
| 392 |
+
"""The reward must survive pickling for the async GRPO rollout worker."""
|
| 393 |
+
reward_fn = get_cosine_scaled_reward(max_len=100)
|
| 394 |
+
unpickled = pickle.loads(pickle.dumps(reward_fn))
|
| 395 |
+
completions = [[{"content": r"\boxed{\frac{1}{3}}"}]]
|
| 396 |
+
solution = [r"\frac{1}{3}"]
|
| 397 |
+
completion_ids = [[1] * 50]
|
| 398 |
+
assert unpickled(completions, solution, completion_ids) == [pytest.approx(0.75)]
|
| 399 |
+
assert unpickled.__name__ == "cosine_scaled_reward"
|
tasks/tasksmith-b71e9e0a47b6/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 |
+
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# MoE models log the load-balancing auxiliary loss (on by default)
|
| 97 |
+
if trainer.aux_loss_enabled:
|
| 98 |
+
assert trainer.state.log_history[-1]["aux_loss"] is not None
|
| 99 |
+
|
| 100 |
+
# Check that the params have changed
|
| 101 |
+
for n, param in previous_trainable_params.items():
|
| 102 |
+
new_param = trainer.model.get_parameter(n)
|
| 103 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 104 |
+
|
| 105 |
+
@pytest.mark.parametrize("config_name", ["standard_prompt_only", "conversational_prompt_only"])
|
| 106 |
+
def test_train_dataset_format(self, config_name):
|
| 107 |
+
dataset = load_dataset("trl-internal-testing/zen", config_name, split="train")
|
| 108 |
+
|
| 109 |
+
training_args = RLOOConfig(
|
| 110 |
+
output_dir=self.tmp_dir,
|
| 111 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 112 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 113 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 114 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 115 |
+
report_to="none",
|
| 116 |
+
)
|
| 117 |
+
trainer = RLOOTrainer(
|
| 118 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 119 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 120 |
+
args=training_args,
|
| 121 |
+
train_dataset=dataset,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 125 |
+
|
| 126 |
+
trainer.train()
|
| 127 |
+
|
| 128 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 129 |
+
|
| 130 |
+
# Check that the params have changed
|
| 131 |
+
for n, param in previous_trainable_params.items():
|
| 132 |
+
new_param = trainer.model.get_parameter(n)
|
| 133 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 134 |
+
|
| 135 |
+
def test_trust_remote_code(self):
|
| 136 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 137 |
+
model_id = "trl-internal-testing/tiny-RemoteForCausalLM"
|
| 138 |
+
|
| 139 |
+
def reward_func(completions, **kwargs):
|
| 140 |
+
return [0.0] * len(completions)
|
| 141 |
+
|
| 142 |
+
with pytest.raises(ValueError, match="custom code"):
|
| 143 |
+
RLOOTrainer(
|
| 144 |
+
model=model_id,
|
| 145 |
+
args=RLOOConfig(output_dir=self.tmp_dir, report_to="none"),
|
| 146 |
+
reward_funcs=reward_func,
|
| 147 |
+
train_dataset=dataset,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
trainer = RLOOTrainer(
|
| 151 |
+
model=model_id,
|
| 152 |
+
args=RLOOConfig(output_dir=self.tmp_dir, report_to="none", trust_remote_code=True),
|
| 153 |
+
reward_funcs=reward_func,
|
| 154 |
+
train_dataset=dataset,
|
| 155 |
+
)
|
| 156 |
+
assert type(trainer.model).__name__ == "RemoteForCausalLM"
|
| 157 |
+
|
| 158 |
+
def test_train_with_eval(self):
|
| 159 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only")
|
| 160 |
+
|
| 161 |
+
training_args = RLOOConfig(
|
| 162 |
+
output_dir=self.tmp_dir,
|
| 163 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 164 |
+
per_device_eval_batch_size=3, # reduce the batch size to reduce memory usage
|
| 165 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 166 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 167 |
+
eval_strategy="steps",
|
| 168 |
+
eval_steps=2,
|
| 169 |
+
report_to="none",
|
| 170 |
+
)
|
| 171 |
+
trainer = RLOOTrainer(
|
| 172 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 173 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 174 |
+
args=training_args,
|
| 175 |
+
train_dataset=dataset["train"],
|
| 176 |
+
eval_dataset=dataset["test"],
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
trainer.train()
|
| 180 |
+
|
| 181 |
+
def test_train_with_num_generations_eval(self):
|
| 182 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only")
|
| 183 |
+
|
| 184 |
+
training_args = RLOOConfig(
|
| 185 |
+
output_dir=self.tmp_dir,
|
| 186 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 187 |
+
per_device_eval_batch_size=3, # reduce the batch size to reduce memory usage
|
| 188 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 189 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 190 |
+
num_generations_eval=1,
|
| 191 |
+
eval_strategy="steps",
|
| 192 |
+
eval_steps=2,
|
| 193 |
+
report_to="none",
|
| 194 |
+
)
|
| 195 |
+
trainer = RLOOTrainer(
|
| 196 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 197 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 198 |
+
args=training_args,
|
| 199 |
+
train_dataset=dataset["train"],
|
| 200 |
+
eval_dataset=dataset["test"],
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
trainer.train()
|
| 204 |
+
|
| 205 |
+
def test_train_multiple_iterations(self):
|
| 206 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 207 |
+
|
| 208 |
+
training_args = RLOOConfig(
|
| 209 |
+
output_dir=self.tmp_dir,
|
| 210 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 211 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 212 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 213 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 214 |
+
num_iterations=2,
|
| 215 |
+
report_to="none",
|
| 216 |
+
)
|
| 217 |
+
trainer = RLOOTrainer(
|
| 218 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 219 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 220 |
+
args=training_args,
|
| 221 |
+
train_dataset=dataset,
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 225 |
+
|
| 226 |
+
trainer.train()
|
| 227 |
+
|
| 228 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 229 |
+
|
| 230 |
+
# Check that the params have changed
|
| 231 |
+
for n, param in previous_trainable_params.items():
|
| 232 |
+
new_param = trainer.model.get_parameter(n)
|
| 233 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 234 |
+
|
| 235 |
+
@require_peft
|
| 236 |
+
def test_train_peft_config(self):
|
| 237 |
+
model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32")
|
| 238 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 239 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 240 |
+
|
| 241 |
+
training_args = RLOOConfig(
|
| 242 |
+
output_dir=self.tmp_dir,
|
| 243 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 244 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 245 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 246 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 247 |
+
report_to="none",
|
| 248 |
+
)
|
| 249 |
+
trainer = RLOOTrainer(
|
| 250 |
+
model=model,
|
| 251 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 252 |
+
args=training_args,
|
| 253 |
+
train_dataset=dataset,
|
| 254 |
+
peft_config=LoraConfig(),
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 258 |
+
|
| 259 |
+
trainer.train()
|
| 260 |
+
|
| 261 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 262 |
+
|
| 263 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 264 |
+
for n, param in previous_trainable_params.items():
|
| 265 |
+
new_param = trainer.model.get_parameter(n)
|
| 266 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 267 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 268 |
+
elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
|
| 269 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 270 |
+
|
| 271 |
+
@require_peft
|
| 272 |
+
def test_train_peft_model(self):
|
| 273 |
+
model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32")
|
| 274 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 275 |
+
lora_config = LoraConfig()
|
| 276 |
+
model = get_peft_model(model, lora_config)
|
| 277 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 278 |
+
|
| 279 |
+
training_args = RLOOConfig(
|
| 280 |
+
output_dir=self.tmp_dir,
|
| 281 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 282 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 283 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 284 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 285 |
+
report_to="none",
|
| 286 |
+
)
|
| 287 |
+
trainer = RLOOTrainer(
|
| 288 |
+
model=model,
|
| 289 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 290 |
+
args=training_args,
|
| 291 |
+
train_dataset=dataset,
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 295 |
+
|
| 296 |
+
trainer.train()
|
| 297 |
+
|
| 298 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 299 |
+
|
| 300 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 301 |
+
for n, param in previous_trainable_params.items():
|
| 302 |
+
new_param = trainer.model.get_parameter(n)
|
| 303 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 304 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 305 |
+
elif "base_layer" not in n and "ref" not in n: # and the peft params to be different (except base and ref)
|
| 306 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 307 |
+
|
| 308 |
+
@require_peft
|
| 309 |
+
def test_train_moe_peft_model(self):
|
| 310 |
+
# Regression test for https://github.com/huggingface/trl/issues/5222. PEFT only supports one adapter per model
|
| 311 |
+
# when the LoRA config uses `target_parameters` (see peft#3340), so no "ref" adapter can be created and the
|
| 312 |
+
# reference log probs are computed with adapters disabled instead.
|
| 313 |
+
model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM", dtype="float32")
|
| 314 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 315 |
+
lora_config = LoraConfig(target_parameters=["mlp.experts.down_proj", "mlp.experts.gate_up_proj"])
|
| 316 |
+
model = get_peft_model(model, lora_config)
|
| 317 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 318 |
+
|
| 319 |
+
training_args = RLOOConfig(
|
| 320 |
+
output_dir=self.tmp_dir,
|
| 321 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 322 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 323 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 324 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 325 |
+
report_to="none",
|
| 326 |
+
)
|
| 327 |
+
trainer = RLOOTrainer(
|
| 328 |
+
model=model,
|
| 329 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 330 |
+
args=training_args,
|
| 331 |
+
train_dataset=dataset,
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
assert "ref" not in trainer.model.peft_config
|
| 335 |
+
|
| 336 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 337 |
+
|
| 338 |
+
trainer.train()
|
| 339 |
+
|
| 340 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 341 |
+
|
| 342 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 343 |
+
for n, param in previous_trainable_params.items():
|
| 344 |
+
new_param = trainer.model.get_parameter(n)
|
| 345 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 346 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 347 |
+
elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
|
| 348 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 349 |
+
|
| 350 |
+
# In practice, this test is the same as `test_train_peft_config`, since gradient checkpointing is enabled by
|
| 351 |
+
# default in `RLOOTrainer`. We keep it as a regression guard: if the default ever changes, we still explicitly test
|
| 352 |
+
# PEFT + gradient checkpointing, which has caused issues in the past.
|
| 353 |
+
@require_peft
|
| 354 |
+
def test_train_peft_with_gradient_checkpointing(self):
|
| 355 |
+
model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", dtype="float32")
|
| 356 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 357 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 358 |
+
|
| 359 |
+
training_args = RLOOConfig(
|
| 360 |
+
output_dir=self.tmp_dir,
|
| 361 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 362 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 363 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 364 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 365 |
+
gradient_checkpointing=True, # enable gradient checkpointing
|
| 366 |
+
report_to="none",
|
| 367 |
+
)
|
| 368 |
+
trainer = RLOOTrainer(
|
| 369 |
+
model=model,
|
| 370 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 371 |
+
args=training_args,
|
| 372 |
+
train_dataset=dataset,
|
| 373 |
+
peft_config=LoraConfig(),
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 377 |
+
|
| 378 |
+
trainer.train()
|
| 379 |
+
|
| 380 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 381 |
+
|
| 382 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 383 |
+
for n, param in previous_trainable_params.items():
|
| 384 |
+
new_param = trainer.model.get_parameter(n)
|
| 385 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 386 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 387 |
+
elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
|
| 388 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 389 |
+
|
| 390 |
+
def test_train_different_reward_model(self):
|
| 391 |
+
# Use a reward model different from the model: different chat template, tokenization, etc.
|
| 392 |
+
dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train")
|
| 393 |
+
reward_model_id = "trl-internal-testing/tiny-LlamaForSequenceClassification-3.2"
|
| 394 |
+
reward_model = AutoModelForSequenceClassification.from_pretrained(reward_model_id)
|
| 395 |
+
reward_tokenizer = AutoTokenizer.from_pretrained(reward_model_id)
|
| 396 |
+
# By default, the trainer uses the eos token as the padding token. However, for Llama models, the eos token
|
| 397 |
+
# appears in the chat template. Using it as a pad token disrupts the reward calculation, as the calculation
|
| 398 |
+
# considers the score of the last token before the first pad token. To ensure correct reward calculations,
|
| 399 |
+
# we use a separate pad token instead.
|
| 400 |
+
reward_tokenizer.pad_token = "<|finetune_right_pad_id|>"
|
| 401 |
+
|
| 402 |
+
training_args = RLOOConfig(
|
| 403 |
+
output_dir=self.tmp_dir,
|
| 404 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 405 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 406 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 407 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 408 |
+
report_to="none",
|
| 409 |
+
)
|
| 410 |
+
trainer = RLOOTrainer(
|
| 411 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 412 |
+
reward_funcs=reward_model,
|
| 413 |
+
args=training_args,
|
| 414 |
+
train_dataset=dataset,
|
| 415 |
+
reward_processing_classes=reward_tokenizer,
|
| 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_reward_func_standard(self):
|
| 430 |
+
# Test if trainer can handle reward function with standard format
|
| 431 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 432 |
+
|
| 433 |
+
def reward_func(completions, **kwargs):
|
| 434 |
+
"""Reward function that rewards longer completions."""
|
| 435 |
+
return [float(len(completion)) for completion in completions]
|
| 436 |
+
|
| 437 |
+
training_args = RLOOConfig(
|
| 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 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 441 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 442 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 443 |
+
report_to="none",
|
| 444 |
+
)
|
| 445 |
+
trainer = RLOOTrainer(
|
| 446 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 447 |
+
reward_funcs=reward_func,
|
| 448 |
+
args=training_args,
|
| 449 |
+
train_dataset=dataset,
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 453 |
+
|
| 454 |
+
trainer.train()
|
| 455 |
+
|
| 456 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 457 |
+
|
| 458 |
+
# Check that the params have changed
|
| 459 |
+
for n, param in previous_trainable_params.items():
|
| 460 |
+
new_param = trainer.model.get_parameter(n)
|
| 461 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 462 |
+
|
| 463 |
+
def test_train_reward_func_conversational(self):
|
| 464 |
+
# Test if trainer can handle reward function with conversational format
|
| 465 |
+
dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train")
|
| 466 |
+
|
| 467 |
+
def reward_func(completions, **kwargs):
|
| 468 |
+
"""Reward function that gives higher scores to longer completion content."""
|
| 469 |
+
completion_contents = [completion[0]["content"] for completion in completions]
|
| 470 |
+
return [float(len(content)) for content in completion_contents]
|
| 471 |
+
|
| 472 |
+
training_args = RLOOConfig(
|
| 473 |
+
output_dir=self.tmp_dir,
|
| 474 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 475 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 476 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 477 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 478 |
+
report_to="none",
|
| 479 |
+
)
|
| 480 |
+
trainer = RLOOTrainer(
|
| 481 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 482 |
+
reward_funcs=reward_func,
|
| 483 |
+
args=training_args,
|
| 484 |
+
train_dataset=dataset,
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 488 |
+
|
| 489 |
+
trainer.train()
|
| 490 |
+
|
| 491 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 492 |
+
|
| 493 |
+
# Check that the params have changed
|
| 494 |
+
for n, param in previous_trainable_params.items():
|
| 495 |
+
new_param = trainer.model.get_parameter(n)
|
| 496 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 497 |
+
|
| 498 |
+
def test_train_multiple_reward_funcs(self):
|
| 499 |
+
# Test that RLOOTrainer can be instantiated with multiple reward functions
|
| 500 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 501 |
+
|
| 502 |
+
def reward_func1(completions, **kwargs):
|
| 503 |
+
"""Reward function that rewards longer completions."""
|
| 504 |
+
return [float(len(completion)) for completion in completions]
|
| 505 |
+
|
| 506 |
+
def reward_func2(completions, **kwargs):
|
| 507 |
+
"""Reward function that rewards completions with more unique letters."""
|
| 508 |
+
return [float(len(set(completion))) for completion in completions]
|
| 509 |
+
|
| 510 |
+
training_args = RLOOConfig(
|
| 511 |
+
output_dir=self.tmp_dir,
|
| 512 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 513 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 514 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 515 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 516 |
+
report_to="none",
|
| 517 |
+
)
|
| 518 |
+
trainer = RLOOTrainer(
|
| 519 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 520 |
+
reward_funcs=[reward_func1, reward_func2],
|
| 521 |
+
args=training_args,
|
| 522 |
+
train_dataset=dataset,
|
| 523 |
+
)
|
| 524 |
+
|
| 525 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 526 |
+
|
| 527 |
+
trainer.train()
|
| 528 |
+
|
| 529 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 530 |
+
|
| 531 |
+
# Check that the params have changed
|
| 532 |
+
for n, param in previous_trainable_params.items():
|
| 533 |
+
new_param = trainer.model.get_parameter(n)
|
| 534 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 535 |
+
|
| 536 |
+
def test_train_sync_and_async_reward_funcs(self):
|
| 537 |
+
# Test that RLOOTrainer can be instantiated with multiple reward functions one of which is async
|
| 538 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 539 |
+
|
| 540 |
+
def sync_reward_func1(completions, **kwargs):
|
| 541 |
+
"""Reward function that rewards longer completions."""
|
| 542 |
+
return [float(len(completion)) for completion in completions]
|
| 543 |
+
|
| 544 |
+
def sync_reward_func2(completions, **kwargs):
|
| 545 |
+
return [1 for _ in completions]
|
| 546 |
+
|
| 547 |
+
async def async_reward_func(completions, **kwargs):
|
| 548 |
+
"""Async Reward function that rewards completions with more unique letters."""
|
| 549 |
+
return [float(len(set(completion))) for completion in completions]
|
| 550 |
+
|
| 551 |
+
training_args = RLOOConfig(
|
| 552 |
+
output_dir=self.tmp_dir,
|
| 553 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 554 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 555 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 556 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 557 |
+
report_to="none",
|
| 558 |
+
)
|
| 559 |
+
trainer = RLOOTrainer(
|
| 560 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 561 |
+
reward_funcs=[sync_reward_func1, sync_reward_func2, async_reward_func],
|
| 562 |
+
args=training_args,
|
| 563 |
+
train_dataset=dataset,
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 567 |
+
|
| 568 |
+
trainer.train()
|
| 569 |
+
|
| 570 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 571 |
+
|
| 572 |
+
# Check that the params have changed
|
| 573 |
+
for n, param in previous_trainable_params.items():
|
| 574 |
+
new_param = trainer.model.get_parameter(n)
|
| 575 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 576 |
+
|
| 577 |
+
def test_train_multiple_reward_funcs_with_None_output(self):
|
| 578 |
+
"""Test that a valid math reward function is processed correctly while the code reward function returns None."""
|
| 579 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 580 |
+
|
| 581 |
+
def applicable_reward_func(completions, **kwargs):
|
| 582 |
+
"""A reward function that rewards longer completions."""
|
| 583 |
+
return [float(len(completion)) for completion in completions]
|
| 584 |
+
|
| 585 |
+
def non_applicable_reward_func(completions, **kwargs):
|
| 586 |
+
"""A reward function that returns None for all inputs, as it is not applicable to this sample."""
|
| 587 |
+
return [None] * len(completions)
|
| 588 |
+
|
| 589 |
+
training_args = RLOOConfig(
|
| 590 |
+
output_dir=self.tmp_dir,
|
| 591 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 592 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 593 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 594 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 595 |
+
report_to="none",
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
trainer = RLOOTrainer(
|
| 599 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 600 |
+
reward_funcs=[
|
| 601 |
+
applicable_reward_func,
|
| 602 |
+
non_applicable_reward_func,
|
| 603 |
+
], # One applicable, one non applicable
|
| 604 |
+
args=training_args,
|
| 605 |
+
train_dataset=dataset,
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
previous_trainable_params = {
|
| 609 |
+
n: param.clone() for n, param in trainer.model.named_parameters() if param.requires_grad
|
| 610 |
+
}
|
| 611 |
+
|
| 612 |
+
trainer.train()
|
| 613 |
+
|
| 614 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 615 |
+
|
| 616 |
+
# Check that the params have changed
|
| 617 |
+
for n, param in previous_trainable_params.items():
|
| 618 |
+
new_param = trainer.model.get_parameter(n)
|
| 619 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 620 |
+
|
| 621 |
+
def test_train_multiple_reward_funcs_with_weights(self):
|
| 622 |
+
"""Test that RLOOTrainer can handle multiple reward functions with weights."""
|
| 623 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 624 |
+
|
| 625 |
+
def reward_func1(completions, **kwargs):
|
| 626 |
+
"""Reward function that rewards longer completions."""
|
| 627 |
+
return [float(len(completion)) for completion in completions]
|
| 628 |
+
|
| 629 |
+
def reward_func2(completions, **kwargs):
|
| 630 |
+
"""Reward function that rewards completions with more unique letters."""
|
| 631 |
+
return [float(len(set(completion))) for completion in completions]
|
| 632 |
+
|
| 633 |
+
training_args = RLOOConfig(
|
| 634 |
+
output_dir=self.tmp_dir,
|
| 635 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 636 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 637 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 638 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 639 |
+
report_to="none",
|
| 640 |
+
reward_weights=[0.7, 0.3], # weight of reward_func1 and reward_func2 respectively
|
| 641 |
+
)
|
| 642 |
+
trainer = RLOOTrainer(
|
| 643 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 644 |
+
reward_funcs=[reward_func1, reward_func2],
|
| 645 |
+
args=training_args,
|
| 646 |
+
train_dataset=dataset,
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 650 |
+
|
| 651 |
+
trainer.train()
|
| 652 |
+
|
| 653 |
+
# Check that training logs contain both reward metrics
|
| 654 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 655 |
+
assert "rewards/reward_func1/mean" in trainer.state.log_history[-1]
|
| 656 |
+
assert "rewards/reward_func1/std" in trainer.state.log_history[-1]
|
| 657 |
+
assert "rewards/reward_func2/mean" in trainer.state.log_history[-1]
|
| 658 |
+
assert "rewards/reward_func2/std" in trainer.state.log_history[-1]
|
| 659 |
+
|
| 660 |
+
# Check that the params have changed
|
| 661 |
+
for n, param in previous_trainable_params.items():
|
| 662 |
+
new_param = trainer.model.get_parameter(n)
|
| 663 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 664 |
+
|
| 665 |
+
def test_reward_metric_reflects_reward_weights(self):
|
| 666 |
+
"""Test that the logged 'reward' metric uses reward_weights, not an unweighted sum."""
|
| 667 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 668 |
+
|
| 669 |
+
def constant_reward_1(completions, **kwargs):
|
| 670 |
+
return [1.0] * len(completions)
|
| 671 |
+
|
| 672 |
+
def constant_reward_0(completions, **kwargs):
|
| 673 |
+
return [0.0] * len(completions)
|
| 674 |
+
|
| 675 |
+
training_args = RLOOConfig(
|
| 676 |
+
output_dir=self.tmp_dir,
|
| 677 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 678 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 679 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 680 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 681 |
+
report_to="none",
|
| 682 |
+
reward_weights=[0.7, 0.3],
|
| 683 |
+
)
|
| 684 |
+
trainer = RLOOTrainer(
|
| 685 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 686 |
+
reward_funcs=[constant_reward_1, constant_reward_0],
|
| 687 |
+
args=training_args,
|
| 688 |
+
train_dataset=dataset,
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
trainer.train()
|
| 692 |
+
|
| 693 |
+
log = trainer.state.log_history[-1]
|
| 694 |
+
# With reward_weights=[0.7, 0.3] and rewards [1.0, 0.0]:
|
| 695 |
+
# weighted reward = 0.7*1.0 + 0.3*0.0 = 0.7
|
| 696 |
+
# unweighted reward = 1.0 + 0.0 = 1.0
|
| 697 |
+
assert abs(log["reward"] - 0.7) < 1e-5, (
|
| 698 |
+
f"Expected logged reward to be ~0.7 (weighted), got {log['reward']}. "
|
| 699 |
+
"The reward metric should reflect reward_weights."
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
def test_train_multiple_mixed_reward_funcs(self):
|
| 703 |
+
# Test if the trainer can handle a mix of reward functions and reward models
|
| 704 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 705 |
+
|
| 706 |
+
def reward_func(completions, **kwargs):
|
| 707 |
+
"""Reward function that rewards longer completions."""
|
| 708 |
+
return [float(len(completion)) for completion in completions]
|
| 709 |
+
|
| 710 |
+
training_args = RLOOConfig(
|
| 711 |
+
output_dir=self.tmp_dir,
|
| 712 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 713 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 714 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 715 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 716 |
+
report_to="none",
|
| 717 |
+
)
|
| 718 |
+
trainer = RLOOTrainer(
|
| 719 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 720 |
+
reward_funcs=[reward_func, "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"],
|
| 721 |
+
args=training_args,
|
| 722 |
+
train_dataset=dataset,
|
| 723 |
+
)
|
| 724 |
+
|
| 725 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 726 |
+
|
| 727 |
+
trainer.train()
|
| 728 |
+
|
| 729 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 730 |
+
|
| 731 |
+
# Check that the params have changed
|
| 732 |
+
for n, param in previous_trainable_params.items():
|
| 733 |
+
new_param = trainer.model.get_parameter(n)
|
| 734 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 735 |
+
|
| 736 |
+
def test_train_reward_func_additional_column(self):
|
| 737 |
+
# Test if trainer can handle reward function that rely on additional columns in the dataset
|
| 738 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 739 |
+
|
| 740 |
+
# Add a column to the dataset (dummy example, the column could be anything)
|
| 741 |
+
some_values = list(range(len(dataset)))
|
| 742 |
+
dataset = dataset.add_column("some_values", some_values)
|
| 743 |
+
|
| 744 |
+
def reward_func(completions, some_values, **kwargs):
|
| 745 |
+
"""Reward function that rewards completions with lengths closer to the values in some_values."""
|
| 746 |
+
return [
|
| 747 |
+
float(abs(len(completion) - value)) for completion, value in zip(completions, some_values, strict=True)
|
| 748 |
+
]
|
| 749 |
+
|
| 750 |
+
training_args = RLOOConfig(
|
| 751 |
+
output_dir=self.tmp_dir,
|
| 752 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 753 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 754 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 755 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 756 |
+
report_to="none",
|
| 757 |
+
)
|
| 758 |
+
trainer = RLOOTrainer(
|
| 759 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 760 |
+
reward_funcs=reward_func,
|
| 761 |
+
args=training_args,
|
| 762 |
+
train_dataset=dataset,
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 766 |
+
|
| 767 |
+
trainer.train()
|
| 768 |
+
|
| 769 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 770 |
+
|
| 771 |
+
# Check that the params have changed
|
| 772 |
+
for n, param in previous_trainable_params.items():
|
| 773 |
+
new_param = trainer.model.get_parameter(n)
|
| 774 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 775 |
+
|
| 776 |
+
def test_train_with_sync_ref_model(self):
|
| 777 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 778 |
+
|
| 779 |
+
training_args = RLOOConfig(
|
| 780 |
+
output_dir=self.tmp_dir,
|
| 781 |
+
beta=0.1, # ensure ref model is created so sync can update it
|
| 782 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 783 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 784 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 785 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 786 |
+
sync_ref_model=True,
|
| 787 |
+
ref_model_sync_steps=2, # reduce sync steps to ensure a sync happens
|
| 788 |
+
report_to="none",
|
| 789 |
+
)
|
| 790 |
+
trainer = RLOOTrainer(
|
| 791 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 792 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 793 |
+
args=training_args,
|
| 794 |
+
train_dataset=dataset,
|
| 795 |
+
)
|
| 796 |
+
|
| 797 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 798 |
+
assert trainer.ref_model is not None
|
| 799 |
+
previous_ref_params = {n: param.clone() for n, param in trainer.ref_model.named_parameters()}
|
| 800 |
+
|
| 801 |
+
trainer.train()
|
| 802 |
+
|
| 803 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 804 |
+
|
| 805 |
+
# Check that the params have changed
|
| 806 |
+
for n, param in previous_trainable_params.items():
|
| 807 |
+
new_param = trainer.model.get_parameter(n)
|
| 808 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 809 |
+
new_ref_param = trainer.ref_model.get_parameter(n)
|
| 810 |
+
assert not torch.equal(previous_ref_params[n], new_ref_param), f"Ref Parameter {n} has not changed."
|
| 811 |
+
|
| 812 |
+
def test_train_beta_zero(self):
|
| 813 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 814 |
+
training_args = RLOOConfig(
|
| 815 |
+
output_dir=self.tmp_dir,
|
| 816 |
+
beta=0.0, # set beta to zero value to test the case where the reference model is not used
|
| 817 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 818 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 819 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 820 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 821 |
+
report_to="none",
|
| 822 |
+
)
|
| 823 |
+
trainer = RLOOTrainer(
|
| 824 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 825 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 826 |
+
args=training_args,
|
| 827 |
+
train_dataset=dataset,
|
| 828 |
+
)
|
| 829 |
+
|
| 830 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 831 |
+
|
| 832 |
+
trainer.train()
|
| 833 |
+
|
| 834 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 835 |
+
|
| 836 |
+
# Check that the params have changed
|
| 837 |
+
for n, param in previous_trainable_params.items():
|
| 838 |
+
new_param = trainer.model.get_parameter(n)
|
| 839 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 840 |
+
|
| 841 |
+
def test_train_with_pad_to_multiple_of(self):
|
| 842 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 843 |
+
|
| 844 |
+
training_args = RLOOConfig(
|
| 845 |
+
output_dir=self.tmp_dir,
|
| 846 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 847 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 848 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 849 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 850 |
+
pad_to_multiple_of=8,
|
| 851 |
+
report_to="none",
|
| 852 |
+
)
|
| 853 |
+
trainer = RLOOTrainer(
|
| 854 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 855 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 856 |
+
args=training_args,
|
| 857 |
+
train_dataset=dataset,
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 861 |
+
|
| 862 |
+
trainer.train()
|
| 863 |
+
|
| 864 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 865 |
+
|
| 866 |
+
# Check that the params have changed
|
| 867 |
+
for n, param in previous_trainable_params.items():
|
| 868 |
+
new_param = trainer.model.get_parameter(n)
|
| 869 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 870 |
+
|
| 871 |
+
@require_peft
|
| 872 |
+
@require_vllm
|
| 873 |
+
@pytest.mark.skip(reason="We should add a mock for the vLLM server.")
|
| 874 |
+
def test_train_vllm_and_peft(self):
|
| 875 |
+
"""Test that training works with vLLM for generation."""
|
| 876 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 877 |
+
"Qwen/Qwen2.5-0.5B-Instruct", dtype="float32"
|
| 878 |
+
) # tiny model is too small for vLLM
|
| 879 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 880 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 881 |
+
|
| 882 |
+
training_args = RLOOConfig(
|
| 883 |
+
output_dir=self.tmp_dir,
|
| 884 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 885 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 886 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 887 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 888 |
+
report_to="none",
|
| 889 |
+
use_vllm=True,
|
| 890 |
+
)
|
| 891 |
+
lora_config = LoraConfig(
|
| 892 |
+
target_modules="all-linear",
|
| 893 |
+
# test with non-default modules as it adds extra keys in state_dict that we need to handle
|
| 894 |
+
modules_to_save=["embed_tokens", "lm_head"],
|
| 895 |
+
)
|
| 896 |
+
trainer = RLOOTrainer(
|
| 897 |
+
model=model,
|
| 898 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 899 |
+
args=training_args,
|
| 900 |
+
train_dataset=dataset,
|
| 901 |
+
peft_config=lora_config,
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 905 |
+
|
| 906 |
+
trainer.train()
|
| 907 |
+
|
| 908 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 909 |
+
|
| 910 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 911 |
+
for n, param in previous_trainable_params.items():
|
| 912 |
+
new_param = trainer.model.get_parameter(n)
|
| 913 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 914 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 915 |
+
elif "base_layer" not in n and "original_module" not in n:
|
| 916 |
+
# We expect the peft params to be different (except for the base layer)
|
| 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_structured_outputs(self):
|
| 922 |
+
"""Test that training works with vLLM for generation with structured outputs."""
|
| 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 |
+
vllm_structured_outputs_regex=r"<reasoning>\n.*\n</reasoning>\n<answer>\n.*\n</answer>",
|
| 934 |
+
)
|
| 935 |
+
trainer = RLOOTrainer(
|
| 936 |
+
model="Qwen/Qwen2.5-0.5B-Instruct", # tiny model is too small for vLLM
|
| 937 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 938 |
+
args=training_args,
|
| 939 |
+
train_dataset=dataset,
|
| 940 |
+
)
|
| 941 |
+
|
| 942 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 943 |
+
|
| 944 |
+
trainer.train()
|
| 945 |
+
|
| 946 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 947 |
+
|
| 948 |
+
# Check that the params have changed
|
| 949 |
+
for n, param in previous_trainable_params.items():
|
| 950 |
+
new_param = trainer.model.get_parameter(n)
|
| 951 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 952 |
+
|
| 953 |
+
def test_train_with_additional_generation_kwargs(self):
|
| 954 |
+
"""Test that training works with additional generation kwargs."""
|
| 955 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 956 |
+
|
| 957 |
+
training_args = RLOOConfig(
|
| 958 |
+
output_dir=self.tmp_dir,
|
| 959 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 960 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 961 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 962 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 963 |
+
report_to="none",
|
| 964 |
+
top_p=0.9,
|
| 965 |
+
top_k=10,
|
| 966 |
+
min_p=0.01,
|
| 967 |
+
repetition_penalty=1.1,
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
trainer = RLOOTrainer(
|
| 971 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 972 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 973 |
+
args=training_args,
|
| 974 |
+
train_dataset=dataset,
|
| 975 |
+
)
|
| 976 |
+
|
| 977 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 978 |
+
|
| 979 |
+
trainer.train()
|
| 980 |
+
|
| 981 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 982 |
+
|
| 983 |
+
# Check that the params have changed
|
| 984 |
+
for n, param in previous_trainable_params.items():
|
| 985 |
+
new_param = trainer.model.get_parameter(n)
|
| 986 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 987 |
+
|
| 988 |
+
@require_vllm
|
| 989 |
+
@pytest.mark.skip(reason="We should add a mock for the vLLM server.")
|
| 990 |
+
def test_train_vllm_with_additional_generation_kwargs(self):
|
| 991 |
+
"""Test that training works with vLLM and additional generation kwargs."""
|
| 992 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 993 |
+
|
| 994 |
+
training_args = RLOOConfig(
|
| 995 |
+
output_dir=self.tmp_dir,
|
| 996 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 997 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 998 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 999 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1000 |
+
report_to="none",
|
| 1001 |
+
use_vllm=True,
|
| 1002 |
+
top_p=0.9,
|
| 1003 |
+
top_k=10,
|
| 1004 |
+
min_p=0.01,
|
| 1005 |
+
repetition_penalty=1.1,
|
| 1006 |
+
)
|
| 1007 |
+
|
| 1008 |
+
trainer = RLOOTrainer(
|
| 1009 |
+
model="Qwen/Qwen2.5-0.5B-Instruct", # tiny model is too small for vLLM
|
| 1010 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 1011 |
+
args=training_args,
|
| 1012 |
+
train_dataset=dataset,
|
| 1013 |
+
)
|
| 1014 |
+
|
| 1015 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1016 |
+
|
| 1017 |
+
trainer.train()
|
| 1018 |
+
|
| 1019 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1020 |
+
|
| 1021 |
+
# Check that the params have changed
|
| 1022 |
+
for n, param in previous_trainable_params.items():
|
| 1023 |
+
new_param = trainer.model.get_parameter(n)
|
| 1024 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1025 |
+
|
| 1026 |
+
def test_train_with_normalized_advantages(self):
|
| 1027 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1028 |
+
|
| 1029 |
+
training_args = RLOOConfig(
|
| 1030 |
+
output_dir=self.tmp_dir,
|
| 1031 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1032 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 1033 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 1034 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1035 |
+
normalize_advantages=True,
|
| 1036 |
+
report_to="none",
|
| 1037 |
+
)
|
| 1038 |
+
trainer = RLOOTrainer(
|
| 1039 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1040 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 1041 |
+
args=training_args,
|
| 1042 |
+
train_dataset=dataset,
|
| 1043 |
+
)
|
| 1044 |
+
|
| 1045 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1046 |
+
|
| 1047 |
+
trainer.train()
|
| 1048 |
+
|
| 1049 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1050 |
+
|
| 1051 |
+
# Check that the params have changed
|
| 1052 |
+
for n, param in previous_trainable_params.items():
|
| 1053 |
+
new_param = trainer.model.get_parameter(n)
|
| 1054 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1055 |
+
|
| 1056 |
+
def test_train_with_clipped_rewards(self):
|
| 1057 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1058 |
+
|
| 1059 |
+
training_args = RLOOConfig(
|
| 1060 |
+
output_dir=self.tmp_dir,
|
| 1061 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1062 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 1063 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 1064 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1065 |
+
reward_clip_range=(-1, 1),
|
| 1066 |
+
report_to="none",
|
| 1067 |
+
)
|
| 1068 |
+
trainer = RLOOTrainer(
|
| 1069 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1070 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 1071 |
+
args=training_args,
|
| 1072 |
+
train_dataset=dataset,
|
| 1073 |
+
)
|
| 1074 |
+
|
| 1075 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1076 |
+
|
| 1077 |
+
trainer.train()
|
| 1078 |
+
|
| 1079 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1080 |
+
|
| 1081 |
+
# Check that the params have changed
|
| 1082 |
+
for n, param in previous_trainable_params.items():
|
| 1083 |
+
new_param = trainer.model.get_parameter(n)
|
| 1084 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1085 |
+
|
| 1086 |
+
@patch("transformers.generation.utils.GenerationMixin.generate")
|
| 1087 |
+
def test_train_with_mask_truncated_completions(self, mock_generate):
|
| 1088 |
+
"""Test that training works with mask_truncated_completions=True parameter."""
|
| 1089 |
+
|
| 1090 |
+
# We mock the generate method because the model's random weights make it extremely unlikely to produce a
|
| 1091 |
+
# sequence containing the EOS token within the allowed max_completion_length. As a result, all tokens are
|
| 1092 |
+
# masked in the loss, the model doesn't update, and the final check (which verifies the update) fails.
|
| 1093 |
+
def fake_generate(input_ids, **kwargs):
|
| 1094 |
+
# pad_token_id = 151643; eos_token_id = 151645
|
| 1095 |
+
completion_ids = torch.tensor(
|
| 1096 |
+
[
|
| 1097 |
+
[1, 2, 3, 4, 5, 6, 7, 8], # this one is truncated
|
| 1098 |
+
[9, 10, 11, 151645, 151643, 151643, 151643, 151643], # this one contains eos
|
| 1099 |
+
[12, 13, 14, 15, 16, 17, 18, 151645], # particular case, eos is generated just within the limit
|
| 1100 |
+
],
|
| 1101 |
+
device=input_ids.device,
|
| 1102 |
+
)
|
| 1103 |
+
return torch.cat([input_ids, completion_ids], dim=1)
|
| 1104 |
+
|
| 1105 |
+
mock_generate.side_effect = fake_generate
|
| 1106 |
+
|
| 1107 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1108 |
+
|
| 1109 |
+
training_args = RLOOConfig(
|
| 1110 |
+
output_dir=self.tmp_dir,
|
| 1111 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1112 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 1113 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 1114 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1115 |
+
mask_truncated_completions=True, # Enable masking of truncated completions
|
| 1116 |
+
report_to="none",
|
| 1117 |
+
)
|
| 1118 |
+
trainer = RLOOTrainer(
|
| 1119 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1120 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 1121 |
+
args=training_args,
|
| 1122 |
+
train_dataset=dataset,
|
| 1123 |
+
)
|
| 1124 |
+
|
| 1125 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1126 |
+
|
| 1127 |
+
trainer.train()
|
| 1128 |
+
|
| 1129 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1130 |
+
|
| 1131 |
+
# Check that the params have changed
|
| 1132 |
+
for n, param in previous_trainable_params.items():
|
| 1133 |
+
new_param = trainer.model.get_parameter(n)
|
| 1134 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1135 |
+
|
| 1136 |
+
def test_train_with_mask_truncated_completions_all_masked(self):
|
| 1137 |
+
"""
|
| 1138 |
+
Test that when all generated completions are truncated (i.e., none contain an EOS token), and
|
| 1139 |
+
mask_truncated_completions=True, the model receives no effective learning signal and therefore does not update
|
| 1140 |
+
its parameters.
|
| 1141 |
+
|
| 1142 |
+
Here, we don't mock the generate method, be we rely on the fact that the model the probability of generating
|
| 1143 |
+
the EOS token is extremely low, so all generated completions are truncated.
|
| 1144 |
+
"""
|
| 1145 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1146 |
+
|
| 1147 |
+
training_args = RLOOConfig(
|
| 1148 |
+
output_dir=self.tmp_dir,
|
| 1149 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1150 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 1151 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 1152 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1153 |
+
mask_truncated_completions=True, # Enable masking of truncated completions
|
| 1154 |
+
report_to="none",
|
| 1155 |
+
)
|
| 1156 |
+
trainer = RLOOTrainer(
|
| 1157 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1158 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 1159 |
+
args=training_args,
|
| 1160 |
+
train_dataset=dataset,
|
| 1161 |
+
)
|
| 1162 |
+
|
| 1163 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1164 |
+
|
| 1165 |
+
trainer.train()
|
| 1166 |
+
|
| 1167 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1168 |
+
|
| 1169 |
+
# Check that the params have changed
|
| 1170 |
+
for n, param in previous_trainable_params.items():
|
| 1171 |
+
new_param = trainer.model.get_parameter(n)
|
| 1172 |
+
assert torch.equal(param, new_param), f"Parameter {n} has changed."
|
| 1173 |
+
|
| 1174 |
+
def test_warning_raised_all_rewards_none(self, caplog):
|
| 1175 |
+
"""Test that a proper warning is raised when all rewards are None."""
|
| 1176 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1177 |
+
|
| 1178 |
+
def always_none_reward_func(completions, **kwargs):
|
| 1179 |
+
"""Reward function that always returns None."""
|
| 1180 |
+
return [None] * len(completions)
|
| 1181 |
+
|
| 1182 |
+
training_args = RLOOConfig(
|
| 1183 |
+
output_dir=self.tmp_dir,
|
| 1184 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1185 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 1186 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 1187 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1188 |
+
report_to="none",
|
| 1189 |
+
)
|
| 1190 |
+
trainer = RLOOTrainer(
|
| 1191 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1192 |
+
reward_funcs=always_none_reward_func,
|
| 1193 |
+
args=training_args,
|
| 1194 |
+
train_dataset=dataset,
|
| 1195 |
+
)
|
| 1196 |
+
|
| 1197 |
+
with caplog.at_level("WARNING", logger="trl.trainer.rloo_trainer"):
|
| 1198 |
+
trainer.train()
|
| 1199 |
+
|
| 1200 |
+
expected_warning = "All reward functions returned None for the following kwargs:"
|
| 1201 |
+
assert expected_warning in caplog.text
|
| 1202 |
+
|
| 1203 |
+
def test_train_num_generations_larger_than_batch_size(self):
|
| 1204 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1205 |
+
|
| 1206 |
+
training_args = RLOOConfig(
|
| 1207 |
+
output_dir=self.tmp_dir,
|
| 1208 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1209 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 1210 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1211 |
+
num_generations=6, # the number of generations is larger than the batch size, but
|
| 1212 |
+
gradient_accumulation_steps=2, # gradient accumulation should allow that
|
| 1213 |
+
report_to="none",
|
| 1214 |
+
)
|
| 1215 |
+
trainer = RLOOTrainer(
|
| 1216 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1217 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 1218 |
+
args=training_args,
|
| 1219 |
+
train_dataset=dataset,
|
| 1220 |
+
)
|
| 1221 |
+
|
| 1222 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1223 |
+
|
| 1224 |
+
trainer.train()
|
| 1225 |
+
|
| 1226 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1227 |
+
|
| 1228 |
+
# Check that the params have changed
|
| 1229 |
+
for n, param in previous_trainable_params.items():
|
| 1230 |
+
new_param = trainer.model.get_parameter(n)
|
| 1231 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1232 |
+
|
| 1233 |
+
def test_train_multiple_dataloader_workers(self):
|
| 1234 |
+
# Pytest/CI often starts background threads before tests run. With Python 3.12, using the default "fork" start
|
| 1235 |
+
# method in a multi-threaded process emits a DeprecationWarning and may deadlock.
|
| 1236 |
+
#
|
| 1237 |
+
# We force "spawn" here to make multiprocessing safe under pytest when DataLoader workers are enabled. This is
|
| 1238 |
+
# test-environment–specific and not required by the training logic itself.
|
| 1239 |
+
#
|
| 1240 |
+
# This means the test does not cover "fork". However, "spawn" is stricter (requires full picklability and clean
|
| 1241 |
+
# state) and avoids fork-after-threads issues that pytest cannot reliably test anyway. Fork-specific behavior,
|
| 1242 |
+
# if needed, should be tested in a clean process outside pytest.
|
| 1243 |
+
torch.multiprocessing.set_start_method("spawn", force=True)
|
| 1244 |
+
|
| 1245 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1246 |
+
|
| 1247 |
+
training_args = RLOOConfig(
|
| 1248 |
+
output_dir=self.tmp_dir,
|
| 1249 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1250 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 1251 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 1252 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1253 |
+
dataloader_num_workers=2, # use multiple dataloader workers
|
| 1254 |
+
report_to="none",
|
| 1255 |
+
)
|
| 1256 |
+
trainer = RLOOTrainer(
|
| 1257 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1258 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 1259 |
+
args=training_args,
|
| 1260 |
+
train_dataset=dataset,
|
| 1261 |
+
)
|
| 1262 |
+
|
| 1263 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1264 |
+
|
| 1265 |
+
trainer.train()
|
| 1266 |
+
|
| 1267 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1268 |
+
|
| 1269 |
+
# Check that the params have changed
|
| 1270 |
+
for n, param in previous_trainable_params.items():
|
| 1271 |
+
new_param = trainer.model.get_parameter(n)
|
| 1272 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1273 |
+
|
| 1274 |
+
def test_train_with_generation_kwargs(self):
|
| 1275 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1276 |
+
|
| 1277 |
+
training_args = RLOOConfig(
|
| 1278 |
+
output_dir=self.tmp_dir,
|
| 1279 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1280 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 1281 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 1282 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1283 |
+
# Pass gen kwargs
|
| 1284 |
+
generation_kwargs={"do_sample": True, "top_k": 50, "num_beams": 2, "length_penalty": -0.1},
|
| 1285 |
+
report_to="none",
|
| 1286 |
+
)
|
| 1287 |
+
trainer = RLOOTrainer(
|
| 1288 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1289 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 1290 |
+
args=training_args,
|
| 1291 |
+
train_dataset=dataset,
|
| 1292 |
+
)
|
| 1293 |
+
|
| 1294 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1295 |
+
|
| 1296 |
+
trainer.train()
|
| 1297 |
+
|
| 1298 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1299 |
+
|
| 1300 |
+
# Check that the params have changed
|
| 1301 |
+
for n, param in previous_trainable_params.items():
|
| 1302 |
+
new_param = trainer.model.get_parameter(n)
|
| 1303 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1304 |
+
|
| 1305 |
+
def test_train_with_reward_func_accessing_trainer_state(self):
|
| 1306 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1307 |
+
|
| 1308 |
+
def reward_func(completions, **kwargs):
|
| 1309 |
+
trainer_state = kwargs.get("trainer_state")
|
| 1310 |
+
assert trainer_state is not None
|
| 1311 |
+
# transformers.TrainerState instance should have a `global_step` property.
|
| 1312 |
+
assert hasattr(trainer_state, "global_step")
|
| 1313 |
+
return [float(len(set(completion))) for completion in completions]
|
| 1314 |
+
|
| 1315 |
+
training_args = RLOOConfig(
|
| 1316 |
+
output_dir=self.tmp_dir,
|
| 1317 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 1318 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 1319 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1320 |
+
report_to="none",
|
| 1321 |
+
)
|
| 1322 |
+
trainer = RLOOTrainer(
|
| 1323 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1324 |
+
reward_funcs=reward_func,
|
| 1325 |
+
args=training_args,
|
| 1326 |
+
train_dataset=dataset,
|
| 1327 |
+
)
|
| 1328 |
+
trainer.train()
|
| 1329 |
+
|
| 1330 |
+
def test_train_reward_func_with_log_extra(self):
|
| 1331 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1332 |
+
|
| 1333 |
+
def reward_func(completions, **kwargs):
|
| 1334 |
+
log_extra = kwargs.get("log_extra")
|
| 1335 |
+
assert log_extra is not None
|
| 1336 |
+
log_extra("test_column", [completion[:5] for completion in completions])
|
| 1337 |
+
return [float(len(completion)) for completion in completions]
|
| 1338 |
+
|
| 1339 |
+
training_args = RLOOConfig(
|
| 1340 |
+
output_dir=self.tmp_dir,
|
| 1341 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 1342 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 1343 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1344 |
+
report_to="none",
|
| 1345 |
+
log_completions=True,
|
| 1346 |
+
)
|
| 1347 |
+
trainer = RLOOTrainer(
|
| 1348 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1349 |
+
reward_funcs=reward_func,
|
| 1350 |
+
args=training_args,
|
| 1351 |
+
train_dataset=dataset,
|
| 1352 |
+
)
|
| 1353 |
+
trainer.train()
|
| 1354 |
+
assert "test_column" in trainer._logs["extra"]
|
| 1355 |
+
|
| 1356 |
+
def test_train_reward_func_with_log_metric(self):
|
| 1357 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1358 |
+
|
| 1359 |
+
def reward_func(completions, **kwargs):
|
| 1360 |
+
log_metric = kwargs.get("log_metric")
|
| 1361 |
+
assert log_metric is not None
|
| 1362 |
+
log_metric("custom_accuracy", 0.75)
|
| 1363 |
+
return [float(len(completion)) for completion in completions]
|
| 1364 |
+
|
| 1365 |
+
training_args = RLOOConfig(
|
| 1366 |
+
output_dir=self.tmp_dir,
|
| 1367 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 1368 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 1369 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1370 |
+
report_to="none",
|
| 1371 |
+
)
|
| 1372 |
+
trainer = RLOOTrainer(
|
| 1373 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1374 |
+
reward_funcs=reward_func,
|
| 1375 |
+
args=training_args,
|
| 1376 |
+
train_dataset=dataset,
|
| 1377 |
+
)
|
| 1378 |
+
trainer.train()
|
| 1379 |
+
# log_metric appends to _metrics, which gets averaged and merged into log_history
|
| 1380 |
+
logged_keys = {k for entry in trainer.state.log_history for k in entry}
|
| 1381 |
+
assert "custom_accuracy" in logged_keys
|
| 1382 |
+
|
| 1383 |
+
def test_prepare_input_called_with_correct_data(self):
|
| 1384 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1385 |
+
training_args = RLOOConfig(
|
| 1386 |
+
output_dir=self.tmp_dir,
|
| 1387 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1388 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1389 |
+
gradient_accumulation_steps=3, # can be anything in this test
|
| 1390 |
+
# steps_per_generation*per_device_train_batch_size=24 is divisible by num_generations=4
|
| 1391 |
+
steps_per_generation=4,
|
| 1392 |
+
num_generations=4,
|
| 1393 |
+
per_device_train_batch_size=6, # reduce the batch size to reduce memory usage
|
| 1394 |
+
num_iterations=2,
|
| 1395 |
+
shuffle_dataset=False,
|
| 1396 |
+
report_to="none",
|
| 1397 |
+
)
|
| 1398 |
+
trainer = RLOOTrainer(
|
| 1399 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1400 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 1401 |
+
args=training_args,
|
| 1402 |
+
train_dataset=dataset,
|
| 1403 |
+
)
|
| 1404 |
+
# steps_per_generation=4, per_device_train_batch_size=6 and num_generations=4, so we expect a
|
| 1405 |
+
# generation batch of 24 samples (steps_per_generation * per_device_train_batch_size), containing 6
|
| 1406 |
+
# different prompts (steps_per_generation * per_device_train_batch_size // num_generations), each repeated
|
| 1407 |
+
# 4 times (num_generations).
|
| 1408 |
+
expected_first_generation_batch = (
|
| 1409 |
+
[{"prompt": "Beautiful is better than"}] * 4
|
| 1410 |
+
+ [{"prompt": "Explicit is"}] * 4
|
| 1411 |
+
+ [{"prompt": "Simple is better"}] * 4
|
| 1412 |
+
+ [{"prompt": "Complex"}] * 4
|
| 1413 |
+
+ [{"prompt": "Flat is better than"}] * 4
|
| 1414 |
+
+ [{"prompt": "Sparse is better"}] * 4
|
| 1415 |
+
)
|
| 1416 |
+
expected_second_generation_batch = (
|
| 1417 |
+
[{"prompt": "Readability"}] * 4
|
| 1418 |
+
+ [{"prompt": "Special cases aren't special"}] * 4
|
| 1419 |
+
+ [{"prompt": "Although practicality beats"}] * 4
|
| 1420 |
+
+ [{"prompt": "Errors should never"}] * 4
|
| 1421 |
+
+ [{"prompt": "Unless explicitly"}] * 4
|
| 1422 |
+
+ [{"prompt": "In the face of ambiguity, refuse"}] * 4
|
| 1423 |
+
)
|
| 1424 |
+
|
| 1425 |
+
with patch.object(RLOOTrainer, "training_step", wraps=trainer.training_step) as mock_prepare:
|
| 1426 |
+
trainer.train()
|
| 1427 |
+
# 3 epochs * 2 iterations * 2 generation batches to cover the dataset * 4 steps_per_generation
|
| 1428 |
+
assert mock_prepare.call_count == 48
|
| 1429 |
+
for i in range(0, 8): # Generation batch repeated 8 times (steps_per_generation*num_iterations)
|
| 1430 |
+
assert mock_prepare.call_args_list[i].args[1] == expected_first_generation_batch
|
| 1431 |
+
for i in range(8, 16):
|
| 1432 |
+
assert mock_prepare.call_args_list[i].args[1] == expected_second_generation_batch
|
| 1433 |
+
|
| 1434 |
+
def test_train_with_chat_template_kwargs(self):
|
| 1435 |
+
dataset = load_dataset("trl-internal-testing/zen", "conversational_prompt_only", split="train")
|
| 1436 |
+
|
| 1437 |
+
training_args = RLOOConfig(
|
| 1438 |
+
output_dir=self.tmp_dir,
|
| 1439 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1440 |
+
per_device_train_batch_size=3, # reduce the batch size to reduce memory usage
|
| 1441 |
+
num_generations=3, # reduce the number of generations to reduce memory usage
|
| 1442 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1443 |
+
report_to="none",
|
| 1444 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 1445 |
+
)
|
| 1446 |
+
trainer = RLOOTrainer(
|
| 1447 |
+
model="trl-internal-testing/tiny-Qwen3ForCausalLM",
|
| 1448 |
+
reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 1449 |
+
args=training_args,
|
| 1450 |
+
train_dataset=dataset,
|
| 1451 |
+
)
|
| 1452 |
+
|
| 1453 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1454 |
+
|
| 1455 |
+
trainer.train()
|
| 1456 |
+
|
| 1457 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1458 |
+
|
| 1459 |
+
# Check that the params have changed
|
| 1460 |
+
for n, param in previous_trainable_params.items():
|
| 1461 |
+
new_param = trainer.model.get_parameter(n)
|
| 1462 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1463 |
+
|
| 1464 |
+
def test_mismatched_reward_processing_classes_length(self):
|
| 1465 |
+
"""Test that mismatched length between reward_funcs and reward_processing_classes raises error."""
|
| 1466 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1467 |
+
|
| 1468 |
+
# Use two reward models
|
| 1469 |
+
reward_models = [
|
| 1470 |
+
"trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 1471 |
+
"trl-internal-testing/tiny-Qwen3ForSequenceClassification",
|
| 1472 |
+
]
|
| 1473 |
+
|
| 1474 |
+
# Create a single processing class (tokenizer)
|
| 1475 |
+
single_processing_class = AutoTokenizer.from_pretrained(
|
| 1476 |
+
"trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"
|
| 1477 |
+
)
|
| 1478 |
+
|
| 1479 |
+
training_args = RLOOConfig(output_dir=self.tmp_dir, report_to="none")
|
| 1480 |
+
|
| 1481 |
+
with pytest.raises(ValueError, match="must match"):
|
| 1482 |
+
RLOOTrainer(
|
| 1483 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1484 |
+
reward_funcs=reward_models,
|
| 1485 |
+
reward_processing_classes=single_processing_class, # only one, but need two
|
| 1486 |
+
args=training_args,
|
| 1487 |
+
train_dataset=dataset,
|
| 1488 |
+
)
|
| 1489 |
+
|
| 1490 |
+
def test_correct_reward_processing_classes_list(self):
|
| 1491 |
+
"""Test that correct list of reward_processing_classes works properly."""
|
| 1492 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1493 |
+
|
| 1494 |
+
# Use two reward models
|
| 1495 |
+
reward_models = [
|
| 1496 |
+
"trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5",
|
| 1497 |
+
"trl-internal-testing/tiny-Qwen3ForSequenceClassification",
|
| 1498 |
+
]
|
| 1499 |
+
|
| 1500 |
+
# Create processing classes
|
| 1501 |
+
processing_class1 = AutoTokenizer.from_pretrained(
|
| 1502 |
+
"trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"
|
| 1503 |
+
)
|
| 1504 |
+
processing_class2 = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen3ForSequenceClassification")
|
| 1505 |
+
|
| 1506 |
+
training_args = RLOOConfig(output_dir=self.tmp_dir, report_to="none")
|
| 1507 |
+
|
| 1508 |
+
# Correct list length should work
|
| 1509 |
+
correct_processing_classes = [processing_class1, processing_class2]
|
| 1510 |
+
|
| 1511 |
+
trainer = RLOOTrainer(
|
| 1512 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1513 |
+
reward_funcs=reward_models,
|
| 1514 |
+
reward_processing_classes=correct_processing_classes,
|
| 1515 |
+
args=training_args,
|
| 1516 |
+
train_dataset=dataset,
|
| 1517 |
+
)
|
| 1518 |
+
|
| 1519 |
+
assert len(trainer.reward_processing_classes) == len(reward_models)
|
| 1520 |
+
|
| 1521 |
+
def test_single_reward_model_with_single_processing_class(self):
|
| 1522 |
+
"""Test that single reward model with single processing class works."""
|
| 1523 |
+
dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
|
| 1524 |
+
|
| 1525 |
+
# Use single reward model
|
| 1526 |
+
reward_model = "trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"
|
| 1527 |
+
|
| 1528 |
+
# Create a single processing class (tokenizer)
|
| 1529 |
+
single_processing_class = AutoTokenizer.from_pretrained(
|
| 1530 |
+
"trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5"
|
| 1531 |
+
)
|
| 1532 |
+
|
| 1533 |
+
training_args = RLOOConfig(output_dir=self.tmp_dir, report_to="none")
|
| 1534 |
+
|
| 1535 |
+
trainer = RLOOTrainer(
|
| 1536 |
+
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
|
| 1537 |
+
reward_funcs=reward_model,
|
| 1538 |
+
reward_processing_classes=single_processing_class, # single object for single reward model
|
| 1539 |
+
args=training_args,
|
| 1540 |
+
train_dataset=dataset,
|
| 1541 |
+
)
|
| 1542 |
+
|
| 1543 |
+
assert len(trainer.reward_processing_classes) == 1
|
| 1544 |
+
assert trainer.reward_processing_classes[0] == single_processing_class
|
| 1545 |
+
|
| 1546 |
+
|
| 1547 |
+
@require_vision
|
| 1548 |
+
class TestRLOOTrainerVLM(TrlTestCase):
|
| 1549 |
+
@pytest.mark.parametrize(
|
| 1550 |
+
"model_id",
|
| 1551 |
+
[
|
| 1552 |
+
"trl-internal-testing/tiny-Gemma3ForConditionalGeneration",
|
| 1553 |
+
pytest.param(
|
| 1554 |
+
"trl-internal-testing/tiny-Gemma4ForConditionalGeneration",
|
| 1555 |
+
marks=pytest.mark.skipif(
|
| 1556 |
+
Version(transformers.__version__) < Version("5.5.0"),
|
| 1557 |
+
reason="Gemma4 models were introduced in transformers-5.5.0",
|
| 1558 |
+
),
|
| 1559 |
+
),
|
| 1560 |
+
"trl-internal-testing/tiny-LlavaNextForConditionalGeneration",
|
| 1561 |
+
"trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 1562 |
+
"trl-internal-testing/tiny-Qwen2VLForConditionalGeneration",
|
| 1563 |
+
pytest.param(
|
| 1564 |
+
"trl-internal-testing/tiny-Qwen3_5ForConditionalGeneration-NoThink",
|
| 1565 |
+
marks=pytest.mark.skipif(
|
| 1566 |
+
Version(transformers.__version__) < Version("5.2.0"),
|
| 1567 |
+
reason="Qwen3.5 models were introduced in transformers-5.2.0",
|
| 1568 |
+
),
|
| 1569 |
+
),
|
| 1570 |
+
pytest.param(
|
| 1571 |
+
"trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6",
|
| 1572 |
+
marks=pytest.mark.skipif(
|
| 1573 |
+
Version(transformers.__version__) < Version("5.2.0"),
|
| 1574 |
+
reason="Qwen3.5 models were introduced in transformers-5.2.0",
|
| 1575 |
+
),
|
| 1576 |
+
),
|
| 1577 |
+
# "trl-internal-testing/tiny-SmolVLMForConditionalGeneration", seems not to support bf16 properly
|
| 1578 |
+
],
|
| 1579 |
+
)
|
| 1580 |
+
def test_train_vlm(self, model_id):
|
| 1581 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train")
|
| 1582 |
+
|
| 1583 |
+
def reward_func(completions, **kwargs):
|
| 1584 |
+
"""Reward function that rewards longer completions."""
|
| 1585 |
+
return [float(len(completion[0]["content"])) for completion in completions]
|
| 1586 |
+
|
| 1587 |
+
training_args = RLOOConfig(
|
| 1588 |
+
output_dir=self.tmp_dir,
|
| 1589 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1590 |
+
per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 1591 |
+
num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM
|
| 1592 |
+
# note: num_generations=2 is only suitable for CI testing; production training should use more generations
|
| 1593 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1594 |
+
report_to="none",
|
| 1595 |
+
)
|
| 1596 |
+
trainer = RLOOTrainer(
|
| 1597 |
+
model=model_id,
|
| 1598 |
+
reward_funcs=reward_func,
|
| 1599 |
+
args=training_args,
|
| 1600 |
+
train_dataset=dataset,
|
| 1601 |
+
)
|
| 1602 |
+
|
| 1603 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1604 |
+
|
| 1605 |
+
trainer.train()
|
| 1606 |
+
|
| 1607 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1608 |
+
|
| 1609 |
+
# Check that the params have changed
|
| 1610 |
+
for n, param in previous_trainable_params.items():
|
| 1611 |
+
new_param = trainer.model.get_parameter(n)
|
| 1612 |
+
# LLaVA & LLaVA-Next: vision_feature_layer=-2 leaves the last encoder layer (layers.1) and
|
| 1613 |
+
# post_layernorm (pooler-only path) without gradient by design. Assert they stay frozen — if they
|
| 1614 |
+
# ever start training, the feature-selection plumbing has likely regressed.
|
| 1615 |
+
if model_id in (
|
| 1616 |
+
"trl-internal-testing/tiny-LlavaForConditionalGeneration",
|
| 1617 |
+
"trl-internal-testing/tiny-LlavaNextForConditionalGeneration",
|
| 1618 |
+
) and ("encoder.layers.1" in n or "post_layernorm" in n):
|
| 1619 |
+
assert torch.equal(param, new_param), f"Param {n} expected frozen by LLaVA design, but changed"
|
| 1620 |
+
else:
|
| 1621 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1622 |
+
|
| 1623 |
+
def test_train_vlm_with_pad_to_multiple_of(self):
|
| 1624 |
+
# Models like Gemma3 use other forward keyword arguments like token_type_ids that also need to be padded when
|
| 1625 |
+
# using pad_to_multiple_of, so we test that the trainer correctly pads all the necessary inputs in this case.
|
| 1626 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train")
|
| 1627 |
+
|
| 1628 |
+
def reward_func(completions, **kwargs):
|
| 1629 |
+
"""Reward function that rewards longer completions."""
|
| 1630 |
+
return [float(len(completion[0]["content"])) for completion in completions]
|
| 1631 |
+
|
| 1632 |
+
training_args = RLOOConfig(
|
| 1633 |
+
output_dir=self.tmp_dir,
|
| 1634 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1635 |
+
per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 1636 |
+
num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM
|
| 1637 |
+
# note: num_generations=2 is only suitable for CI testing; production training should use more generations
|
| 1638 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1639 |
+
pad_to_multiple_of=7,
|
| 1640 |
+
report_to="none",
|
| 1641 |
+
)
|
| 1642 |
+
trainer = RLOOTrainer(
|
| 1643 |
+
model="trl-internal-testing/tiny-Gemma3ForConditionalGeneration",
|
| 1644 |
+
reward_funcs=reward_func,
|
| 1645 |
+
args=training_args,
|
| 1646 |
+
train_dataset=dataset,
|
| 1647 |
+
)
|
| 1648 |
+
|
| 1649 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1650 |
+
|
| 1651 |
+
trainer.train()
|
| 1652 |
+
|
| 1653 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1654 |
+
|
| 1655 |
+
# Check that the params have changed
|
| 1656 |
+
for n, param in previous_trainable_params.items():
|
| 1657 |
+
new_param = trainer.model.get_parameter(n)
|
| 1658 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1659 |
+
|
| 1660 |
+
@pytest.mark.parametrize(
|
| 1661 |
+
"model_id",
|
| 1662 |
+
[
|
| 1663 |
+
"trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 1664 |
+
],
|
| 1665 |
+
)
|
| 1666 |
+
def test_train_vlm_beta_non_zero(self, model_id):
|
| 1667 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train")
|
| 1668 |
+
|
| 1669 |
+
def reward_func(completions, **kwargs):
|
| 1670 |
+
"""Reward function that rewards longer completions."""
|
| 1671 |
+
return [float(len(completion[0]["content"])) for completion in completions]
|
| 1672 |
+
|
| 1673 |
+
training_args = RLOOConfig(
|
| 1674 |
+
output_dir=self.tmp_dir,
|
| 1675 |
+
beta=0.1, # set beta to non-zero value to test the case where the reference model is used
|
| 1676 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1677 |
+
per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 1678 |
+
num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM
|
| 1679 |
+
# note: num_generations=2 is only suitable for CI testing; production training should use more generations
|
| 1680 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1681 |
+
report_to="none",
|
| 1682 |
+
)
|
| 1683 |
+
trainer = RLOOTrainer(
|
| 1684 |
+
model=model_id,
|
| 1685 |
+
reward_funcs=reward_func,
|
| 1686 |
+
args=training_args,
|
| 1687 |
+
train_dataset=dataset,
|
| 1688 |
+
)
|
| 1689 |
+
|
| 1690 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1691 |
+
|
| 1692 |
+
trainer.train()
|
| 1693 |
+
|
| 1694 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1695 |
+
|
| 1696 |
+
# Check that the params have changed
|
| 1697 |
+
for n, param in previous_trainable_params.items():
|
| 1698 |
+
new_param = trainer.model.get_parameter(n)
|
| 1699 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1700 |
+
|
| 1701 |
+
@pytest.mark.parametrize(
|
| 1702 |
+
"model_id",
|
| 1703 |
+
[
|
| 1704 |
+
"trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 1705 |
+
],
|
| 1706 |
+
)
|
| 1707 |
+
@require_peft
|
| 1708 |
+
def test_train_vlm_peft(self, model_id):
|
| 1709 |
+
model = AutoModelForImageTextToText.from_pretrained(model_id, dtype="float32")
|
| 1710 |
+
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
|
| 1711 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train")
|
| 1712 |
+
|
| 1713 |
+
def reward_func(completions, **kwargs):
|
| 1714 |
+
"""Reward function that rewards longer completions."""
|
| 1715 |
+
return [float(len(completion[0]["content"])) for completion in completions]
|
| 1716 |
+
|
| 1717 |
+
training_args = RLOOConfig(
|
| 1718 |
+
output_dir=self.tmp_dir,
|
| 1719 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1720 |
+
per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 1721 |
+
num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM
|
| 1722 |
+
# note: num_generations=2 is only suitable for CI testing; production training should use more generations
|
| 1723 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1724 |
+
report_to="none",
|
| 1725 |
+
)
|
| 1726 |
+
trainer = RLOOTrainer(
|
| 1727 |
+
model=model,
|
| 1728 |
+
reward_funcs=reward_func,
|
| 1729 |
+
args=training_args,
|
| 1730 |
+
train_dataset=dataset,
|
| 1731 |
+
peft_config=LoraConfig(target_modules=["q_proj", "v_proj"]),
|
| 1732 |
+
)
|
| 1733 |
+
|
| 1734 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1735 |
+
|
| 1736 |
+
trainer.train()
|
| 1737 |
+
|
| 1738 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1739 |
+
|
| 1740 |
+
# Check that the peft params have changed and the base model params have not changed
|
| 1741 |
+
for n, param in previous_trainable_params.items():
|
| 1742 |
+
new_param = trainer.model.get_parameter(n)
|
| 1743 |
+
if n in base_param_names: # We expect the base model params to be the same
|
| 1744 |
+
torch.testing.assert_close(param, new_param, msg=f"Parameter {n} has changed.")
|
| 1745 |
+
elif "base_layer" not in n: # We expect the peft params to be different (except for the base layer)
|
| 1746 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1747 |
+
|
| 1748 |
+
@pytest.mark.parametrize(
|
| 1749 |
+
"model_id",
|
| 1750 |
+
[
|
| 1751 |
+
"trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 1752 |
+
"trl-internal-testing/tiny-Gemma3ForConditionalGeneration",
|
| 1753 |
+
pytest.param(
|
| 1754 |
+
"trl-internal-testing/tiny-Gemma4ForConditionalGeneration",
|
| 1755 |
+
marks=pytest.mark.skipif(
|
| 1756 |
+
Version(transformers.__version__) < Version("5.5.0"),
|
| 1757 |
+
reason="Gemma4 models were introduced in transformers-5.5.0",
|
| 1758 |
+
),
|
| 1759 |
+
),
|
| 1760 |
+
],
|
| 1761 |
+
)
|
| 1762 |
+
@require_vllm
|
| 1763 |
+
@pytest.mark.skip(reason="We should add a mock for the vLLM server.")
|
| 1764 |
+
def test_train_vlm_and_vllm(self, model_id) -> None:
|
| 1765 |
+
dataset = load_dataset("trl-internal-testing/zen-image", "conversational_prompt_only", split="train")
|
| 1766 |
+
|
| 1767 |
+
def reward_func(completions, **kwargs):
|
| 1768 |
+
"""Reward function that rewards longer completions."""
|
| 1769 |
+
return [float(len(completion[0]["content"])) for completion in completions]
|
| 1770 |
+
|
| 1771 |
+
training_args = RLOOConfig(
|
| 1772 |
+
output_dir=self.tmp_dir,
|
| 1773 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1774 |
+
per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 1775 |
+
num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM
|
| 1776 |
+
# note: num_generations=2 is only suitable for CI testing; production training should use more generations
|
| 1777 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1778 |
+
report_to="none",
|
| 1779 |
+
use_vllm=True,
|
| 1780 |
+
vllm_mode="server",
|
| 1781 |
+
)
|
| 1782 |
+
trainer = RLOOTrainer(
|
| 1783 |
+
model=model_id,
|
| 1784 |
+
reward_funcs=reward_func,
|
| 1785 |
+
args=training_args,
|
| 1786 |
+
train_dataset=dataset,
|
| 1787 |
+
)
|
| 1788 |
+
|
| 1789 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1790 |
+
|
| 1791 |
+
trainer.train()
|
| 1792 |
+
|
| 1793 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1794 |
+
|
| 1795 |
+
for n, param in previous_trainable_params.items():
|
| 1796 |
+
new_param = trainer.model.get_parameter(n)
|
| 1797 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
| 1798 |
+
|
| 1799 |
+
@pytest.mark.parametrize(
|
| 1800 |
+
"model_id",
|
| 1801 |
+
[
|
| 1802 |
+
"trl-internal-testing/tiny-Qwen2_5_VLForConditionalGeneration",
|
| 1803 |
+
],
|
| 1804 |
+
)
|
| 1805 |
+
def test_train_vlm_multi_image(self, model_id):
|
| 1806 |
+
dataset = load_dataset("trl-internal-testing/zen-multi-image", "conversational_prompt_only", split="train")
|
| 1807 |
+
|
| 1808 |
+
def reward_func(completions, **kwargs):
|
| 1809 |
+
"""Reward function that rewards longer completions."""
|
| 1810 |
+
return [float(len(completion[0]["content"])) for completion in completions]
|
| 1811 |
+
|
| 1812 |
+
training_args = RLOOConfig(
|
| 1813 |
+
output_dir=self.tmp_dir,
|
| 1814 |
+
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
|
| 1815 |
+
per_device_train_batch_size=2, # VLM training is memory intensive, reduce batch size to avoid OOM
|
| 1816 |
+
num_generations=2, # VLM training is memory intensive, reduce num_generations to avoid OOM
|
| 1817 |
+
# note: num_generations=2 is only suitable for CI testing; production training should use more generations
|
| 1818 |
+
max_completion_length=8, # reduce the completion length to reduce memory usage
|
| 1819 |
+
report_to="none",
|
| 1820 |
+
)
|
| 1821 |
+
trainer = RLOOTrainer(
|
| 1822 |
+
model=model_id,
|
| 1823 |
+
reward_funcs=reward_func,
|
| 1824 |
+
args=training_args,
|
| 1825 |
+
train_dataset=dataset,
|
| 1826 |
+
)
|
| 1827 |
+
|
| 1828 |
+
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
|
| 1829 |
+
|
| 1830 |
+
trainer.train()
|
| 1831 |
+
|
| 1832 |
+
assert trainer.state.log_history[-1]["train_loss"] is not None
|
| 1833 |
+
|
| 1834 |
+
for n, param in previous_trainable_params.items():
|
| 1835 |
+
new_param = trainer.model.get_parameter(n)
|
| 1836 |
+
assert not torch.equal(param, new_param), f"Parameter {n} has not changed."
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_sft_trainer.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-b71e9e0a47b6/tests/source/tests/test_skills.py
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-b71e9e0a47b6/tests/source/tests/test_skills_cli.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-b71e9e0a47b6/tests/source/tests/test_utils.py
ADDED
|
@@ -0,0 +1,1380 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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020-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-b71e9e0a47b6/tests/source/tests/test_vllm_client_server.py
ADDED
|
@@ -0,0 +1,1036 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-b71e9e0a47b6/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-b71e9e0a47b6/tests/source/tests/testing_utils.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_harbor_available,
|
| 35 |
+
is_jmespath_available,
|
| 36 |
+
is_joblib_available,
|
| 37 |
+
is_liger_kernel_available,
|
| 38 |
+
is_math_verify_available,
|
| 39 |
+
is_mergekit_available,
|
| 40 |
+
is_openreward_available,
|
| 41 |
+
is_vllm_available,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
require_bitsandbytes = pytest.mark.skipif(not is_bitsandbytes_available(), reason="test requires bitsandbytes")
|
| 46 |
+
require_comet = pytest.mark.skipif(not is_comet_available(), reason="test requires comet_ml")
|
| 47 |
+
require_harbor = pytest.mark.skipif(not is_harbor_available(), reason="test requires harbor")
|
| 48 |
+
require_jmespath = pytest.mark.skipif(not is_jmespath_available(), reason="test requires jmespath")
|
| 49 |
+
require_kernels = pytest.mark.skipif(not is_kernels_available(), reason="test requires kernels")
|
| 50 |
+
require_liger_kernel = pytest.mark.skipif(not is_liger_kernel_available(), reason="test requires liger-kernel")
|
| 51 |
+
require_math_latex = pytest.mark.skipif(not is_math_verify_available(), reason="test requires math_verify")
|
| 52 |
+
require_mergekit = pytest.mark.skipif(not is_mergekit_available(), reason="test requires mergekit")
|
| 53 |
+
require_openreward = pytest.mark.skipif(not is_openreward_available(), reason="test requires openreward")
|
| 54 |
+
require_peft = pytest.mark.skipif(not is_peft_available(), reason="test requires peft")
|
| 55 |
+
require_rich = pytest.mark.skipif(not is_rich_available(), reason="test requires rich")
|
| 56 |
+
require_sklearn = pytest.mark.skipif(
|
| 57 |
+
not (is_sklearn_available() and is_joblib_available()), reason="test requires sklearn"
|
| 58 |
+
)
|
| 59 |
+
require_torch_accelerator = pytest.mark.skipif(
|
| 60 |
+
torch_device is None or torch_device == "cpu", reason="test requires accelerator"
|
| 61 |
+
)
|
| 62 |
+
require_torch_multi_accelerator = pytest.mark.skipif(
|
| 63 |
+
not is_torch_available() or backend_device_count(torch_device) <= 1, reason="test requires multiple accelerators"
|
| 64 |
+
)
|
| 65 |
+
require_vision = pytest.mark.skipif(not is_vision_available(), reason="test requires vision")
|
| 66 |
+
require_vllm = pytest.mark.skipif(not is_vllm_available(), reason="test requires vllm")
|
| 67 |
+
require_wandb = pytest.mark.skipif(not is_wandb_available(), reason="test requires wandb")
|
| 68 |
+
require_no_wandb = pytest.mark.skipif(is_wandb_available(), reason="test requires no wandb")
|
| 69 |
+
require_3_accelerators = pytest.mark.skipif(
|
| 70 |
+
not (getattr(torch, torch_device, torch.cuda).device_count() >= 3),
|
| 71 |
+
reason=f"test requires at least 3 {torch_device}s",
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def is_bitsandbytes_multi_backend_available() -> bool:
|
| 76 |
+
if is_bitsandbytes_available():
|
| 77 |
+
import bitsandbytes as bnb
|
| 78 |
+
|
| 79 |
+
return "multi_backend" in getattr(bnb, "features", set())
|
| 80 |
+
return False
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# Function ported from transformers.testing_utils before transformers#41283
|
| 84 |
+
require_torch_gpu_if_bnb_not_multi_backend_enabled = pytest.mark.skipif(
|
| 85 |
+
not is_bitsandbytes_multi_backend_available() and not torch_device == "cuda",
|
| 86 |
+
reason="test requires bitsandbytes multi-backend enabled or 'cuda' torch device",
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def is_ampere_or_newer(device_index=0):
|
| 91 |
+
if not torch.cuda.is_available():
|
| 92 |
+
return False
|
| 93 |
+
|
| 94 |
+
# "Ampere" is an NVIDIA architecture; an AMD (ROCm) GPU is never Ampere. On ROCm,
|
| 95 |
+
# torch.cuda.get_device_capability returns the gfx version, which would spuriously compare >= (8, 0).
|
| 96 |
+
if torch.version.hip is not None:
|
| 97 |
+
return False
|
| 98 |
+
|
| 99 |
+
major, minor = torch.cuda.get_device_capability(device_index)
|
| 100 |
+
# Ampere starts at compute capability 8.0 (e.g., A100 = 8.0, RTX 30xx = 8.6)
|
| 101 |
+
return (major, minor) >= (8, 0)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class TrlTestCase:
|
| 105 |
+
@pytest.fixture(autouse=True)
|
| 106 |
+
def set_tmp_dir(self, tmp_path):
|
| 107 |
+
self.tmp_dir = str(tmp_path)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def ignore_warnings(message: str = None, category: type[Warning] = Warning) -> Callable:
|
| 111 |
+
"""
|
| 112 |
+
Decorator to ignore warnings with a specific message and/or category.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
message (`str`, *optional*):
|
| 116 |
+
Regex pattern for the warning message to ignore. If `None`, all messages are ignored.
|
| 117 |
+
category (`type[Warning]`, *optional*, defaults to `Warning`):
|
| 118 |
+
Warning class to ignore. Defaults to `Warning`, which ignores all warnings.
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
def decorator(test_func):
|
| 122 |
+
@functools.wraps(test_func)
|
| 123 |
+
def wrapper(*args, **kwargs):
|
| 124 |
+
with warnings.catch_warnings():
|
| 125 |
+
warnings.filterwarnings("ignore", message=message, category=category)
|
| 126 |
+
return test_func(*args, **kwargs)
|
| 127 |
+
|
| 128 |
+
return wrapper
|
| 129 |
+
|
| 130 |
+
return decorator
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def kill_process(process):
|
| 134 |
+
parent = psutil.Process(process.pid)
|
| 135 |
+
children = parent.children(recursive=True)
|
| 136 |
+
for child in children:
|
| 137 |
+
try:
|
| 138 |
+
child.send_signal(signal.SIGTERM)
|
| 139 |
+
child.wait(timeout=5)
|
| 140 |
+
except psutil.TimeoutExpired:
|
| 141 |
+
child.kill()
|
| 142 |
+
except psutil.NoSuchProcess:
|
| 143 |
+
pass
|
| 144 |
+
try:
|
| 145 |
+
process.terminate()
|
| 146 |
+
process.wait(timeout=5)
|
| 147 |
+
except psutil.TimeoutExpired:
|
| 148 |
+
process.kill()
|
| 149 |
+
except psutil.NoSuchProcess:
|
| 150 |
+
pass
|
tasks/tasksmith-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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
|