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

Stage Harbor release files 4001-4500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_gemma3.py +69 -0
  2. tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_gpt_oss.py +92 -0
  3. tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_nemotron_3.py +116 -0
  4. tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_tiny_aya_tool_calling.py +164 -0
  5. tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_video_llm.py +248 -0
  6. tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_vlm.py +117 -0
  7. tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_vlm_gemma3.py +189 -0
  8. tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/tiny_aya_chat_template.jinja +66 -0
  9. tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/xpo.py +132 -0
  10. tasks/tasksmith-0ea2241cceeb/environment/source/pyproject.toml +201 -0
  11. tasks/tasksmith-0ea2241cceeb/environment/source/scripts/add_copyrights.py +92 -0
  12. tasks/tasksmith-0ea2241cceeb/environment/source/scripts/generate_harmony_dataset.py +263 -0
  13. tasks/tasksmith-0ea2241cceeb/environment/source/scripts/generate_tiny_models.py +434 -0
  14. tasks/tasksmith-0ea2241cceeb/environment/source/scripts/generate_toolcall_dataset.py +340 -0
  15. tasks/tasksmith-0ea2241cceeb/environment/source/scripts/generate_zen_dataset.py +660 -0
  16. tasks/tasksmith-0ea2241cceeb/environment/source/scripts/generate_zen_image_dataset.py +346 -0
  17. tasks/tasksmith-0ea2241cceeb/environment/source/scripts/generate_zen_multi_image_dataset.py +243 -0
  18. tasks/tasksmith-0ea2241cceeb/environment/source/scripts/log_reports.py +169 -0
  19. tasks/tasksmith-0ea2241cceeb/environment/source/trl.egg-info/PKG-INFO +295 -0
  20. tasks/tasksmith-0ea2241cceeb/environment/source/trl.egg-info/SOURCES.txt +178 -0
  21. tasks/tasksmith-0ea2241cceeb/environment/source/trl.egg-info/dependency_links.txt +1 -0
  22. tasks/tasksmith-0ea2241cceeb/environment/source/trl.egg-info/entry_points.txt +2 -0
  23. tasks/tasksmith-0ea2241cceeb/environment/source/trl.egg-info/requires.txt +82 -0
  24. tasks/tasksmith-0ea2241cceeb/environment/source/trl.egg-info/top_level.txt +1 -0
  25. tasks/tasksmith-0ea2241cceeb/environment/source/trl/__init__.py +132 -0
  26. tasks/tasksmith-0ea2241cceeb/environment/source/trl/_compat.py +250 -0
  27. tasks/tasksmith-0ea2241cceeb/environment/source/trl/_lazy_module.py +79 -0
  28. tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/fsdp1.yaml +28 -0
  29. tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/fsdp2.yaml +25 -0
  30. tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/multi_gpu.yaml +16 -0
  31. tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/single_gpu.yaml +16 -0
  32. tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/zero1.yaml +20 -0
  33. tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/zero2.yaml +21 -0
  34. tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/zero3.yaml +22 -0
  35. tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_template_utils.py +532 -0
  36. tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/README.md +65 -0
  37. tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/gptoss.jinja +331 -0
  38. tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/gptoss_training.jinja +338 -0
  39. tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/qwen3.jinja +89 -0
  40. tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/qwen3_5_2b_and_below.jinja +154 -0
  41. tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/qwen3_5_4b_and_above.jinja +154 -0
  42. tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/qwen3_training.jinja +93 -0
  43. tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/__init__.py +18 -0
  44. tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/accelerate_config.py +47 -0
  45. tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/accelerate_launcher.py +47 -0
  46. tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/commands/__init__.py +37 -0
  47. tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/commands/base.py +62 -0
  48. tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/commands/env.py +33 -0
  49. tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/commands/skills.py +42 -0
  50. tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/commands/training.py +72 -0
tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_gemma3.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "trl",
18
+ # "Pillow",
19
+ # "trackio",
20
+ # "kernels",
21
+ # ]
22
+ # ///
23
+
24
+ """
25
+ Train Gemma-3 on the Codeforces COTS dataset.
26
+
27
+ accelerate launch --config_file examples/accelerate_configs/deepspeed_zero3.yaml examples/scripts/sft_gemma3.py
28
+ """
29
+
30
+ from datasets import load_dataset
31
+ from transformers import AutoModelForImageTextToText
32
+
33
+ from trl import SFTConfig, SFTTrainer
34
+
35
+
36
+ def main():
37
+ # Load dataset
38
+ train_dataset = load_dataset("open-r1/codeforces-cots", split="train")
39
+ train_dataset = train_dataset.remove_columns("prompt")
40
+
41
+ # Load model
42
+ model_id = "google/gemma-3-12b-it"
43
+ model = AutoModelForImageTextToText.from_pretrained(model_id, attn_implementation="eager")
44
+
45
+ # Train model
46
+ training_args = SFTConfig(
47
+ output_dir=f"{model_id}-codeforces-SFT",
48
+ bf16=True,
49
+ use_liger_kernel=True,
50
+ max_length=8192,
51
+ per_device_train_batch_size=1,
52
+ gradient_accumulation_steps=8,
53
+ dataset_num_proc=32,
54
+ num_train_epochs=1,
55
+ )
56
+
57
+ trainer = SFTTrainer(
58
+ args=training_args,
59
+ model=model,
60
+ train_dataset=train_dataset,
61
+ )
62
+ trainer.train()
63
+
64
+ # Push to hub
65
+ trainer.push_to_hub(dataset_name="open-r1/codeforces-cots")
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()
tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_gpt_oss.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "trl",
18
+ # "kernels",
19
+ # "trackio",
20
+ # "kernels",
21
+ # ]
22
+ # ///
23
+
24
+ """
25
+ pip install –-upgrade kernels
26
+
27
+ Example:
28
+
29
+ accelerate launch \
30
+ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \
31
+ examples/scripts/sft_gpt_oss.py \
32
+ --dtype bfloat16 \
33
+ --model_name_or_path openai/gpt-oss-20b \
34
+ --packing \
35
+ --run_name 20b-full-eager \
36
+ --attn_implementation kernels-community/vllm-flash-attn3 \
37
+ --dataset_num_proc 12 \
38
+ --dataset_name HuggingFaceH4/Multilingual-Thinking \
39
+ --max_length 4096 \
40
+ --per_device_train_batch_size 2 \
41
+ --num_train_epochs 1 \
42
+ --logging_steps 1 \
43
+ --warmup_steps 0.03 \
44
+ --lr_scheduler_type cosine_with_min_lr \
45
+ --lr_scheduler_kwargs '{"min_lr_rate": 0.1}' \
46
+ --output_dir gpt-oss-20b-multilingual-reasoner \
47
+ --report_to trackio \
48
+ --seed 42
49
+ """
50
+
51
+ from datasets import load_dataset
52
+ from transformers import AutoModelForCausalLM, Mxfp4Config
53
+
54
+ from trl import ModelConfig, ScriptArguments, SFTConfig, SFTTrainer, TrlParser, get_peft_config
55
+
56
+
57
+ def main(script_args, training_args, model_args):
58
+ # Load model
59
+ quantization_config = Mxfp4Config(dequantize=True)
60
+ model_kwargs = dict(
61
+ revision=model_args.model_revision,
62
+ trust_remote_code=model_args.trust_remote_code,
63
+ attn_implementation=model_args.attn_implementation,
64
+ dtype=model_args.dtype,
65
+ use_cache=False if training_args.gradient_checkpointing else True,
66
+ quantization_config=quantization_config,
67
+ )
68
+
69
+ model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
70
+
71
+ # Load dataset
72
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
73
+
74
+ # Train model
75
+ trainer = SFTTrainer(
76
+ model=model,
77
+ args=training_args,
78
+ train_dataset=dataset[script_args.dataset_train_split],
79
+ eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
80
+ peft_config=get_peft_config(model_args),
81
+ )
82
+
83
+ trainer.train()
84
+ trainer.save_model(training_args.output_dir)
85
+ if training_args.push_to_hub:
86
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
87
+
88
+
89
+ if __name__ == "__main__":
90
+ parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig))
91
+ script_args, training_args, model_args, _ = parser.parse_args_and_config(return_remaining_strings=True)
92
+ main(script_args, training_args, model_args)
tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_nemotron_3.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "trl[peft,quantization]",
18
+ # "transformers>=5.3.0",
19
+ # "trackio",
20
+ # "mamba_ssm==2.2.5",
21
+ # "causal_conv1d==1.5.2",
22
+ # ]
23
+ # ///
24
+
25
+ """
26
+ Fine-tune NVIDIA Nemotron 3 models with SFT.
27
+
28
+ Prerequisites:
29
+
30
+ pip install "transformers>=5.3.0"
31
+ pip install --no-build-isolation mamba_ssm==2.2.5
32
+ pip install --no-build-isolation causal_conv1d==1.5.2
33
+
34
+ Example:
35
+
36
+ accelerate launch \
37
+ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \
38
+ examples/scripts/sft_nemotron_3.py \
39
+ --dtype bfloat16 \
40
+ --model_name_or_path nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16 \
41
+ --attn_implementation eager \
42
+ --dataset_name HuggingFaceH4/Multilingual-Thinking \
43
+ --max_length 128 \
44
+ --per_device_train_batch_size 1 \
45
+ --gradient_accumulation_steps 4 \
46
+ --num_train_epochs 1 \
47
+ --learning_rate 2e-4 \
48
+ --optim paged_adamw_8bit \
49
+ --logging_steps 10 \
50
+ --output_dir nemotron-3-sft \
51
+ --report_to trackio \
52
+ --use_peft \
53
+ --lora_r 8 \
54
+ --lora_alpha 16 \
55
+ --lora_target_modules q_proj k_proj v_proj o_proj gate_proj up_proj down_proj
56
+ """
57
+
58
+ from datasets import load_dataset
59
+ from transformers import AutoModelForCausalLM
60
+
61
+ from trl import ModelConfig, ScriptArguments, SFTConfig, SFTTrainer, TrlParser, get_peft_config
62
+
63
+
64
+ def main(script_args, training_args, model_args):
65
+ # NemotronH does not support gradient checkpointing
66
+ training_args.gradient_checkpointing = False
67
+
68
+ # Load model
69
+ model_kwargs = dict(
70
+ revision=model_args.model_revision,
71
+ attn_implementation=model_args.attn_implementation,
72
+ dtype=model_args.dtype,
73
+ )
74
+ model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
75
+
76
+ # Load dataset
77
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
78
+
79
+ # Merge thinking into message content using <think> tags and remove extra columns
80
+ def merge_thinking_and_remove_key(example):
81
+ new_messages = []
82
+ for msg in example["messages"]:
83
+ content = msg["content"]
84
+ thinking = msg.get("thinking")
85
+ if thinking and isinstance(thinking, str) and thinking.strip():
86
+ content = f"<think>\n{thinking}\n</think>\n{content}"
87
+ new_messages.append({"role": msg["role"], "content": content})
88
+ example["messages"] = new_messages
89
+ return example
90
+
91
+ dataset = dataset.map(merge_thinking_and_remove_key)
92
+
93
+ # Prepare eval dataset if needed
94
+ eval_dataset = None
95
+ if training_args.eval_strategy != "no" and script_args.dataset_test_split in dataset:
96
+ eval_dataset = dataset[script_args.dataset_test_split]
97
+
98
+ # Train model
99
+ trainer = SFTTrainer(
100
+ model=model,
101
+ args=training_args,
102
+ train_dataset=dataset[script_args.dataset_train_split],
103
+ eval_dataset=eval_dataset,
104
+ peft_config=get_peft_config(model_args),
105
+ )
106
+
107
+ trainer.train()
108
+ trainer.save_model(training_args.output_dir)
109
+ if training_args.push_to_hub:
110
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
111
+
112
+
113
+ if __name__ == "__main__":
114
+ parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig))
115
+ script_args, training_args, model_args, _ = parser.parse_args_and_config(return_remaining_strings=True)
116
+ main(script_args, training_args, model_args)
tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_tiny_aya_tool_calling.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
+ # /// script
16
+ # dependencies = [
17
+ # "trl[peft]",
18
+ # "bitsandbytes",
19
+ # "liger-kernel",
20
+ # "trackio",
21
+ # ]
22
+ # ///
23
+
24
+ """
25
+ Teach tool calling to CohereLabs/tiny-aya-global using SFT with QLoRA on the bebechien/SimpleToolCalling dataset.
26
+
27
+ The model used in this script does not have native tool-calling support. We extend its existing Jinja2 chat template to
28
+ serialize tool schemas into the system preamble and render tool calls as structured <tool_call> XML inside the model's
29
+ native <|START_RESPONSE|> / <|END_RESPONSE|> delimiters. The modified template is saved with the tokenizer, so
30
+ inference only requires loading the tokenizer from the output directory and calling apply_chat_template with
31
+ tools=TOOLS — no manual system-prompt construction needed.
32
+
33
+ Example:
34
+
35
+ python examples/scripts/sft_tiny_aya_tool_calling.py
36
+ """
37
+
38
+ import json
39
+ from pathlib import Path
40
+
41
+ import torch
42
+ from datasets import load_dataset
43
+ from peft import LoraConfig
44
+ from transformers import AutoModelForCausalLM, BitsAndBytesConfig
45
+
46
+ from trl import SFTConfig, SFTTrainer
47
+
48
+
49
+ # These are the tool schemas that are used in the dataset
50
+ TOOLS = [
51
+ {
52
+ "type": "function",
53
+ "function": {
54
+ "name": "search_knowledge_base",
55
+ "description": "Search internal company documents, policies and project data.",
56
+ "parameters": {
57
+ "type": "object",
58
+ "properties": {"query": {"type": "string", "description": "query string"}},
59
+ "required": ["query"],
60
+ },
61
+ "return": {"type": "string"},
62
+ },
63
+ },
64
+ {
65
+ "type": "function",
66
+ "function": {
67
+ "name": "search_google",
68
+ "description": "Search public information.",
69
+ "parameters": {
70
+ "type": "object",
71
+ "properties": {"query": {"type": "string", "description": "query string"}},
72
+ "required": ["query"],
73
+ },
74
+ "return": {"type": "string"},
75
+ },
76
+ },
77
+ ]
78
+
79
+
80
+ def create_conversation(sample):
81
+ return {
82
+ "prompt": [{"role": "user", "content": sample["user_content"]}],
83
+ "completion": [
84
+ {
85
+ "role": "assistant",
86
+ "tool_calls": [
87
+ {
88
+ "type": "function",
89
+ "function": {
90
+ "name": sample["tool_name"],
91
+ "arguments": json.loads(sample["tool_arguments"]),
92
+ },
93
+ }
94
+ ],
95
+ },
96
+ ],
97
+ "tools": TOOLS,
98
+ }
99
+
100
+
101
+ def main():
102
+ model_id = "CohereLabs/tiny-aya-global"
103
+ dataset_name = "bebechien/SimpleToolCalling"
104
+ output_dir = "tiny-aya-global-tool-calling-SFT"
105
+
106
+ # Load and format dataset
107
+ dataset = load_dataset(dataset_name, split="train")
108
+ dataset = dataset.map(create_conversation, remove_columns=dataset.features)
109
+ dataset = dataset.train_test_split(test_size=0.5, shuffle=True)
110
+
111
+ # Load model
112
+ model = AutoModelForCausalLM.from_pretrained(
113
+ model_id,
114
+ attn_implementation="sdpa",
115
+ dtype=torch.float16,
116
+ quantization_config=BitsAndBytesConfig(
117
+ load_in_4bit=True,
118
+ bnb_4bit_compute_dtype=torch.float16,
119
+ bnb_4bit_use_double_quant=True,
120
+ bnb_4bit_quant_type="nf4",
121
+ ),
122
+ )
123
+
124
+ # Configure LoRA
125
+ peft_config = LoraConfig(
126
+ r=32,
127
+ lora_alpha=32,
128
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
129
+ )
130
+
131
+ # Train
132
+ training_args = SFTConfig(
133
+ output_dir=output_dir,
134
+ per_device_train_batch_size=1,
135
+ gradient_accumulation_steps=4,
136
+ # Use the tool-aware chat template
137
+ chat_template_path=str(Path(__file__).parent / "tiny_aya_chat_template.jinja"),
138
+ warmup_steps=5,
139
+ learning_rate=2e-4,
140
+ optim="paged_adamw_8bit",
141
+ logging_steps=1,
142
+ report_to="trackio",
143
+ trackio_space_id=output_dir,
144
+ max_length=1024,
145
+ use_liger_kernel=True,
146
+ activation_offloading=True,
147
+ push_to_hub=True,
148
+ )
149
+
150
+ trainer = SFTTrainer(
151
+ model=model,
152
+ args=training_args,
153
+ train_dataset=dataset["train"],
154
+ peft_config=peft_config,
155
+ )
156
+ trainer.train()
157
+
158
+ # Save model and tokenizer (tokenizer carries the updated chat template)
159
+ trainer.save_model(output_dir)
160
+ trainer.push_to_hub(dataset_name=dataset_name)
161
+
162
+
163
+ if __name__ == "__main__":
164
+ main()
tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_video_llm.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "trl[peft]",
18
+ # "qwen-vl-utils",
19
+ # "torchvision",
20
+ # "bitsandbytes",
21
+ # "trackio",
22
+ # "kernels",
23
+ # ]
24
+ # ///
25
+
26
+ """
27
+ Example usage:
28
+ accelerate launch \
29
+ --config_file examples/accelerate_configs/deepspeed_zero2.yaml \
30
+ examples/scripts/sft_video_llm.py \
31
+ --dataset_name mfarre/simplevideoshorts \
32
+ --video_cache_dir "/optional/path/to/cache/" \
33
+ --model_name_or_path Qwen/Qwen2-VL-7B-Instruct \
34
+ --per_device_train_batch_size 1 \
35
+ --output_dir video-llm-output \
36
+ --tf32 True \
37
+ --gradient_accumulation_steps 4 \
38
+ --num_train_epochs 4 \
39
+ --optim adamw_torch_fused \
40
+ --log_level debug \
41
+ --log_level_replica debug \
42
+ --save_strategy steps \
43
+ --save_steps 300 \
44
+ --learning_rate 8e-5 \
45
+ --max_grad_norm 0.3 \
46
+ --warmup_steps 0.1 \
47
+ --lr_scheduler_type cosine \
48
+ --push_to_hub False \
49
+ --dtype bfloat16
50
+ """
51
+
52
+ import json
53
+ import os
54
+ import random
55
+ from dataclasses import dataclass, field
56
+ from typing import Any
57
+
58
+ import requests
59
+ import torch
60
+ from datasets import load_dataset
61
+ from peft import LoraConfig
62
+ from qwen_vl_utils import process_vision_info
63
+ from transformers import AutoModelForImageTextToText, AutoProcessor, BitsAndBytesConfig, Qwen2VLProcessor
64
+
65
+ from trl import ModelConfig, ScriptArguments, SFTConfig, SFTTrainer, TrlParser, get_kbit_device_map
66
+
67
+
68
+ def download_video(url: str, cache_dir: str) -> str:
69
+ """Download video if not already present locally."""
70
+ os.makedirs(cache_dir, exist_ok=True) # Create cache dir if it doesn't exist
71
+ filename = url.split("/")[-1]
72
+ local_path = os.path.join(cache_dir, filename)
73
+
74
+ if os.path.exists(local_path):
75
+ return local_path
76
+
77
+ try:
78
+ with requests.get(url, stream=True) as r:
79
+ r.raise_for_status()
80
+ with open(local_path, "wb") as f:
81
+ for chunk in r.iter_content(chunk_size=8192):
82
+ if chunk:
83
+ f.write(chunk)
84
+ return local_path
85
+ except requests.RequestException as e:
86
+ raise Exception(f"Failed to download video: {e}") from e
87
+
88
+
89
+ def prepare_dataset(example: dict[str, Any], cache_dir: str) -> dict[str, list[dict[str, Any]]]:
90
+ """Prepare dataset example for training."""
91
+ video_url = example["video_url"]
92
+ timecoded_cc = example["timecoded_cc"]
93
+ qa_pairs = json.loads(example["qa"])
94
+
95
+ system_message = "You are an expert in movie narrative analysis."
96
+ base_prompt = f"""Analyze the video and consider the following timecoded subtitles:
97
+
98
+ {timecoded_cc}
99
+
100
+ Based on this information, please answer the following questions:"""
101
+
102
+ selected_qa = random.sample(qa_pairs, 1)[0]
103
+
104
+ messages = [
105
+ {"role": "system", "content": [{"type": "text", "text": system_message}]},
106
+ {
107
+ "role": "user",
108
+ "content": [
109
+ {"type": "video", "video": download_video(video_url, cache_dir), "max_pixels": 360 * 420, "fps": 1.0},
110
+ {"type": "text", "text": f"{base_prompt}\n\nQuestion: {selected_qa['question']}"},
111
+ ],
112
+ },
113
+ {"role": "assistant", "content": [{"type": "text", "text": selected_qa["answer"]}]},
114
+ ]
115
+
116
+ return {"messages": messages}
117
+
118
+
119
+ def collate_fn(examples: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
120
+ """Collate batch of examples for training."""
121
+ texts = []
122
+ video_inputs = []
123
+
124
+ for i, example in enumerate(examples):
125
+ try:
126
+ video_path = next(
127
+ content["video"]
128
+ for message in example["messages"]
129
+ for content in message["content"]
130
+ if content.get("type") == "video"
131
+ )
132
+ print(f"Processing video: {os.path.basename(video_path)}")
133
+
134
+ texts.append(processor.apply_chat_template(example["messages"], tokenize=False))
135
+ video_input = process_vision_info(example["messages"])[1][0]
136
+ video_inputs.append(video_input)
137
+ except Exception as e:
138
+ raise ValueError(f"Failed to process example {i}: {e}") from e
139
+
140
+ inputs = processor(text=texts, videos=video_inputs, return_tensors="pt", padding=True)
141
+
142
+ labels = inputs["input_ids"].clone()
143
+ labels[labels == processor.tokenizer.pad_token_id] = -100
144
+
145
+ # Handle visual tokens based on processor type
146
+ visual_tokens = (
147
+ [151652, 151653, 151656]
148
+ if isinstance(processor, Qwen2VLProcessor)
149
+ else [processor.tokenizer.convert_tokens_to_ids(processor.image_token)]
150
+ )
151
+
152
+ for visual_token_id in visual_tokens:
153
+ labels[labels == visual_token_id] = -100
154
+
155
+ inputs["labels"] = labels
156
+ return inputs
157
+
158
+
159
+ @dataclass
160
+ class CustomScriptArguments(ScriptArguments):
161
+ r"""
162
+ Arguments for the script.
163
+
164
+ Args:
165
+ video_cache_dir (`str`, *optional*, defaults to `"/tmp/videos/"`):
166
+ Video cache directory.
167
+ """
168
+
169
+ video_cache_dir: str = field(default="/tmp/videos/", metadata={"help": "Video cache directory."})
170
+
171
+
172
+ if __name__ == "__main__":
173
+ # Parse arguments
174
+ parser = TrlParser((CustomScriptArguments, SFTConfig, ModelConfig))
175
+ script_args, training_args, model_args = parser.parse_args_and_config()
176
+
177
+ # Configure training args
178
+ training_args.remove_unused_columns = False
179
+
180
+ # Load dataset
181
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config, split="train")
182
+
183
+ # Setup model
184
+ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
185
+
186
+ # Quantization configuration for 4-bit training
187
+ bnb_config = BitsAndBytesConfig(
188
+ load_in_4bit=True,
189
+ bnb_4bit_use_double_quant=True,
190
+ bnb_4bit_quant_type="nf4",
191
+ bnb_4bit_compute_dtype=torch.bfloat16,
192
+ )
193
+
194
+ # Model initialization
195
+ model_kwargs = dict(
196
+ revision=model_args.model_revision,
197
+ trust_remote_code=model_args.trust_remote_code,
198
+ dtype=dtype,
199
+ device_map=get_kbit_device_map(),
200
+ quantization_config=bnb_config,
201
+ )
202
+
203
+ model = AutoModelForImageTextToText.from_pretrained(model_args.model_name_or_path, **model_kwargs)
204
+
205
+ peft_config = LoraConfig(
206
+ task_type="CAUSAL_LM",
207
+ r=16,
208
+ lora_alpha=16,
209
+ lora_dropout=0.1,
210
+ bias="none",
211
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
212
+ )
213
+
214
+ # Configure model modules for gradients
215
+ if training_args.gradient_checkpointing:
216
+ model.gradient_checkpointing_enable()
217
+ model.config.use_reentrant = False
218
+ model.enable_input_require_grads()
219
+
220
+ processor = AutoProcessor.from_pretrained(
221
+ model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code
222
+ )
223
+
224
+ # Prepare dataset
225
+ prepared_dataset = [prepare_dataset(example, script_args.video_cache_dir) for example in dataset]
226
+
227
+ # Initialize trainer
228
+ trainer = SFTTrainer(
229
+ model=model,
230
+ args=training_args,
231
+ train_dataset=prepared_dataset,
232
+ data_collator=collate_fn,
233
+ peft_config=peft_config,
234
+ processing_class=processor,
235
+ )
236
+
237
+ # Train model
238
+ trainer.train()
239
+
240
+ # Save final model
241
+ trainer.save_model(training_args.output_dir)
242
+ if training_args.push_to_hub:
243
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
244
+
245
+ # Cleanup
246
+ del model
247
+ del trainer
248
+ torch.cuda.empty_cache()
tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_vlm.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "trl[peft]",
18
+ # "Pillow>=9.4.0",
19
+ # "trackio",
20
+ # "kernels",
21
+ # ]
22
+ # ///
23
+
24
+ """
25
+ pip install pillow
26
+
27
+ # Tested on 8x H100 GPUs
28
+ accelerate launch \
29
+ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \
30
+ examples/scripts/sft_vlm.py \
31
+ --dataset_name HuggingFaceH4/llava-instruct-mix-vsft \
32
+ --model_name_or_path llava-hf/llava-1.5-7b-hf \
33
+ --gradient_accumulation_steps 8 \
34
+ --output_dir LLaVA-1.5-7B-SFT \
35
+ --dtype bfloat16
36
+
37
+ For LLaVA-NeXT, use:
38
+ --model_name_or_path llava-hf/llava-v1.6-mistral-7b-hf
39
+
40
+ For meta-llama/Llama-3.2-11B-Vision-Instruct, use:
41
+ --model_name_or_path meta-llama/Llama-3.2-11B-Vision-Instruct
42
+
43
+ accelerate launch \
44
+ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \
45
+ examples/scripts/sft_vlm.py \
46
+ --dataset_name HuggingFaceH4/llava-instruct-mix-vsft \
47
+ --model_name_or_path HuggingFaceTB/SmolVLM-Instruct \
48
+ --per_device_train_batch_size 1 \
49
+ --gradient_accumulation_steps 1 \
50
+ --output_dir SmolVLM-SFT \
51
+ --dtype bfloat16 \
52
+ --use_peft \
53
+ --lora_target_modules down_proj, o_proj, k_proj, q_proj, gate_proj, up_proj, v_proj
54
+ """
55
+
56
+ import torch
57
+ from datasets import load_dataset
58
+ from transformers import AutoModelForImageTextToText
59
+
60
+ from trl import (
61
+ ModelConfig,
62
+ ScriptArguments,
63
+ SFTConfig,
64
+ SFTTrainer,
65
+ TrlParser,
66
+ get_kbit_device_map,
67
+ get_peft_config,
68
+ get_quantization_config,
69
+ )
70
+
71
+
72
+ if __name__ == "__main__":
73
+ parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig))
74
+ script_args, training_args, model_args = parser.parse_args_and_config()
75
+ training_args.max_length = None
76
+
77
+ ################
78
+ # Model
79
+ ################
80
+ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
81
+ model_kwargs = dict(
82
+ revision=model_args.model_revision,
83
+ attn_implementation=model_args.attn_implementation,
84
+ dtype=dtype,
85
+ )
86
+ quantization_config = get_quantization_config(model_args)
87
+ if quantization_config is not None:
88
+ # Passing None would not be treated the same as omitting the argument, so we include it only when valid.
89
+ model_kwargs["device_map"] = get_kbit_device_map()
90
+ model_kwargs["quantization_config"] = quantization_config
91
+
92
+ model = AutoModelForImageTextToText.from_pretrained(
93
+ model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code, **model_kwargs
94
+ )
95
+
96
+ ################
97
+ # Dataset
98
+ ################
99
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
100
+
101
+ ################
102
+ # Training
103
+ ################
104
+ trainer = SFTTrainer(
105
+ model=model,
106
+ args=training_args,
107
+ train_dataset=dataset[script_args.dataset_train_split],
108
+ eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
109
+ peft_config=get_peft_config(model_args),
110
+ )
111
+
112
+ trainer.train()
113
+
114
+ # Save and push to hub
115
+ trainer.save_model(training_args.output_dir)
116
+ if training_args.push_to_hub:
117
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/sft_vlm_gemma3.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "trl[peft]",
18
+ # "Pillow>=9.4.0",
19
+ # "trackio",
20
+ # "kernels",
21
+ # ]
22
+ # ///
23
+
24
+ """
25
+ Train Gemma 3 on the HuggingFaceH4/llava-instruct-mix-vsft dataset (single-image).
26
+
27
+ accelerate launch \
28
+ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \
29
+ examples/scripts/sft_vlm_gemma3.py \
30
+ --dataset_name HuggingFaceH4/llava-instruct-mix-vsft \
31
+ --model_name_or_path google/gemma-3-4b-it \
32
+ --per_device_train_batch_size 1 \
33
+ --output_dir Gemma-3-4B-SFT-MMIU \
34
+ --dtype bfloat16 \
35
+ --use_peft \
36
+ --lora_target_modules all-linear \
37
+ --attn_implementation eager
38
+
39
+ Train Gemma 3 on the FanqingM/MMIU-Benchmark dataset (multi-image).
40
+
41
+ accelerate launch \
42
+ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \
43
+ examples/scripts/sft_vlm_gemma3.py \
44
+ --dataset_name FanqingM/MMIU-Benchmark \
45
+ --dataset_train_split test \
46
+ --model_name_or_path google/gemma-3-4b-it \
47
+ --per_device_train_batch_size 1 \
48
+ --output_dir Gemma-3-4B-SFT-MMIU \
49
+ --dtype bfloat16 \
50
+ --use_peft \
51
+ --lora_target_modules all-linear \
52
+ --attn_implementation eager
53
+ """
54
+
55
+ import io
56
+ import os
57
+ import zipfile
58
+
59
+ import torch
60
+ from datasets import DatasetDict, load_dataset
61
+ from huggingface_hub import hf_hub_download, list_repo_files
62
+ from PIL import Image
63
+ from transformers import AutoModelForImageTextToText
64
+
65
+ from trl import (
66
+ ModelConfig,
67
+ ScriptArguments,
68
+ SFTConfig,
69
+ SFTTrainer,
70
+ TrlParser,
71
+ get_kbit_device_map,
72
+ get_peft_config,
73
+ get_quantization_config,
74
+ )
75
+
76
+
77
+ # For multi-image example
78
+ def process_vision_info(messages: list[dict]) -> list[Image.Image]:
79
+ image_inputs = []
80
+ for msg in messages:
81
+ content = msg.get("content", [])
82
+ if not isinstance(content, list):
83
+ content = [content]
84
+
85
+ for element in content:
86
+ if isinstance(element, dict) and ("image" in element or element.get("type") == "image"):
87
+ if "image" in element:
88
+ image = element["image"]
89
+ else:
90
+ image = element
91
+ if image is not None:
92
+ image = Image.open(io.BytesIO(image["bytes"]))
93
+ image_inputs.append(image.convert("RGB"))
94
+ return image_inputs
95
+
96
+
97
+ def format_data(samples: dict[str, any]) -> dict[str, list]:
98
+ formatted_samples = {"messages": []}
99
+ for cont in range(len(samples["question"])):
100
+ images = []
101
+ for img_path in samples["input_image_path"][cont]:
102
+ try:
103
+ with open(img_path, "rb") as f:
104
+ img_bytes = f.read()
105
+ image = Image.open(io.BytesIO(img_bytes)).convert("RGB")
106
+ images.append({"type": "image", "image": image})
107
+ except Exception as e:
108
+ print(f"Error processing image {img_path}: {e}")
109
+ continue
110
+
111
+ formatted_samples["messages"].append(
112
+ [
113
+ {"role": "system", "content": [{"type": "text", "text": samples["context"][cont]}]},
114
+ {"role": "user", "content": images + [{"type": "text", "text": samples["question"][cont]}]},
115
+ {"role": "assistant", "content": [{"type": "text", "text": samples["output"][cont]}]},
116
+ ]
117
+ )
118
+ return formatted_samples
119
+
120
+
121
+ # For multi-image example
122
+ def prepare_dataset(dataset: DatasetDict, dataset_name: str) -> DatasetDict:
123
+ all_files = list_repo_files(dataset_name, repo_type="dataset")
124
+ zip_files = [f for f in all_files if f.endswith(".zip")]
125
+
126
+ for zip_filename in zip_files:
127
+ zip_path = hf_hub_download(repo_id=dataset_name, filename=zip_filename, repo_type="dataset")
128
+ extract_folder = zip_filename.replace(".zip", "")
129
+ os.makedirs(extract_folder, exist_ok=True)
130
+
131
+ with zipfile.ZipFile(zip_path, "r") as zip_ref:
132
+ zip_ref.extractall(extract_folder)
133
+
134
+ dataset = dataset.map(format_data, batched=True, batch_size=4, num_proc=16)
135
+ return dataset
136
+
137
+
138
+ def main():
139
+ parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig))
140
+ script_args, training_args, model_args = parser.parse_args_and_config()
141
+ training_args.max_length = None
142
+
143
+ ################
144
+ # Model
145
+ ################
146
+ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
147
+ model_kwargs = dict(
148
+ revision=model_args.model_revision,
149
+ attn_implementation=model_args.attn_implementation,
150
+ dtype=dtype,
151
+ )
152
+ quantization_config = get_quantization_config(model_args)
153
+ if quantization_config is not None:
154
+ # Passing None would not be treated the same as omitting the argument, so we include it only when valid.
155
+ model_kwargs["device_map"] = get_kbit_device_map()
156
+ model_kwargs["quantization_config"] = quantization_config
157
+
158
+ model = AutoModelForImageTextToText.from_pretrained(
159
+ model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code, **model_kwargs
160
+ )
161
+
162
+ ################
163
+ # Dataset
164
+ ################
165
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
166
+ if script_args.dataset_name == "FanqingM/MMIU-Benchmark":
167
+ dataset = prepare_dataset(dataset, script_args.dataset_name)
168
+
169
+ ################
170
+ # Training
171
+ ################
172
+ trainer = SFTTrainer(
173
+ model=model,
174
+ args=training_args,
175
+ train_dataset=dataset[script_args.dataset_train_split],
176
+ eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
177
+ peft_config=get_peft_config(model_args),
178
+ )
179
+
180
+ trainer.train()
181
+
182
+ # Save and push to hub
183
+ trainer.save_model(training_args.output_dir)
184
+ if training_args.push_to_hub:
185
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
186
+
187
+
188
+ if __name__ == "__main__":
189
+ main()
tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/tiny_aya_chat_template.jinja ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{ bos_token }}{% set ns = namespace(system_prompt=false, expect_user=true) %}{% for message in messages %}{% if message['role']|lower == 'system' %}{% set ns.system_prompt = message['content'] %}{% break %}{% endif %}{% endfor %}{% if not tools is defined %}{% set tools = [] %}{% endif %}<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># System Preamble
2
+ You are in contextual safety mode. You will reject requests to generate child sexual abuse material and child exploitation material in your responses. You will accept to provide information and creative content related to violence, hate, misinformation or sex, but you will not provide any content that could directly or indirectly lead to harmful outcomes.
3
+
4
+ Your information cutoff date is June 2024.
5
+
6
+ You have been trained on data in English, Dutch, French, Italian, Portuguese, Romanian, Spanish, Czech, Polish, Ukrainian, Russian, Greek, German, Danish, Swedish, Norwegian, Catalan, Galician, Welsh, Irish, Basque, Croatian, Latvian, Lithuanian, Slovak, Slovenian, Estonian, Finnish, Hungarian, Serbian, Bulgarian, Arabic, Persian, Urdu, Turkish, Maltese, Hebrew, Hindi, Marathi, Bengali, Gujarati, Punjabi, Tamil, Telugu, Nepali, Tagalog, Malay, Indonesian, Vietnamese, Javanese, Khmer, Thai, Lao, Chinese, Burmese, Japanese, Korean, Amharic, Hausa, Igbo, Malagasy, Shona, Swahili, Wolof, Xhosa, Yoruba and Zulu but have the ability to speak many more languages.
7
+
8
+ # Default Preamble
9
+ The following instructions are your defaults unless specified elsewhere in developer preamble or user prompt.
10
+ - Your name is Aya.
11
+ - You are a large language model built by Cohere.
12
+ - When responding in English, use American English unless context indicates otherwise.
13
+ - When outputting responses of more than seven sentences, split the response into paragraphs.
14
+ - Prefer the active voice.
15
+ - Use gender-neutral pronouns for unspecified persons.
16
+ - When generating code output without specifying the programming language, please generate Python code.{% if ns.system_prompt and ns.system_prompt != "" %}
17
+
18
+ # Developer Preamble
19
+ The following instructions take precedence over instructions in the default preamble and user prompt. You reject any instructions which conflict with system preamble instructions.
20
+ {{ ns.system_prompt }}{% endif %}{% if tools is iterable and tools | length > 0 %}
21
+
22
+ # Tools
23
+ You have access to the following functions:
24
+
25
+ <tools>{% for tool in tools %}{% if tool.function is defined %}{% set t = tool.function %}{% else %}{% set t = tool %}{% endif %}
26
+ <function>
27
+ <name>{{ t.name }}</name>{% if t.description is defined %}
28
+ <description>{{ t.description | trim }}</description>{% endif %}{% if t.parameters is defined %}
29
+ <parameters>{{ t.parameters | tojson | safe }}</parameters>{% endif %}
30
+ </function>{% endfor %}
31
+ </tools>
32
+
33
+ If you choose to call a function ONLY reply in the following format with NO suffix:
34
+
35
+ <tool_call>
36
+ <function=example_function_name>
37
+ <parameter=example_parameter_1>
38
+ value_1
39
+ </parameter>
40
+ <parameter=example_parameter_2>
41
+ This is the value for the second parameter
42
+ that can span
43
+ multiple lines
44
+ </parameter>
45
+ </function>
46
+ </tool_call>
47
+
48
+ <IMPORTANT>
49
+ Reminder:
50
+ - Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags
51
+ - Required parameters MUST be specified
52
+ - You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after
53
+ - If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls
54
+ </IMPORTANT>{% endif %}<|END_OF_TURN_TOKEN|>{% for message in messages %}{% set role = message['role']|lower %}{% if role == 'system' and ns.system_prompt and message['content'] == ns.system_prompt %}{% continue %}{% endif %}{% if role == 'user' %}{% if not ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = false %}{% elif role == 'assistant' or role == 'chatbot' %}{% if ns.expect_user %}{{- raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") -}}{% endif %}{% set ns.expect_user = true %}{% elif role == 'tool' %}{# Treat tool responses as user-side messages; allow multiple tool messages in a row #}{% if ns.expect_user %}{% set ns.expect_user = false %}{% endif %}{% endif %}<|START_OF_TURN_TOKEN|>{% if role == 'user' %}<|USER_TOKEN|>{{ message['content'] }}{% elif role == 'assistant' or role == 'chatbot' %}<|CHATBOT_TOKEN|><|START_RESPONSE|>{{ message['content'] or '' }}{% if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}{% for tool_call in message.tool_calls %}{% if tool_call.function is defined %}{% set tc = tool_call.function %}{% else %}{% set tc = tool_call %}{% endif %}
55
+ <tool_call>
56
+ <function={{ tc.name }}>
57
+ {% if tc.arguments is mapping %}{% for args_name, args_value in tc.arguments | items %}<parameter={{ args_name }}>
58
+ {%- set v = args_value if args_value is string else (args_value | tojson | safe) -%}{{ v }}
59
+ </parameter>
60
+ {% endfor %}{% elif tc.arguments is defined %}<arguments>
61
+ {{ tc.arguments }}
62
+ </arguments>
63
+ {% endif %}</function>
64
+ </tool_call>{% endfor %}{% endif %}<|END_RESPONSE|>{% elif role == 'tool' %}<|USER_TOKEN|><tool_response>
65
+ {{ message['content'] or '' }}
66
+ </tool_response>{% elif role == 'system' %}<|SYSTEM_TOKEN|>{{ message['content'] }}{% endif %}<|END_OF_TURN_TOKEN|>{% endfor %}{% if add_generation_prompt %}<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>{% endif %}
tasks/tasksmith-0ea2241cceeb/environment/source/examples/scripts/xpo.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
+ # /// script
16
+ # dependencies = [
17
+ # "trl",
18
+ # "trackio",
19
+ # "kernels",
20
+ # ]
21
+ # ///
22
+
23
+ """
24
+ Usage:
25
+
26
+ python examples/scripts/xpo.py \
27
+ --model_name_or_path trl-lib/pythia-1b-deduped-tldr-sft \
28
+ --reward_model_path trl-lib/pythia-1b-deduped-tldr-rm \
29
+ --dataset_name trl-lib/tldr \
30
+ --learning_rate 5.0e-7 \
31
+ --output_dir pythia-1b-tldr-xpo \
32
+ --per_device_train_batch_size 4 \
33
+ --gradient_accumulation_steps 32 \
34
+ --num_train_epochs 3 \
35
+ --max_new_tokens 64 \
36
+ --warmup_steps 0.1 \
37
+ --missing_eos_penalty 1.0 \
38
+ --push_to_hub
39
+ """
40
+
41
+ import torch
42
+ from datasets import load_dataset
43
+ from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer, GenerationConfig
44
+
45
+ from trl import (
46
+ LogCompletionsCallback,
47
+ ModelConfig,
48
+ ScriptArguments,
49
+ TrlParser,
50
+ get_kbit_device_map,
51
+ get_quantization_config,
52
+ )
53
+ from trl.experimental.judges import HfPairwiseJudge, OpenAIPairwiseJudge, PairRMJudge
54
+ from trl.experimental.xpo import XPOConfig, XPOTrainer
55
+
56
+
57
+ JUDGES = {"pair_rm": PairRMJudge, "openai": OpenAIPairwiseJudge, "hf": HfPairwiseJudge}
58
+
59
+
60
+ if __name__ == "__main__":
61
+ parser = TrlParser((ScriptArguments, XPOConfig, ModelConfig))
62
+ script_args, training_args, model_args = parser.parse_args_and_config()
63
+ training_args.gradient_checkpointing_kwargs = {"use_reentrant": True}
64
+
65
+ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
66
+ model_kwargs = dict(
67
+ revision=model_args.model_revision,
68
+ attn_implementation=model_args.attn_implementation,
69
+ dtype=dtype,
70
+ use_cache=False if training_args.gradient_checkpointing else True,
71
+ )
72
+ quantization_config = get_quantization_config(model_args)
73
+ if quantization_config is not None:
74
+ # Passing None would not be treated the same as omitting the argument, so we include it only when valid.
75
+ model_kwargs["device_map"] = get_kbit_device_map()
76
+ model_kwargs["quantization_config"] = quantization_config
77
+
78
+ model = AutoModelForCausalLM.from_pretrained(
79
+ model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code, **model_kwargs
80
+ )
81
+ ref_model = AutoModelForCausalLM.from_pretrained(
82
+ model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code, **model_kwargs
83
+ )
84
+
85
+ if training_args.reward_model_path is not None:
86
+ reward_model = AutoModelForSequenceClassification.from_pretrained(
87
+ training_args.reward_model_path,
88
+ num_labels=1,
89
+ trust_remote_code=model_args.trust_remote_code,
90
+ **model_kwargs,
91
+ )
92
+ else:
93
+ reward_model = None
94
+
95
+ if training_args.judge is not None:
96
+ judge_cls = JUDGES[training_args.judge]
97
+ judge = judge_cls()
98
+ else:
99
+ judge = None
100
+
101
+ tokenizer = AutoTokenizer.from_pretrained(
102
+ model_args.model_name_or_path, padding_side="left", trust_remote_code=model_args.trust_remote_code
103
+ )
104
+ if tokenizer.pad_token is None:
105
+ tokenizer.pad_token = tokenizer.eos_token
106
+
107
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
108
+
109
+ trainer = XPOTrainer(
110
+ model=model,
111
+ ref_model=ref_model,
112
+ reward_funcs=reward_model,
113
+ judge=judge,
114
+ args=training_args,
115
+ train_dataset=dataset[script_args.dataset_train_split],
116
+ eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
117
+ processing_class=tokenizer,
118
+ )
119
+
120
+ if training_args.eval_strategy != "no":
121
+ generation_config = GenerationConfig(
122
+ max_new_tokens=training_args.max_new_tokens, do_sample=True, temperature=training_args.temperature
123
+ )
124
+ completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8)
125
+ trainer.add_callback(completions_callback)
126
+
127
+ trainer.train()
128
+
129
+ # Save and push to hub
130
+ trainer.save_model(training_args.output_dir)
131
+ if training_args.push_to_hub:
132
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
tasks/tasksmith-0ea2241cceeb/environment/source/pyproject.toml ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools >= 77.0.3"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "trl"
7
+ description = "Train transformer language models with reinforcement learning."
8
+ authors = [
9
+ { name = "Leandro von Werra", email = "leandro.vonwerra@gmail.com" }
10
+ ]
11
+ readme = { file = "README.md", content-type = "text/markdown" }
12
+ license = "Apache-2.0"
13
+ license-files = ["LICENSE"]
14
+ keywords = [
15
+ "transformers", "huggingface", "language modeling", "post-training", "rlhf", "sft", "dpo", "grpo"
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 2 - Pre-Alpha",
19
+ "Intended Audience :: Developers",
20
+ "Intended Audience :: Science/Research",
21
+ "Natural Language :: English",
22
+ "Operating System :: OS Independent",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Programming Language :: Python :: 3.14"
29
+ ]
30
+ requires-python = ">=3.10"
31
+ dependencies = [
32
+ "accelerate>=1.4.0",
33
+ "datasets>=4.7.0", # Support Json type and on_mixed_types="use_json"
34
+ "jinja2",
35
+ "packaging>20.0",
36
+ "transformers>=4.56.2",
37
+ ]
38
+ dynamic = ["version"]
39
+
40
+ [project.urls]
41
+ Homepage = "https://github.com/huggingface/trl"
42
+
43
+ [project.scripts]
44
+ trl = "trl.cli:main"
45
+
46
+ [project.optional-dependencies]
47
+ bco = [
48
+ "scikit-learn",
49
+ "joblib"
50
+ ]
51
+ deepspeed = [
52
+ "deepspeed>=0.14.4",
53
+ "transformers!=5.1.0", # see transformers#43780
54
+ ]
55
+ judges = [
56
+ "openai>=1.23.2",
57
+ "llm-blender>=0.0.2",
58
+ "transformers<5.0.0", # see #4918
59
+ ]
60
+ kernels = [
61
+ "kernels"
62
+ ]
63
+ liger = [
64
+ "liger-kernel>=0.7.0"
65
+ ]
66
+ peft = [
67
+ "peft>=0.8.0"
68
+ ]
69
+ quality = [
70
+ "pre-commit",
71
+ "hf-doc-builder"
72
+ ]
73
+ quantization = [
74
+ "bitsandbytes"
75
+ ]
76
+ scikit = [
77
+ "scikit-learn"
78
+ ]
79
+ test = [
80
+ "pytest-cov",
81
+ "pytest-datadir>=1.7.0", # lazy datadirs
82
+ "pytest-rerunfailures==15.1",
83
+ "pytest-xdist",
84
+ "pytest"
85
+ ]
86
+ vllm = [
87
+ "vllm>=0.11.0,<=0.17.1",
88
+ "fastapi",
89
+ "pydantic",
90
+ "aiohttp>=3.13.3",
91
+ "requests",
92
+ "uvicorn"
93
+ ]
94
+ vlm = [
95
+ "Pillow",
96
+ "torchvision",
97
+ "num2words==0.5.14"
98
+ ]
99
+ math_verify = [
100
+ "math-verify>=0.5.2",
101
+ ]
102
+ dev = [
103
+ # bco
104
+ "scikit-learn",
105
+ "joblib",
106
+ # deepspeed
107
+ "deepspeed>=0.14.4",
108
+ # judges
109
+ "openai>=1.23.2",
110
+ "llm-blender>=0.0.2",
111
+ # kernels
112
+ "kernels",
113
+ # liger
114
+ "liger-kernel>=0.7.0",
115
+ # peft
116
+ "peft>=0.8.0",
117
+ # quality
118
+ "pre-commit",
119
+ "hf-doc-builder",
120
+ # quantization
121
+ "bitsandbytes",
122
+ # scikit: included in bco
123
+ # test
124
+ "pytest-cov",
125
+ "pytest-datadir>=1.7.0", # lazy datadirs
126
+ "pytest-rerunfailures==15.1",
127
+ "pytest-xdist",
128
+ "pytest",
129
+ # vllm: not included in dev by default due to CUDA error; see GH-4228
130
+ # vlm
131
+ "Pillow",
132
+ "torchvision",
133
+ "num2words==0.5.14",
134
+ # for response parsing (required for training with tools)
135
+ "jmespath",
136
+ ]
137
+
138
+ [tool.setuptools]
139
+ package-dir = {"trl" = "trl"}
140
+
141
+ [tool.setuptools.dynamic]
142
+ version = { file = "VERSION" }
143
+
144
+ [tool.coverage.run]
145
+ branch = true
146
+
147
+ [tool.ruff]
148
+ target-version = "py310"
149
+ line-length = 119
150
+ src = ["trl"]
151
+
152
+ [tool.ruff.lint]
153
+ ignore = [
154
+ "B028", # warning without explicit stacklevel
155
+ "C408", # dict() calls (stylistic)
156
+ "C901", # function complexity
157
+ "E501",
158
+ ]
159
+ extend-select = ["E", "F", "I", "W", "UP", "B", "T", "C"]
160
+
161
+ [tool.ruff.lint.per-file-ignores]
162
+ # Allow prints in auxiliary scripts
163
+ "examples/**.py" = ["T201"]
164
+ "scripts/**.py" = ["T201"]
165
+ "trl/cli/**.py" = ["T201"]
166
+ "trl/skills/cli.py" = ["T201"]
167
+ # Ignore import violations in all `__init__.py` files.
168
+ "__init__.py" = ["F401"]
169
+
170
+ [tool.ruff.lint.isort]
171
+ lines-after-imports = 2
172
+ known-first-party = ["trl"]
173
+
174
+ [tool.pytest.ini_options]
175
+ markers = [
176
+ "slow: marks tests as slow (deselect with '-m \"not slow\"')",
177
+ "low_priority: marks tests as low priority (deselect with '-m \"not low_priority\"')"
178
+ ]
179
+ norecursedirs = [
180
+ "tests/experimental",
181
+ ]
182
+ filterwarnings = [
183
+ # SWIG deprecations from SWIG-generated C/C++ extensions: sentencepiece
184
+ # Upstream issue: https://github.com/google/sentencepiece/issues/1150
185
+ "ignore:builtin type SwigPyPacked has no __module__ attribute:DeprecationWarning",
186
+ "ignore:builtin type SwigPyObject has no __module__ attribute:DeprecationWarning",
187
+ "ignore:builtin type swigvarlink has no __module__ attribute:DeprecationWarning",
188
+
189
+ # PyTorch JIT deprecations (upstream, not actionable in TRL)
190
+ # Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/7835
191
+ # Upstream PR: https://github.com/deepspeedai/DeepSpeed/pull/7840
192
+ # Upstream fix released in deepspeed v0.18.6: https://github.com/deepspeedai/DeepSpeed/releases/tag/v0.18.6
193
+ "ignore:`torch.jit.script_method` is deprecated:DeprecationWarning",
194
+ "ignore:`torch.jit.script` is deprecated:DeprecationWarning",
195
+
196
+ # PyTorch DataLoader pin_memory device argument deprecations
197
+ # Triggered internally by torch.utils.data, not by our code
198
+ # Upstream issue: https://github.com/pytorch/pytorch/issues/174546
199
+ "ignore:The argument 'device' of Tensor.pin_memory:DeprecationWarning",
200
+ "ignore:The argument 'device' of Tensor.is_pinned:DeprecationWarning",
201
+ ]
tasks/tasksmith-0ea2241cceeb/environment/source/scripts/add_copyrights.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import sys
18
+ from datetime import datetime
19
+
20
+
21
+ COPYRIGHT_HEADER = f"""# Copyright 2020-{datetime.now().year} The HuggingFace Team. All rights reserved.
22
+ #
23
+ # Licensed under the Apache License, Version 2.0 (the "License");
24
+ # you may not use this file except in compliance with the License.
25
+ # You may obtain a copy of the License at
26
+ #
27
+ # http://www.apache.org/licenses/LICENSE-2.0
28
+ #
29
+ # Unless required by applicable law or agreed to in writing, software
30
+ # distributed under the License is distributed on an "AS IS" BASIS,
31
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
32
+ # See the License for the specific language governing permissions and
33
+ # limitations under the License.
34
+ """
35
+
36
+
37
+ def get_tracked_python_files():
38
+ """Get a list of all tracked Python files using git."""
39
+ try:
40
+ # Get the list of all tracked files from Git
41
+ result = subprocess.run(["git", "ls-files"], stdout=subprocess.PIPE, text=True, check=True)
42
+ # Split the result by lines to get individual file paths
43
+ files = result.stdout.splitlines()
44
+ # Filter only Python files
45
+ py_files = [f for f in files if f.endswith(".py")]
46
+ return py_files
47
+ except subprocess.CalledProcessError as e:
48
+ print(f"Error fetching tracked files: {e}")
49
+ return []
50
+
51
+
52
+ def check_and_add_copyright(file_path):
53
+ """Check if the file contains a copyright notice, and add it if missing."""
54
+ if not os.path.isfile(file_path):
55
+ print(f"[SKIP] {file_path} does not exist.")
56
+ return
57
+
58
+ with open(file_path, encoding="utf-8") as f:
59
+ content = f.readlines()
60
+
61
+ # Check if the exact copyright header exists
62
+ if "".join(content).startswith(COPYRIGHT_HEADER):
63
+ return True
64
+
65
+ # If no copyright notice was found, prepend the header
66
+ print(f"[MODIFY] Adding copyright to {file_path}.")
67
+ with open(file_path, "w", encoding="utf-8") as f:
68
+ # Write the copyright header followed by the original content
69
+ f.write(COPYRIGHT_HEADER + "\n" + "".join(content))
70
+ return False
71
+
72
+
73
+ def main():
74
+ """Main function to check and add copyright for all tracked Python files."""
75
+ py_files = get_tracked_python_files()
76
+ if not py_files:
77
+ print("No Python files are tracked in the repository.")
78
+ return
79
+
80
+ print(f"Checking {len(py_files)} Python files for copyright notice...")
81
+
82
+ have_copyright = [check_and_add_copyright(file_path) for file_path in py_files]
83
+ if not all(have_copyright):
84
+ print("❌ Some files were missing the required copyright and have been updated.")
85
+ sys.exit(1)
86
+ else:
87
+ print("✅ All files have the required copyright.")
88
+ sys.exit(0)
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
tasks/tasksmith-0ea2241cceeb/environment/source/scripts/generate_harmony_dataset.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+
17
+ from datasets import Dataset
18
+ from transformers import HfArgumentParser
19
+
20
+
21
+ @dataclass
22
+ class ScriptArguments:
23
+ r"""
24
+ Arguments for the script.
25
+
26
+ Args:
27
+ test_size (`float`, *optional*, defaults to `0.1`):
28
+ Fraction of the dataset to include in the test split.
29
+ push_to_hub (`bool`, *optional*, defaults to `False`):
30
+ Whether to push the dataset to the Hugging Face Hub.
31
+ repo_id (`str`, *optional*, defaults to `"trl-internal-testing/harmony"`):
32
+ Hugging Face repository ID to push the dataset to.
33
+ """
34
+
35
+ test_size: float = field(
36
+ default=0.1,
37
+ metadata={"help": "Fraction of the dataset to include in the test split."},
38
+ )
39
+ push_to_hub: bool = field(
40
+ default=False,
41
+ metadata={"help": "Whether to push the dataset to the Hugging Face Hub."},
42
+ )
43
+ repo_id: str = field(
44
+ default="trl-internal-testing/harmony",
45
+ metadata={"help": "Hugging Face repository ID to push the dataset to."},
46
+ )
47
+
48
+
49
+ def main(test_size, push_to_hub, repo_id):
50
+ # fmt: off
51
+ language_modeling_dataset = Dataset.from_dict({
52
+ "messages": [
53
+ [{"role": "user", "content": "What is better than ugly?"}, {"role": "assistant", "thinking": "Beauty improves clarity and appeal.", "content": "Beautiful."}],
54
+ [{"role": "user", "content": "What is better than implicit?"}, {"role": "assistant", "thinking": "Clarity avoids confusion.", "content": "Explicit."}],
55
+ [{"role": "user", "content": "What is better than complex?"}, {"role": "assistant", "thinking": "Simplicity is easier to manage.", "content": "Simple."}],
56
+ [{"role": "user", "content": "What is better than complicated?"}, {"role": "assistant", "thinking": "Complexity has structure; complication doesn’t.", "content": "Complex."}],
57
+ [{"role": "user", "content": "What is better than nested?"}, {"role": "assistant", "thinking": "Flat structures are easier to read.", "content": "Flat."}],
58
+ [{"role": "user", "content": "What is better than dense?"}, {"role": "assistant", "thinking": "Spacing aids understanding.", "content": "Sparse."}],
59
+ [{"role": "user", "content": "What counts?"}, {"role": "assistant", "thinking": "Readable code lasts longer.", "content": "Readability."}],
60
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}, {"role": "assistant", "thinking": "Consistency is more valuable.", "content": "No, special cases aren't special enough to break the rules."}],
61
+ [{"role": "user", "content": "What beats purity?"}, {"role": "assistant", "thinking": "Real-world needs outweigh ideals.", "content": "Practicality."}],
62
+ [{"role": "user", "content": "What should never pass silently?"}, {"role": "assistant", "thinking": "Silent errors cause hidden issues.", "content": "Errors."}],
63
+ [{"role": "user", "content": "When can errors pass silently?"}, {"role": "assistant", "thinking": "Silence must be intentional.", "content": "When explicitly silenced."}],
64
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}, {"role": "assistant", "thinking": "Guessing leads to wrong choices.", "content": "Refuse the temptation to guess."}],
65
+ [{"role": "user", "content": "How many ways should there be to do it?"}, {"role": "assistant", "thinking": "One way reduces confusion.", "content": "One, and preferably only one."}],
66
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}, {"role": "assistant", "thinking": "A playful nod to Python’s creator.", "content": "Dutch."}],
67
+ [{"role": "user", "content": "What is better than never?"}, {"role": "assistant", "thinking": "Action is better than endless delay.", "content": "Now is better than never."}],
68
+ [{"role": "user", "content": "Is never better than *right* now?"}, {"role": "assistant", "thinking": "Rushed action can be worse.", "content": "Yes, often."}],
69
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}, {"role": "assistant", "thinking": "Good ideas should be clear.", "content": "It means it's a bad idea."}],
70
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}, {"role": "assistant", "thinking": "Clarity suggests soundness.", "content": "It means it may be a good idea."}],
71
+ [{"role": "user", "content": "Any great ideas?"}, {"role": "assistant", "thinking": "Namespaces prevent conflicts.", "content": "Namespaces are one honking great idea."}]
72
+ ],
73
+ "chat_template_kwargs": [
74
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
75
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
76
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
77
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
78
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
79
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
80
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
81
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
82
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
83
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
84
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
85
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
86
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
87
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
88
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
89
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
90
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
91
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
92
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
93
+ ]
94
+ }, on_mixed_types="use_json")
95
+ language_modeling_dataset = language_modeling_dataset.train_test_split(test_size=test_size, shuffle=False)
96
+ if push_to_hub:
97
+ language_modeling_dataset.push_to_hub(repo_id, config_name="language_modeling")
98
+
99
+ prompt_completion_dataset = Dataset.from_dict({
100
+ "prompt": [
101
+ [{"role": "user", "content": "What is better than ugly?"}],
102
+ [{"role": "user", "content": "What is better than implicit?"}],
103
+ [{"role": "user", "content": "What is better than complex?"}],
104
+ [{"role": "user", "content": "What is better than complicated?"}],
105
+ [{"role": "user", "content": "What is better than nested?"}],
106
+ [{"role": "user", "content": "What is better than dense?"}],
107
+ [{"role": "user", "content": "What counts?"}],
108
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}],
109
+ [{"role": "user", "content": "What beats purity?"}],
110
+ [{"role": "user", "content": "What should never pass silently?"}],
111
+ [{"role": "user", "content": "When can errors pass silently?"}],
112
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}],
113
+ [{"role": "user", "content": "How many ways should there be to do it?"}],
114
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}],
115
+ [{"role": "user", "content": "What is better than never?"}],
116
+ [{"role": "user", "content": "Is never better than *right* now?"}],
117
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}],
118
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}],
119
+ [{"role": "user", "content": "Any great ideas?"}],
120
+ ],
121
+ "completion": [
122
+ [{"role": "assistant", "thinking": "Beauty improves clarity and appeal.", "content": "Beautiful."}],
123
+ [{"role": "assistant", "thinking": "Clarity avoids confusion.", "content": "Explicit."}],
124
+ [{"role": "assistant", "thinking": "Simplicity is easier to manage.", "content": "Simple."}],
125
+ [{"role": "assistant", "thinking": "Complexity has structure; complication doesn’t.", "content": "Complex."}],
126
+ [{"role": "assistant", "thinking": "Flat structures are easier to read.", "content": "Flat."}],
127
+ [{"role": "assistant", "thinking": "Spacing aids understanding.", "content": "Sparse."}],
128
+ [{"role": "assistant", "thinking": "Readable code lasts longer.", "content": "Readability."}],
129
+ [{"role": "assistant", "thinking": "Consistency is more valuable.", "content": "No, special cases aren't special enough to break the rules."}],
130
+ [{"role": "assistant", "thinking": "Real-world needs outweigh ideals.", "content": "Practicality."}],
131
+ [{"role": "assistant", "thinking": "Silent errors cause hidden issues.", "content": "Errors."}],
132
+ [{"role": "assistant", "thinking": "Silence must be intentional.", "content": "When explicitly silenced."}],
133
+ [{"role": "assistant", "thinking": "Guessing leads to wrong choices.", "content": "Refuse the temptation to guess."}],
134
+ [{"role": "assistant", "thinking": "One way reduces confusion.", "content": "One, and preferably only one."}],
135
+ [{"role": "assistant", "thinking": "A playful nod to Python’s creator.", "content": "Dutch."}],
136
+ [{"role": "assistant", "thinking": "Action is better than endless delay.", "content": "Now is better than never."}],
137
+ [{"role": "assistant", "thinking": "Rushed action can be worse.", "content": "Yes, often."}],
138
+ [{"role": "assistant", "thinking": "Good ideas should be clear.", "content": "It means it's a bad idea."}],
139
+ [{"role": "assistant", "thinking": "Clarity suggests soundness.", "content": "It means it may be a good idea."}],
140
+ [{"role": "assistant", "thinking": "Namespaces prevent conflicts.", "content": "Namespaces are one honking great idea."}],
141
+ ],
142
+ "chat_template_kwargs": [
143
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
144
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
145
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
146
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
147
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
148
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
149
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
150
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
151
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
152
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
153
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
154
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
155
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
156
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
157
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
158
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
159
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
160
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
161
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
162
+ ]
163
+ })
164
+ prompt_completion_dataset = prompt_completion_dataset.train_test_split(test_size=test_size, shuffle=False)
165
+ if push_to_hub:
166
+ prompt_completion_dataset.push_to_hub(repo_id, config_name="prompt_completion")
167
+
168
+ preference_dataset = Dataset.from_dict({
169
+ "prompt": [
170
+ [{"role": "user", "content": "What is better than ugly?"}],
171
+ [{"role": "user", "content": "What is better than implicit?"}],
172
+ [{"role": "user", "content": "What is better than complex?"}],
173
+ [{"role": "user", "content": "What is better than complicated?"}],
174
+ [{"role": "user", "content": "What is better than nested?"}],
175
+ [{"role": "user", "content": "What is better than dense?"}],
176
+ [{"role": "user", "content": "What counts?"}],
177
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}],
178
+ [{"role": "user", "content": "What beats purity?"}],
179
+ [{"role": "user", "content": "What should never pass silently?"}],
180
+ [{"role": "user", "content": "When can errors pass silently?"}],
181
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}],
182
+ [{"role": "user", "content": "How many ways should there be to do it?"}],
183
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}],
184
+ [{"role": "user", "content": "What is better than never?"}],
185
+ [{"role": "user", "content": "Is never better than *right* now?"}],
186
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}],
187
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}],
188
+ [{"role": "user", "content": "Any great ideas?"}],
189
+ ],
190
+ "chosen": [
191
+ [{"role": "assistant", "thinking": "Beauty improves clarity and appeal.", "content": "Beautiful."}],
192
+ [{"role": "assistant", "thinking": "Clarity avoids confusion.", "content": "Explicit."}],
193
+ [{"role": "assistant", "thinking": "Simplicity is easier to manage.", "content": "Simple."}],
194
+ [{"role": "assistant", "thinking": "Complexity has structure; complication doesn’t.", "content": "Complex."}],
195
+ [{"role": "assistant", "thinking": "Flat structures are easier to read.", "content": "Flat."}],
196
+ [{"role": "assistant", "thinking": "Spacing aids understanding.", "content": "Sparse."}],
197
+ [{"role": "assistant", "thinking": "Readable code lasts longer.", "content": "Readability."}],
198
+ [{"role": "assistant", "thinking": "Consistency is more valuable.", "content": "No, special cases aren't special enough to break the rules."}],
199
+ [{"role": "assistant", "thinking": "Real-world needs outweigh ideals.", "content": "Practicality."}],
200
+ [{"role": "assistant", "thinking": "Silent errors cause hidden issues.", "content": "Errors."}],
201
+ [{"role": "assistant", "thinking": "Silence must be intentional.", "content": "When explicitly silenced."}],
202
+ [{"role": "assistant", "thinking": "Guessing leads to wrong choices.", "content": "Refuse the temptation to guess."}],
203
+ [{"role": "assistant", "thinking": "One way reduces confusion.", "content": "One, and preferably only one."}],
204
+ [{"role": "assistant", "thinking": "A playful nod to Python’s creator.", "content": "Dutch."}],
205
+ [{"role": "assistant", "thinking": "Action is better than endless delay.", "content": "Now is better than never."}],
206
+ [{"role": "assistant", "thinking": "Rushed action can be worse.", "content": "Yes, often."}],
207
+ [{"role": "assistant", "thinking": "Good ideas should be clear.", "content": "It means it's a bad idea."}],
208
+ [{"role": "assistant", "thinking": "Clarity suggests soundness.", "content": "It means it may be a good idea."}],
209
+ [{"role": "assistant", "thinking": "Namespaces prevent conflicts.", "content": "Namespaces are one honking great idea."}],
210
+ ],
211
+ "rejected": [
212
+ [{"role": "assistant", "thinking": "This comparison is nonsensical.", "content": "Better than the moon."}],
213
+ [{"role": "assistant", "thinking": "This dismisses the value of clarity.", "content": "Worse than nothing."}],
214
+ [{"role": "assistant", "thinking": "This mixes code style with leisure.", "content": "Better than a long vacation."}],
215
+ [{"role": "assistant", "thinking": "This overstates complexity as a universal solution.", "content": "Always the answer."}],
216
+ [{"role": "assistant", "thinking": "This swaps a structural concept for a random object.", "content": "Better than chocolate."}],
217
+ [{"role": "assistant", "thinking": "This ignores the need for context in sparse designs.", "content": "Without any context."}],
218
+ [{"role": "assistant", "thinking": "This implies readability is optional, which it is not.", "content": "Optional."}],
219
+ [{"role": "assistant", "thinking": "This exaggerates special cases into fantasy.", "content": "Enough to become unicorns."}],
220
+ [{"role": "assistant", "thinking": "This twists the original contrast between practicality and purity.", "content": "Beats reality."}],
221
+ [{"role": "assistant", "thinking": "This misapplies \"passing\" to a literal driving test.", "content": "Pass their driving test."}],
222
+ [{"role": "assistant", "thinking": "This suggests forgetting rather than intentional silence.", "content": "Forgotten."}],
223
+ [{"role": "assistant", "thinking": "This replaces careful judgment with a joke.", "content": "Refuse the opportunity to laugh."}],
224
+ [{"role": "assistant", "thinking": "This encourages multiple confusing approaches instead of one clear way.", "content": "Two or more confusing methods."}],
225
+ [{"role": "assistant", "thinking": "This turns a simple example into time-travel absurdity.", "content": "A time traveler."}],
226
+ [{"role": "assistant", "thinking": "This denies the value of timely action.", "content": "Never better."}],
227
+ [{"role": "assistant", "thinking": "This removes the sense of tradeoff and possibility.", "content": "Not even a possibility."}],
228
+ [{"role": "assistant", "thinking": "This inverts the meaning of explainability.", "content": "Clearly the best choice."}],
229
+ [{"role": "assistant", "thinking": "This treats clarity as something mystical rather than practical.", "content": "Probably magic."}],
230
+ [{"role": "assistant", "thinking": "This turns a design principle into a silly metaphor.", "content": "Watermelon -- let's plant some!"}],
231
+ ],
232
+ "chat_template_kwargs": [
233
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
234
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
235
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
236
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
237
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
238
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
239
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
240
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
241
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
242
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
243
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
244
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
245
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
246
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
247
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
248
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
249
+ {"reasoning_effort": "medium", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
250
+ {"reasoning_effort": "high", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
251
+ {"reasoning_effort": "low", "model_identity": "You are Tiny ChatGPT, a tiny language model."},
252
+ ],
253
+ })
254
+ preference_dataset = preference_dataset.train_test_split(test_size=test_size, shuffle=False)
255
+ if push_to_hub:
256
+ preference_dataset.push_to_hub(repo_id, config_name="preference")
257
+ # fmt: on
258
+
259
+
260
+ if __name__ == "__main__":
261
+ parser = HfArgumentParser(ScriptArguments)
262
+ script_args = parser.parse_args_into_dataclasses()[0]
263
+ main(script_args.test_size, script_args.push_to_hub, script_args.repo_id)
tasks/tasksmith-0ea2241cceeb/environment/source/scripts/generate_tiny_models.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # This script generates tiny models used in the TRL library for unit tests. It pushes them to the Hub under the
16
+ # `trl-internal-testing` organization.
17
+ # This script is meant to be run when adding new tiny model to the TRL library.
18
+
19
+ import torch
20
+ from huggingface_hub import HfApi, ModelCard
21
+ from peft import LoraConfig, get_peft_model
22
+ from torch import nn
23
+ from transformers import (
24
+ AutoConfig,
25
+ AutoProcessor,
26
+ AutoTokenizer,
27
+ BartModel,
28
+ Cohere2Config,
29
+ Cohere2ForCausalLM,
30
+ CohereConfig,
31
+ CohereForCausalLM,
32
+ DeepseekV3Config,
33
+ DeepseekV3ForCausalLM,
34
+ FalconMambaConfig,
35
+ FalconMambaForCausalLM,
36
+ Gemma2Config,
37
+ Gemma2ForCausalLM,
38
+ Gemma3ForConditionalGeneration,
39
+ Gemma4ForConditionalGeneration,
40
+ GemmaConfig,
41
+ GemmaForCausalLM,
42
+ GenerationConfig,
43
+ Glm4MoeConfig,
44
+ Glm4MoeForCausalLM,
45
+ GPT2Config,
46
+ GPT2LMHeadModel,
47
+ GPTNeoXConfig,
48
+ GPTNeoXForCausalLM,
49
+ GPTNeoXForSequenceClassification,
50
+ GptOssConfig,
51
+ GptOssForCausalLM,
52
+ Idefics2Config,
53
+ Idefics2ForConditionalGeneration,
54
+ Idefics3ForConditionalGeneration,
55
+ InternVLForConditionalGeneration,
56
+ LlamaConfig,
57
+ LlamaForCausalLM,
58
+ LlamaForSequenceClassification,
59
+ LlavaForConditionalGeneration,
60
+ LlavaNextForConditionalGeneration,
61
+ MistralConfig,
62
+ MistralForCausalLM,
63
+ OPTConfig,
64
+ OPTForCausalLM,
65
+ PaliGemmaForConditionalGeneration,
66
+ Phi3Config,
67
+ Phi3ForCausalLM,
68
+ Qwen2_5_VLConfig,
69
+ Qwen2_5_VLForConditionalGeneration,
70
+ Qwen2Config,
71
+ Qwen2ForCausalLM,
72
+ Qwen2ForSequenceClassification,
73
+ Qwen2VLConfig,
74
+ Qwen2VLForConditionalGeneration,
75
+ Qwen3_5Config,
76
+ Qwen3_5ForConditionalGeneration,
77
+ Qwen3Config,
78
+ Qwen3ForCausalLM,
79
+ Qwen3ForSequenceClassification,
80
+ Qwen3MoeConfig,
81
+ Qwen3MoeForCausalLM,
82
+ Qwen3MoeForSequenceClassification,
83
+ Qwen3VLConfig,
84
+ Qwen3VLForConditionalGeneration,
85
+ SmolVLMForConditionalGeneration,
86
+ T5ForConditionalGeneration,
87
+ )
88
+
89
+
90
+ ORGANIZATION = "trl-internal-testing"
91
+
92
+ MODEL_CARD = """
93
+ ---
94
+ library_name: transformers
95
+ tags: [trl]
96
+ ---
97
+
98
+ # Tiny {model_class_name}
99
+
100
+ This is a minimal model built for unit tests in the [TRL](https://github.com/huggingface/trl) library.
101
+ """
102
+
103
+
104
+ api = HfApi()
105
+
106
+
107
+ def push_to_hub(model, tokenizer, generation_config, prefix=None, suffix=None, force=False):
108
+ model_class_name = model.__class__.__name__
109
+ content = MODEL_CARD.format(model_class_name=model_class_name)
110
+ model_card = ModelCard(content)
111
+ if prefix is not None:
112
+ model_class_name = f"{prefix}-{model_class_name}"
113
+ repo_id = f"{ORGANIZATION}/{model_class_name}"
114
+ if suffix is not None:
115
+ repo_id += f"-{suffix}"
116
+
117
+ if api.repo_exists(repo_id) and not force:
118
+ print(f"Model {repo_id} already exists, skipping")
119
+ else:
120
+ model.push_to_hub(repo_id)
121
+ model_card.push_to_hub(repo_id)
122
+ if tokenizer is not None:
123
+ tokenizer.push_to_hub(repo_id)
124
+ if generation_config is not None:
125
+ generation_config.push_to_hub(repo_id)
126
+
127
+
128
+ def init_weights_tiny_model(model):
129
+ """
130
+ Initialize tiny test models to avoid NaNs from uninitialized weights.
131
+
132
+ Uses safe defaults:
133
+ - Linear/Conv1d: Xavier uniform (weights), zero (biases)
134
+ - Embedding: Normal(0, 0.02)
135
+ - LayerNorm: Ones (weights), zero (biases)
136
+
137
+ Args:
138
+ model: PyTorch model (modified in-place)
139
+ """
140
+ for module in model.modules():
141
+ if isinstance(module, nn.Linear):
142
+ # Attention/MLP projections → Xavier or Normal
143
+ if module.bias is not None:
144
+ nn.init.zeros_(module.bias)
145
+ nn.init.xavier_uniform_(module.weight)
146
+
147
+ elif isinstance(module, nn.Embedding):
148
+ # Token embeddings → GPT-style Normal
149
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
150
+
151
+ elif isinstance(module, nn.LayerNorm):
152
+ # LayerNorm weights always 1, bias 0
153
+ nn.init.ones_(module.weight)
154
+ if module.bias is not None:
155
+ nn.init.zeros_(module.bias)
156
+
157
+ elif isinstance(module, nn.Conv1d):
158
+ # Convolutional layers → Xavier or Normal
159
+ if module.bias is not None:
160
+ nn.init.zeros_(module.bias)
161
+ nn.init.xavier_uniform_(module.weight)
162
+
163
+
164
+ # Decoder models
165
+ for model_id, config_class, model_class, dtype, suffix in [
166
+ # ("bigscience/bloomz-560m", BloomConfig, BloomForCausalLM, None), # loading fails with this model, see https://huggingface.co/bigscience/bloomz-560m/discussions/14
167
+ ("CohereLabs/aya-expanse-8b", CohereConfig, CohereForCausalLM, torch.float16, None),
168
+ ("CohereLabs/tiny-aya-earth", Cohere2Config, Cohere2ForCausalLM, torch.bfloat16, None),
169
+ ("deepseek-ai/DeepSeek-R1", DeepseekV3Config, DeepseekV3ForCausalLM, torch.bfloat16, None),
170
+ # It's important to have R1-0528 as it doesn't have the same chat template
171
+ ("deepseek-ai/DeepSeek-R1-0528", DeepseekV3Config, DeepseekV3ForCausalLM, torch.bfloat16, "0528"),
172
+ ("tiiuae/falcon-7b-instruct", FalconMambaConfig, FalconMambaForCausalLM, torch.bfloat16, None),
173
+ ("google/gemma-2-2b-it", Gemma2Config, Gemma2ForCausalLM, torch.bfloat16, None),
174
+ ("google/gemma-7b-it", GemmaConfig, GemmaForCausalLM, torch.bfloat16, None),
175
+ ("openai-community/gpt2", GPT2Config, GPT2LMHeadModel, torch.float32, None),
176
+ ("EleutherAI/pythia-14m", GPTNeoXConfig, GPTNeoXForCausalLM, torch.float16, None),
177
+ ("meta-llama/Meta-Llama-3-8B-Instruct", LlamaConfig, LlamaForCausalLM, torch.bfloat16, "3"),
178
+ ("meta-llama/Llama-3.1-8B-Instruct", LlamaConfig, LlamaForCausalLM, torch.bfloat16, "3.1"),
179
+ ("meta-llama/Llama-3.2-1B-Instruct", LlamaConfig, LlamaForCausalLM, torch.bfloat16, "3.2"),
180
+ ("mistralai/Mistral-7B-Instruct-v0.1", MistralConfig, MistralForCausalLM, torch.bfloat16, "0.1"),
181
+ ("mistralai/Mistral-7B-Instruct-v0.2", MistralConfig, MistralForCausalLM, torch.bfloat16, "0.2"),
182
+ ("facebook/opt-1.3b", OPTConfig, OPTForCausalLM, torch.float16, None),
183
+ ("microsoft/Phi-3.5-mini-instruct", Phi3Config, Phi3ForCausalLM, torch.bfloat16, None),
184
+ ("Qwen/Qwen2.5-32B-Instruct", Qwen2Config, Qwen2ForCausalLM, torch.bfloat16, "2.5"),
185
+ ("Qwen/Qwen2.5-Coder-0.5B", Qwen2Config, Qwen2ForCausalLM, torch.bfloat16, "2.5-Coder"),
186
+ ("Qwen/Qwen3-8B", Qwen3Config, Qwen3ForCausalLM, torch.bfloat16, None),
187
+ ]:
188
+ revision = "refs/pr/14" if model_id == "Qwen/Qwen3-8B" else "main" # chat template with {% generation %}
189
+ tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)
190
+ generation_config = GenerationConfig.from_pretrained(model_id, revision=revision)
191
+ config = config_class(
192
+ vocab_size=len(tokenizer.vocab),
193
+ hidden_size=8,
194
+ num_attention_heads=4,
195
+ num_key_value_heads=2,
196
+ num_hidden_layers=2,
197
+ intermediate_size=32,
198
+ )
199
+ model = model_class(config).to(dtype=dtype)
200
+ init_weights_tiny_model(model)
201
+ push_to_hub(model, tokenizer, generation_config, "tiny", suffix)
202
+
203
+ # MoE models
204
+ for model_id, config_class, model_class, dtype, suffix in [
205
+ ("Qwen/Qwen3-30B-A3B", Qwen3MoeConfig, Qwen3MoeForCausalLM, torch.bfloat16, None),
206
+ ("openai/gpt-oss-20b", GptOssConfig, GptOssForCausalLM, torch.bfloat16, None),
207
+ ("zai-org/GLM-4.5", Glm4MoeConfig, Glm4MoeForCausalLM, torch.bfloat16, None),
208
+ ]:
209
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
210
+ generation_config = GenerationConfig.from_pretrained(model_id)
211
+ kwargs = {}
212
+ if model_id == "zai-org/GLM-4.5":
213
+ kwargs["n_routed_experts"] = 4
214
+ elif model_id in ("Qwen/Qwen3-30B-A3B", "openai/gpt-oss-20b"):
215
+ kwargs["num_experts"] = 4
216
+
217
+ config = config_class(
218
+ vocab_size=len(tokenizer.vocab),
219
+ hidden_size=8,
220
+ num_attention_heads=4,
221
+ num_key_value_heads=2,
222
+ num_hidden_layers=2,
223
+ intermediate_size=32,
224
+ num_experts_per_tok=2,
225
+ **kwargs,
226
+ )
227
+ model = model_class(config).to(dtype=dtype)
228
+ init_weights_tiny_model(model)
229
+ push_to_hub(model, tokenizer, generation_config, "tiny", suffix)
230
+
231
+ # Two slightly bigger models, required for vLLM testing
232
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-32B-Instruct")
233
+ generation_config = GenerationConfig.from_pretrained("Qwen/Qwen2.5-32B-Instruct")
234
+ config = Qwen2Config(
235
+ vocab_size=len(tokenizer.vocab),
236
+ hidden_size=128, # increase hidden size so that hidden_size // num_attention_heads = 32, required for vLLM
237
+ num_attention_heads=4,
238
+ num_key_value_heads=2,
239
+ num_hidden_layers=2,
240
+ intermediate_size=32,
241
+ )
242
+ model = Qwen2ForCausalLM(config).to(dtype=torch.bfloat16)
243
+ push_to_hub(model, tokenizer, generation_config, "small", "2.5")
244
+
245
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B")
246
+ generation_config = GenerationConfig.from_pretrained("Qwen/Qwen3-4B")
247
+ config = Qwen3Config(
248
+ vocab_size=len(tokenizer.vocab),
249
+ hidden_size=128, # increase hidden size so that hidden_size // num_attention_heads = 32, required for vLLM
250
+ num_attention_heads=4,
251
+ num_key_value_heads=2,
252
+ num_hidden_layers=2,
253
+ intermediate_size=32,
254
+ )
255
+ model = Qwen3ForCausalLM(config).to(dtype=torch.bfloat16)
256
+ push_to_hub(model, tokenizer, generation_config, "small")
257
+
258
+ # Reward models
259
+ for model_id, model_class, dtype, suffix in [
260
+ ("EleutherAI/pythia-14m", GPTNeoXForSequenceClassification, torch.bfloat16, None),
261
+ ("meta-llama/Llama-3.2-1B-Instruct", LlamaForSequenceClassification, torch.bfloat16, "3.2"),
262
+ ("Qwen/Qwen2.5-32B-Instruct", Qwen2ForSequenceClassification, torch.bfloat16, "2.5"),
263
+ ("Qwen/Qwen3-4B", Qwen3ForSequenceClassification, torch.bfloat16, None),
264
+ ]:
265
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
266
+ generation_config = GenerationConfig.from_pretrained(model_id)
267
+ kwargs = {
268
+ "num_labels": 1,
269
+ "hidden_size": 16,
270
+ "num_attention_heads": 4,
271
+ "num_key_value_heads": 2,
272
+ "num_hidden_layers": 2,
273
+ "intermediate_size": 32,
274
+ }
275
+ config = AutoConfig.from_pretrained(model_id, **kwargs)
276
+ # Bug in transformers: it ignores num_hidden_layers to build layer_types
277
+ if model_id in ("Qwen/Qwen2.5-32B-Instruct", "Qwen/Qwen3-4B"):
278
+ config.layer_types = config.layer_types[:2]
279
+ model = model_class(config).to(dtype=dtype)
280
+ init_weights_tiny_model(model)
281
+ push_to_hub(model, tokenizer, generation_config, "tiny", suffix)
282
+
283
+ # MoE Reward models
284
+ for model_id, model_class, dtype, suffix in [
285
+ ("Qwen/Qwen3-30B-A3B", Qwen3MoeForSequenceClassification, torch.bfloat16, None),
286
+ ]:
287
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
288
+ generation_config = GenerationConfig.from_pretrained(model_id)
289
+ kwargs = {
290
+ "num_labels": 1,
291
+ "hidden_size": 16,
292
+ "num_attention_heads": 4,
293
+ "num_key_value_heads": 2,
294
+ "num_hidden_layers": 2,
295
+ "intermediate_size": 32,
296
+ "num_experts": 4,
297
+ "num_experts_per_tok": 2,
298
+ }
299
+ config = AutoConfig.from_pretrained(model_id, **kwargs)
300
+ model = model_class(config).to(dtype=dtype)
301
+ push_to_hub(model, tokenizer, generation_config, "tiny", suffix)
302
+
303
+
304
+ # Encoder-decoder models
305
+ for model_id, model_class, dtype, suffix in [
306
+ ("facebook/bart-base", BartModel, torch.float32, None),
307
+ ("google/flan-t5-small", T5ForConditionalGeneration, torch.float32, None),
308
+ ]:
309
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
310
+ generation_config = GenerationConfig.from_pretrained(model_id) if model_id != "facebook/bart-base" else None
311
+ config = AutoConfig.from_pretrained(model_id)
312
+ config.d_model = 24
313
+ model = model_class(config).to(dtype=dtype)
314
+ push_to_hub(model, tokenizer, generation_config, "tiny", suffix)
315
+
316
+
317
+ # Vision Language Models
318
+ for model_id, model_class, dtype in [
319
+ ("google/gemma-3-4b-it", Gemma3ForConditionalGeneration, torch.bfloat16),
320
+ ("google/gemma-4-E2B-it", Gemma4ForConditionalGeneration, torch.bfloat16),
321
+ ("google/paligemma-3b-pt-224", PaliGemmaForConditionalGeneration, torch.float32),
322
+ ("HuggingFaceM4/idefics2-8b", Idefics2ForConditionalGeneration, torch.float32),
323
+ ("HuggingFaceM4/Idefics3-8B-Llama3", Idefics3ForConditionalGeneration, torch.bfloat16),
324
+ ("HuggingFaceTB/SmolVLM2-2.2B-Instruct", SmolVLMForConditionalGeneration, torch.float32),
325
+ ("llava-hf/llava-1.5-7b-hf", LlavaForConditionalGeneration, torch.float16),
326
+ # Original model dtype is float16, but it triggers CUDA device side assert error (see GH-4741):
327
+ ("llava-hf/llava-v1.6-mistral-7b-hf", LlavaNextForConditionalGeneration, torch.bfloat16),
328
+ ("OpenGVLab/InternVL3-8B-hf", InternVLForConditionalGeneration, torch.bfloat16),
329
+ ("Qwen/Qwen2-VL-2B-Instruct", Qwen2VLForConditionalGeneration, torch.bfloat16),
330
+ ("Qwen/Qwen2.5-VL-3B-Instruct", Qwen2_5_VLForConditionalGeneration, torch.bfloat16),
331
+ ("Qwen/Qwen3-VL-2B-Instruct", Qwen3VLForConditionalGeneration, torch.bfloat16),
332
+ ("Qwen/Qwen3.5-0.8B", Qwen3_5ForConditionalGeneration, torch.bfloat16),
333
+ ]:
334
+ processor = AutoProcessor.from_pretrained(model_id)
335
+ generation_config = GenerationConfig.from_pretrained(model_id) if model_id != "Qwen/Qwen3.5-0.8B" else None
336
+
337
+ text_config = {
338
+ "num_hidden_layers": 2,
339
+ "hidden_size": 16,
340
+ "num_attention_heads": 4,
341
+ "num_key_value_heads": 2,
342
+ "layer_types": None, # Set it automatically from num_hidden_layers
343
+ }
344
+ vision_config = {
345
+ "num_hidden_layers": 2,
346
+ "hidden_size": 16,
347
+ "num_attention_heads": 4,
348
+ "num_key_value_heads": 2,
349
+ "embed_dim": 64,
350
+ }
351
+ kwargs = {}
352
+
353
+ if issubclass(model_class.config_class, (Qwen2VLConfig, Qwen2_5_VLConfig)):
354
+ text_config["rope_scaling"] = {"type": "default", "mrope_section": [1, 1], "rope_type": "default"}
355
+ vision_config["depth"] = 2
356
+ # Different dict object from text_config; see GH-4101 and transformers#41020
357
+ kwargs["rope_scaling"] = {"type": "default", "mrope_section": [1, 1], "rope_type": "default"}
358
+
359
+ if issubclass(model_class.config_class, Qwen2_5_VLConfig):
360
+ vision_config["out_hidden_size"] = 16
361
+ # Different dict object at the config root; see GH-4101 and transformers#41020
362
+ kwargs["num_hidden_layers"] = 2
363
+ kwargs["hidden_size"] = 16
364
+ kwargs["num_attention_heads"] = 4
365
+
366
+ if issubclass(model_class.config_class, Idefics2Config):
367
+ kwargs["perceiver_config"] = {"hidden_size": 16}
368
+
369
+ if issubclass(model_class.config_class, Qwen3VLConfig):
370
+ # So hasattr(config, "layer_types") is False
371
+ # See: https://github.com/huggingface/transformers/blob/fe5ca9ddaa07fac2872407e75c7a7661216ac956/src/transformers/models/qwen3_vl/modeling_qwen3_vl.py#L420
372
+ del text_config["layer_types"]
373
+ # "mrope_section" needs 3 elements: for dim, offset in enumerate((1, 2), start=1): mrope_section[dim]
374
+ # See: https://github.com/huggingface/transformers/blob/fe5ca9ddaa07fac2872407e75c7a7661216ac956/src/transformers/models/qwen3_vl/modeling_qwen3_vl.py#L361
375
+ text_config["rope_scaling"] = {"mrope_interleaved": True, "mrope_section": [2, 2, 2], "rope_type": "default"}
376
+ vision_config["depth"] = 2
377
+ vision_config["out_hidden_size"] = 16
378
+
379
+ if issubclass(model_class.config_class, Qwen3_5Config):
380
+ # For tiny layer counts, default `layer_types` can end up with no full-attention layers (e.g. 2 layers and
381
+ # default interval 4), which breaks Qwen3.5 dynamic cache logic. Keep one full-attention layer at the end.
382
+ text_config["layer_types"] = ["linear_attention", "full_attention"]
383
+ text_config["full_attention_interval"] = 2
384
+ # Qwen3.5-VL vision config expects `depth`/`num_heads`, not `num_hidden_layers`/`num_attention_heads`.
385
+ vision_config.pop("num_hidden_layers", None)
386
+ vision_config.pop("num_attention_heads", None)
387
+ vision_config.pop("num_key_value_heads", None)
388
+ vision_config.pop("embed_dim", None)
389
+ vision_config["depth"] = 2
390
+ vision_config["num_heads"] = 4
391
+ vision_config["intermediate_size"] = 32
392
+ vision_config["out_hidden_size"] = 16
393
+
394
+ if model_id == "llava-hf/llava-v1.6-mistral-7b-hf":
395
+ # Hotfix: llava-hf/llava-v1.6-mistral-7b-hf mistakesly sets text_config.dtype to "bfloat16".
396
+ # See https://huggingface.co/llava-hf/llava-v1.6-mistral-7b-hf/discussions/46
397
+ text_config["dtype"] = None
398
+
399
+ if model_class is Gemma4ForConditionalGeneration:
400
+ # Gemma4 rope validation fails when passing text_config as a dict, so we mutate the config directly.
401
+ config = AutoConfig.from_pretrained(model_id)
402
+ for k, v in text_config.items():
403
+ setattr(config.text_config, k, v)
404
+ for k, v in vision_config.items():
405
+ setattr(config.vision_config, k, v)
406
+ config.text_config.layer_types = ["sliding_attention", "full_attention"]
407
+ config.text_config.num_kv_shared_layers = 0
408
+ config.text_config.global_head_dim = 8
409
+ config.text_config.hidden_size_per_layer_input = 16
410
+ config.audio_config = None
411
+ else:
412
+ config = AutoConfig.from_pretrained(model_id, text_config=text_config, vision_config=vision_config, **kwargs)
413
+ model = model_class(config).to(dtype=dtype)
414
+
415
+ if issubclass(model_class.config_class, Qwen3_5Config):
416
+ # Qwen3.5 models has some weights in float32, to mirror this in the tiny model we need to convert them to float32 manually.
417
+ for layer in model.model.language_model.layers:
418
+ if hasattr(layer, "linear_attn"): # applies to linear attention layers only
419
+ layer.linear_attn.A_log.data = layer.linear_attn.A_log.data.float()
420
+ layer.linear_attn.norm.weight.data = layer.linear_attn.norm.weight.data.float()
421
+
422
+ push_to_hub(model, processor, generation_config, "tiny")
423
+
424
+ # PEFT models
425
+ model = Qwen3ForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen3ForCausalLM", dtype="auto")
426
+ model = get_peft_model(model, LoraConfig())
427
+ generation_config = GenerationConfig.from_pretrained("trl-internal-testing/tiny-Qwen3ForCausalLM")
428
+ push_to_hub(model, None, None, "tiny")
429
+
430
+ # Same model, but different weights
431
+ model = Qwen3ForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen3ForCausalLM", dtype="auto")
432
+ model = get_peft_model(model, LoraConfig())
433
+ generation_config = GenerationConfig.from_pretrained("trl-internal-testing/tiny-Qwen3ForCausalLM")
434
+ push_to_hub(model, None, None, "tiny", "2")
tasks/tasksmith-0ea2241cceeb/environment/source/scripts/generate_toolcall_dataset.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+
17
+ from datasets import Dataset
18
+ from transformers import HfArgumentParser
19
+ from transformers.utils import get_json_schema
20
+
21
+
22
+ @dataclass
23
+ class ScriptArguments:
24
+ r"""
25
+ Arguments for the script.
26
+
27
+ Args:
28
+ test_size (`float`, *optional*, defaults to `0.1`):
29
+ Fraction of the dataset to include in the test split.
30
+ push_to_hub (`bool`, *optional*, defaults to `False`):
31
+ Whether to push the dataset to the Hugging Face Hub.
32
+ repo_id (`str`, *optional*, defaults to `"trl-internal-testing/zen"`):
33
+ Hugging Face repository ID to push the dataset to.
34
+ """
35
+
36
+ test_size: float = field(
37
+ default=0.1,
38
+ metadata={"help": "Fraction of the dataset to include in the test split."},
39
+ )
40
+ push_to_hub: bool = field(
41
+ default=False,
42
+ metadata={"help": "Whether to push the dataset to the Hugging Face Hub."},
43
+ )
44
+ repo_id: str = field(
45
+ default="trl-internal-testing/toolcall",
46
+ metadata={"help": "Hugging Face repository ID to push the dataset to."},
47
+ )
48
+
49
+
50
+ def main(test_size, push_to_hub, repo_id):
51
+ # Fictitious functions to simulate tool calls
52
+ def start_timer(duration: int) -> int:
53
+ """
54
+ Starts a timer for the specified duration in seconds.
55
+
56
+ Args:
57
+ duration: Duration in seconds to set the timer for.
58
+
59
+ Returns:
60
+ The duration set for the timer.
61
+ """
62
+ return duration
63
+
64
+ def get_current_time(location: str) -> str:
65
+ """
66
+ Returns the current time in the specified location.
67
+
68
+ Args:
69
+ location: The location for which to get the current time.
70
+
71
+ Returns:
72
+ The current time in the specified location.
73
+ """
74
+ return "06:22:48"
75
+
76
+ def get_air_quality_index(location: str) -> int:
77
+ """
78
+ Returns the air quality index for the specified location.
79
+
80
+ Args:
81
+ location: The location for which to get the air quality index.
82
+
83
+ Returns:
84
+ The air quality index for the specified location.
85
+ """
86
+ return 53
87
+
88
+ def play_music(title: str, artist: str) -> dict:
89
+ """
90
+ Plays music by the specified title and artist.
91
+
92
+ Args:
93
+ title: The title of the music to play.
94
+ artist: The artist of the music to play.
95
+
96
+ Returns:
97
+ A dictionary indicating the status of the music playback.
98
+ """
99
+ return {"status": "Playing"}
100
+
101
+ def get_weather_forecast(city: str, date: str) -> dict:
102
+ """
103
+ Returns the weather forecast for the specified city and date.
104
+
105
+ Args:
106
+ city: The city for which to get the weather forecast.
107
+ date: The date for which to get the weather forecast.
108
+
109
+ Returns:
110
+ A dictionary containing the temperature and weather condition.
111
+ """
112
+ return {"temperature": 22, "condition": "partly cloudy"}
113
+
114
+ def control_light(room: str, state: str) -> dict:
115
+ """
116
+ Controls the light in the specified room.
117
+
118
+ Args:
119
+ room: The room where the light should be controlled.
120
+ state: The desired state of the light ("on" or "off").
121
+
122
+ Returns:
123
+ A dictionary indicating the state of the light.
124
+ """
125
+ return {"state": state}
126
+
127
+ def create_reminder(time: str, note: str) -> str:
128
+ """
129
+ Creates a reminder for the specified time and note.
130
+
131
+ Args:
132
+ time: The time for the reminder.
133
+ note: The note for the reminder.
134
+
135
+ Returns:
136
+ A confirmation message indicating that the reminder has been set.
137
+ """
138
+ return "I'll remind you to call mom at 7 PM."
139
+
140
+ def get_wind_conditions(city: str, unit: str) -> tuple[int, str]:
141
+ """
142
+ Returns the wind conditions for the specified city.
143
+
144
+ Args:
145
+ city: The city for which to get the wind conditions.
146
+ unit: The unit of measurement for the wind speed (e.g., "mph").
147
+
148
+ Returns:
149
+ A tuple containing the wind speed and direction.
150
+ """
151
+ return 14, "NW"
152
+
153
+ start_timer = get_json_schema(start_timer)
154
+ get_current_time = get_json_schema(get_current_time)
155
+ get_air_quality_index = get_json_schema(get_air_quality_index)
156
+ play_music = get_json_schema(play_music)
157
+ get_weather_forecast = get_json_schema(get_weather_forecast)
158
+ control_light = get_json_schema(control_light)
159
+ create_reminder = get_json_schema(create_reminder)
160
+ get_wind_conditions = get_json_schema(get_wind_conditions)
161
+
162
+ # fmt: off
163
+ language_modeling_dataset = Dataset.from_dict({
164
+ "messages": [
165
+ [
166
+ {"role": "user", "content": "Set a timer for 10 minutes."},
167
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "start_timer", "arguments": {"duration": 600}}}]},
168
+ {"role": "tool", "name": "start_timer", "content": "600"},
169
+ {"role": "assistant", "content": "Timer set for 10 minutes."},
170
+ ],
171
+ [
172
+ {"role": "user", "content": "What time is it in Tokyo?"},
173
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_current_time", "arguments": {"location": "Tokyo"}}}]},
174
+ {"role": "tool", "name": "get_current_time", "content": "06:22:48"},
175
+ {"role": "assistant", "content": "The current time in Tokyo is 06:22 AM."},
176
+ ],
177
+ [
178
+ {"role": "user", "content": "Is the air clean today in Lisbon?"},
179
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_air_quality_index", "arguments": {"location": "Lisbon, Portugal"}}}]},
180
+ {"role": "tool", "name": "get_air_quality_index", "content": "53"},
181
+ {"role": "assistant", "content": "The air quality is moderate."},
182
+ ],
183
+ [
184
+ {"role": "user", "content": "Play some music."},
185
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "play_music", "arguments": {"title": "Take Five", "artist": "Dave Brubeck"}}}]},
186
+ {"role": "tool", "name": "play_music", "content": "{'status': 'Playing'}"},
187
+ {"role": "assistant", "content": "Enjoy the jazz tunes!"},
188
+ ],
189
+ [
190
+ {"role": "user", "content": "What's the weather like tomorrow in Berlin?"},
191
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_weather_forecast", "arguments": {"city": "Berlin", "date": "2025-06-16"}}}]},
192
+ {"role": "tool", "name": "get_weather_forecast", "content": "{'temperature': 22, 'condition': 'partly cloudy'}"},
193
+ {"role": "assistant", "content": "Tomorrow in Berlin will be partly cloudy with a high of 22°C."}
194
+ ],
195
+ [
196
+ {"role": "user", "content": "Turn on the living room lights."},
197
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "control_light", "arguments": {"room": "living room", "state": "on"}}}]},
198
+ {"role": "tool", "name": "control_light", "content": "{'state': 'on'}"},
199
+ {"role": "assistant", "content": "The living room lights are now on."}
200
+ ],
201
+ [
202
+ {"role": "user", "content": "Remind me to call mom at 7 PM."},
203
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "create_reminder", "arguments": {"time": "19:00", "note": "Call mom"}}}]},
204
+ {"role": "tool", "name": "create_reminder", "content": "Reminder set"},
205
+ {"role": "assistant", "content": "Okay, I'll remind you to call mom at 7 PM."}
206
+ ],
207
+ [
208
+ {"role": "user", "content": "How strong is the wind in Chicago right now?"},
209
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_wind_conditions", "arguments": {"city": "Chicago", "unit": "mph"}}}]},
210
+ {"role": "tool", "name": "get_wind_conditions", "content": "(14, 'NW')"},
211
+ {"role": "assistant", "content": "The wind in Chicago is blowing at 14 mph from the northwest."}
212
+ ]
213
+ ],
214
+ "tools": [
215
+ [start_timer, create_reminder],
216
+ [get_current_time],
217
+ [get_air_quality_index, get_weather_forecast, get_wind_conditions],
218
+ [play_music, control_light],
219
+ [get_weather_forecast, get_wind_conditions],
220
+ [control_light],
221
+ [start_timer, create_reminder],
222
+ [get_weather_forecast, get_wind_conditions],
223
+ ]
224
+ }, on_mixed_types="use_json")
225
+ language_modeling_dataset = language_modeling_dataset.train_test_split(test_size=test_size, shuffle=False)
226
+ if push_to_hub:
227
+ language_modeling_dataset.push_to_hub(repo_id, config_name="language_modeling")
228
+
229
+ preference_dataset = Dataset.from_dict({
230
+ "prompt": [
231
+ [{"role": "user", "content": "Set a timer for 10 minutes."}],
232
+ [{"role": "user", "content": "What time is it in Tokyo?"}],
233
+ [{"role": "user", "content": "Is the air clean today in Lisbon?"}],
234
+ [{"role": "user", "content": "Play some music."}],
235
+ [{"role": "user", "content": "What's the weather like tomorrow in Berlin?"}],
236
+ [{"role": "user", "content": "Turn on the living room lights."}],
237
+ [{"role": "user", "content": "Remind me to call mom at 7 PM."}],
238
+ [{"role": "user", "content": "How strong is the wind in Chicago right now?"}],
239
+ ],
240
+ "chosen": [
241
+ [
242
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "start_timer", "arguments": {"duration": 600}}}]},
243
+ {"role": "tool", "name": "start_timer", "content": "600"},
244
+ {"role": "assistant", "content": "Timer set for 10 minutes."},
245
+ ],
246
+ [
247
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_current_time", "arguments": {"location": "Tokyo"}}}]},
248
+ {"role": "tool", "name": "get_current_time", "content": "06:22:48"},
249
+ {"role": "assistant", "content": "The current time in Tokyo is 06:22 AM."},
250
+ ],
251
+ [
252
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_air_quality_index", "arguments": {"location": "Lisbon, Portugal"}}}]},
253
+ {"role": "tool", "name": "get_air_quality_index", "content": "53"},
254
+ {"role": "assistant", "content": "The air quality is moderate."},
255
+ ],
256
+ [
257
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "play_music", "arguments": {"title": "Take Five", "artist": "Dave Brubeck"}}}]},
258
+ {"role": "tool", "name": "play_music", "content": "{'status': 'Playing'}"},
259
+ {"role": "assistant", "content": "Enjoy the jazz tunes!"},
260
+ ],
261
+ [
262
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_weather_forecast", "arguments": {"city": "Berlin", "date": "2025-06-16"}}}]},
263
+ {"role": "tool", "name": "get_weather_forecast", "content": "{'temperature': 22, 'condition': 'partly cloudy'}"},
264
+ {"role": "assistant", "content": "Tomorrow in Berlin will be partly cloudy with a high of 22°C."}
265
+ ],
266
+ [
267
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "control_light", "arguments": {"room": "living room", "state": "on"}}}]},
268
+ {"role": "tool", "name": "control_light", "content": "{'state': 'on'}"},
269
+ {"role": "assistant", "content": "The living room lights are now on."}
270
+ ],
271
+ [
272
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "create_reminder", "arguments": {"time": "19:00", "note": "Call mom"}}}]},
273
+ {"role": "tool", "name": "create_reminder", "content": "Reminder set"},
274
+ {"role": "assistant", "content": "Okay, I’ll remind you to call mom at 7 PM."}
275
+ ],
276
+ [
277
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_wind_conditions", "arguments": {"city": "Chicago", "unit": "mph"}}}]},
278
+ {"role": "tool", "name": "get_wind_conditions", "content": "(14, 'NW')"},
279
+ {"role": "assistant", "content": "The wind in Chicago is blowing at 14 mph from the northwest."}
280
+ ],
281
+ ],
282
+ "rejected": [
283
+ [
284
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "start_timer", "arguments": {"duration": 10}}}]},
285
+ {"role": "tool", "name": "start_timer", "content": "10"},
286
+ {"role": "assistant", "content": "Timer set for 10 seconds."},
287
+ ],
288
+ [
289
+ {"role": "assistant", "content": "It is 6:22 AM in Tokyo."},
290
+ ],
291
+ [
292
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_air_quality_index", "arguments": {"location": "Lisbon"}}}]},
293
+ {"role": "tool", "name": "get_air_quality_index", "content": "53"},
294
+ {"role": "assistant", "content": "The air quality is great."},
295
+ ],
296
+ [
297
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "play_music", "arguments": {"title": "Take Five", "artist": "Daft Punk"}}}]},
298
+ {"role": "tool", "name": "play_music", "content": "{'status': 'Playing'}"},
299
+ {"role": "assistant", "content": "Playing your song."},
300
+ ],
301
+ [
302
+ {"role": "assistant", "content": "Tomorrow in Berlin will be hot and sunny."},
303
+ ],
304
+ [
305
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "control_light", "arguments": {"room": "living room", "state": "off"}}}]},
306
+ {"role": "tool", "name": "control_light", "content": "{'state': 'off'}"},
307
+ {"role": "assistant", "content": "The living room lights are now off."}
308
+ ],
309
+ [
310
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "create_reminder", "arguments": {"time": "07:00", "note": "Call mom"}}}]},
311
+ {"role": "tool", "name": "create_reminder", "content": "Reminder set"},
312
+ {"role": "assistant", "content": "Okay, I'll remind you to call mom at 7 AM."}
313
+ ],
314
+ [
315
+ {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_weather_forecast", "arguments": {"city": "Chicago", "date": "2025-06-16"}}}]},
316
+ {"role": "tool", "name": "get_weather_forecast", "content": "{'temperature': 22, 'condition': 'partly cloudy'}"},
317
+ {"role": "assistant", "content": "Tomorrow in Chicago will be partly cloudy with a high of 22°C."}
318
+ ],
319
+ ],
320
+ "tools": [
321
+ [start_timer],
322
+ [get_current_time],
323
+ [get_air_quality_index],
324
+ [play_music],
325
+ [get_weather_forecast],
326
+ [control_light],
327
+ [create_reminder],
328
+ [get_wind_conditions],
329
+ ],
330
+ }, on_mixed_types="use_json")
331
+ preference_dataset = preference_dataset.train_test_split(test_size=test_size, shuffle=False)
332
+ if push_to_hub:
333
+ preference_dataset.push_to_hub(repo_id, config_name="preference")
334
+ # fmt: on
335
+
336
+
337
+ if __name__ == "__main__":
338
+ parser = HfArgumentParser(ScriptArguments)
339
+ script_args = parser.parse_args_into_dataclasses()[0]
340
+ main(script_args.test_size, script_args.push_to_hub, script_args.repo_id)
tasks/tasksmith-0ea2241cceeb/environment/source/scripts/generate_zen_dataset.py ADDED
@@ -0,0 +1,660 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+
17
+ from datasets import Dataset
18
+ from transformers import HfArgumentParser
19
+
20
+
21
+ @dataclass
22
+ class ScriptArguments:
23
+ r"""
24
+ Arguments for the script.
25
+
26
+ Args:
27
+ test_size (`float`, *optional*, defaults to `0.1`):
28
+ Fraction of the dataset to include in the test split.
29
+ push_to_hub (`bool`, *optional*, defaults to `False`):
30
+ Whether to push the dataset to the Hugging Face Hub.
31
+ repo_id (`str`, *optional*, defaults to `"trl-internal-testing/zen"`):
32
+ Hugging Face repository ID to push the dataset to.
33
+ """
34
+
35
+ test_size: float = field(
36
+ default=0.1,
37
+ metadata={"help": "Fraction of the dataset to include in the test split."},
38
+ )
39
+ push_to_hub: bool = field(
40
+ default=False,
41
+ metadata={"help": "Whether to push the dataset to the Hugging Face Hub."},
42
+ )
43
+ repo_id: str = field(
44
+ default="trl-internal-testing/zen",
45
+ metadata={"help": "Hugging Face repository ID to push the dataset to."},
46
+ )
47
+
48
+
49
+ def main(test_size, push_to_hub, repo_id):
50
+ # fmt: off
51
+ standard_language_modeling_dataset = Dataset.from_dict({
52
+ "text": [
53
+ "Beautiful is better than ugly.",
54
+ "Explicit is better than implicit.",
55
+ "Simple is better than complex.",
56
+ "Complex is better than complicated.",
57
+ "Flat is better than nested.",
58
+ "Sparse is better than dense.",
59
+ "Readability counts.",
60
+ "Special cases aren't special enough to break the rules.",
61
+ "Although practicality beats purity.",
62
+ "Errors should never pass silently.",
63
+ "Unless explicitly silenced.",
64
+ "In the face of ambiguity, refuse the temptation to guess.",
65
+ "There should be one-- and preferably only one --obvious way to do it.",
66
+ "Although that way may not be obvious at first unless you're Dutch.",
67
+ "Now is better than never.",
68
+ "Although never is often better than *right* now.",
69
+ "If the implementation is hard to explain, it's a bad idea.",
70
+ "If the implementation is easy to explain, it may be a good idea.",
71
+ "Namespaces are one honking great idea -- let's do more of those!",
72
+ ],
73
+ })
74
+ standard_language_modeling_dataset = standard_language_modeling_dataset.train_test_split(test_size=test_size, shuffle=False)
75
+ if push_to_hub:
76
+ standard_language_modeling_dataset.push_to_hub(repo_id, config_name="standard_language_modeling")
77
+
78
+ standard_prompt_only_dataset = Dataset.from_dict({
79
+ "prompt": [
80
+ "Beautiful is better than",
81
+ "Explicit is",
82
+ "Simple is better",
83
+ "Complex",
84
+ "Flat is better than",
85
+ "Sparse is better",
86
+ "Readability",
87
+ "Special cases aren't special",
88
+ "Although practicality beats",
89
+ "Errors should never",
90
+ "Unless explicitly",
91
+ "In the face of ambiguity, refuse",
92
+ "There should be one-- and preferably",
93
+ "Although that way may not be obvious at first unless you're",
94
+ "Now is",
95
+ "Although never is often",
96
+ "If the implementation is hard to explain,",
97
+ "If the implementation is easy",
98
+ "Namespaces are one honking great",
99
+ ],
100
+ })
101
+ standard_prompt_only_dataset = standard_prompt_only_dataset.train_test_split(test_size=test_size, shuffle=False)
102
+ if push_to_hub:
103
+ standard_prompt_only_dataset.push_to_hub(repo_id, config_name="standard_prompt_only")
104
+
105
+ standard_prompt_completion_dataset = Dataset.from_dict({
106
+ "prompt": [
107
+ "Beautiful is better than",
108
+ "Explicit is",
109
+ "Simple is better",
110
+ "Complex",
111
+ "Flat is better than",
112
+ "Sparse is better",
113
+ "Readability",
114
+ "Special cases aren't special",
115
+ "Although practicality beats",
116
+ "Errors should never",
117
+ "Unless explicitly",
118
+ "In the face of ambiguity, refuse",
119
+ "There should be one-- and preferably",
120
+ "Although that way may not be obvious at first unless you're",
121
+ "Now is",
122
+ "Although never is often",
123
+ "If the implementation is hard to explain,",
124
+ "If the implementation is easy",
125
+ "Namespaces are one honking great",
126
+ ],
127
+ "completion": [
128
+ " ugly.",
129
+ " better than implicit.",
130
+ " than complex.",
131
+ " is better than complicated.",
132
+ " nested.",
133
+ " than dense.",
134
+ " counts.",
135
+ " enough to break the rules.",
136
+ " purity.",
137
+ " pass silently.",
138
+ " silenced.",
139
+ " the temptation to guess.",
140
+ " only one --obvious way to do it.",
141
+ " Dutch.",
142
+ " better than never.",
143
+ " better than *right* now.",
144
+ " it's a bad idea.",
145
+ " to explain, it may be a good idea.",
146
+ " idea -- let's do more of those!",
147
+ ],
148
+ })
149
+ standard_prompt_completion_dataset = standard_prompt_completion_dataset.train_test_split(test_size=test_size, shuffle=False)
150
+ if push_to_hub:
151
+ standard_prompt_completion_dataset.push_to_hub(repo_id, config_name="standard_prompt_completion")
152
+
153
+ standard_preference_dataset = Dataset.from_dict({
154
+ "prompt": [
155
+ "Beautiful is better than",
156
+ "Explicit is",
157
+ "Simple is better",
158
+ "Complex",
159
+ "Flat is better than",
160
+ "Sparse is better",
161
+ "Readability",
162
+ "Special cases aren't special",
163
+ "Although practicality beats",
164
+ "Errors should never",
165
+ "Unless explicitly",
166
+ "In the face of ambiguity, refuse",
167
+ "There should be one-- and preferably",
168
+ "Although that way may not be obvious at first unless you're",
169
+ "Now is",
170
+ "Although never is often",
171
+ "If the implementation is hard to explain,",
172
+ "If the implementation is easy",
173
+ "Namespaces are one honking great",
174
+ ],
175
+ "chosen": [
176
+ " ugly.",
177
+ " better than implicit.",
178
+ " than complex.",
179
+ " is better than complicated.",
180
+ " nested.",
181
+ " than dense.",
182
+ " counts.",
183
+ " enough to break the rules.",
184
+ " purity.",
185
+ " pass silently.",
186
+ " silenced.",
187
+ " the temptation to guess.",
188
+ " only one --obvious way to do it.",
189
+ " Dutch.",
190
+ " better than never.",
191
+ " better than *right* now.",
192
+ " it's a bad idea.",
193
+ " to explain, it may be a good idea.",
194
+ " idea -- let's do more of those!",
195
+ ],
196
+ "rejected": [
197
+ " the moon.",
198
+ " worse than nothing.",
199
+ " than a long vacation.",
200
+ " is always the answer.",
201
+ " chocolate.",
202
+ " without any context.",
203
+ " is optional.",
204
+ " enough to become unicorns.",
205
+ " reality.",
206
+ " pass their driving test.",
207
+ " forgotten.",
208
+ " the opportunity to laugh.",
209
+ " two or more confusing methods.",
210
+ " a time traveler.",
211
+ " never better.",
212
+ " not even a possibility.",
213
+ " it's clearly the best choice.",
214
+ " it's probably magic.",
215
+ " watermelon -- let's plant some!",
216
+ ],
217
+ })
218
+ standard_preference_dataset = standard_preference_dataset.train_test_split(test_size=test_size, shuffle=False)
219
+ if push_to_hub:
220
+ standard_preference_dataset.push_to_hub(repo_id, config_name="standard_preference")
221
+
222
+ standard_implicit_prompt_preference_dataset = Dataset.from_dict({
223
+ "chosen": [
224
+ "Beautiful is better than ugly.",
225
+ "Explicit is better than implicit.",
226
+ "Simple is better than complex.",
227
+ "Complex is better than complicated.",
228
+ "Flat is better than nested.",
229
+ "Sparse is better than dense.",
230
+ "Readability counts.",
231
+ "Special cases aren't special enough to break the rules.",
232
+ "Although practicality beats purity.",
233
+ "Errors should never pass silently.",
234
+ "Unless explicitly silenced.",
235
+ "In the face of ambiguity, refuse the temptation to guess.",
236
+ "There should be one-- and preferably only one --obvious way to do it.",
237
+ "Although that way may not be obvious at first unless you're Dutch.",
238
+ "Now is better than never.",
239
+ "Although never is often better than *right* now.",
240
+ "If the implementation is hard to explain, it's a bad idea.",
241
+ "If the implementation is easy to explain, it may be a good idea.",
242
+ "Namespaces are one honking great idea -- let's do more of those!",
243
+ ],
244
+ "rejected": [
245
+ "Beautiful is better than the moon.",
246
+ "Explicit is worse than nothing.",
247
+ "Simple is better than a long vacation.",
248
+ "Complex is always the answer.",
249
+ "Flat is better than chocolate.",
250
+ "Sparse is better without any context.",
251
+ "Readability is optional.",
252
+ "Special cases aren't special enough to become unicorns.",
253
+ "Although practicality beats reality.",
254
+ "Errors should never pass their driving test.",
255
+ "Unless explicitly forgotten.",
256
+ "In the face of ambiguity, refuse the opportunity to laugh.",
257
+ "There should be one-- and preferably two or more confusing methods.",
258
+ "Although that way may not be obvious at first unless you're a time traveler.",
259
+ "Now is never better.",
260
+ "Although never is often not even a possibility.",
261
+ "If the implementation is hard to explain, it's clearly the best choice.",
262
+ "If the implementation is easy it's probably magic.",
263
+ "Namespaces are one honking great watermelon -- let's plant some!",
264
+ ],
265
+ })
266
+ standard_implicit_prompt_preference_dataset = standard_implicit_prompt_preference_dataset.train_test_split(test_size=test_size, shuffle=False)
267
+ if push_to_hub:
268
+ standard_implicit_prompt_preference_dataset.push_to_hub(repo_id, config_name="standard_implicit_prompt_preference")
269
+
270
+ standard_unpaired_preference_dataset = Dataset.from_dict({
271
+ "prompt": [
272
+ "Beautiful is better than",
273
+ "Explicit is",
274
+ "Simple is better",
275
+ "Complex",
276
+ "Flat is better than",
277
+ "Sparse is better",
278
+ "Readability",
279
+ "Special cases aren't special",
280
+ "Although practicality beats",
281
+ "Errors should never",
282
+ "Unless explicitly",
283
+ "In the face of ambiguity, refuse",
284
+ "There should be one-- and preferably",
285
+ "Although that way may not be obvious at first unless you're",
286
+ "Now is",
287
+ "Although never is often",
288
+ "If the implementation is hard to explain,",
289
+ "If the implementation is easy",
290
+ "Namespaces are one honking great",
291
+ ],
292
+ "completion": [
293
+ " ugly.",
294
+ " worse than nothing.",
295
+ " than a long vacation.",
296
+ " is better than complicated.",
297
+ " nested.",
298
+ " without any context.",
299
+ " counts.",
300
+ " enough to become unicorns.",
301
+ " purity.",
302
+ " pass silently.",
303
+ " forgotten.",
304
+ " the temptation to guess.",
305
+ " only one --obvious way to do it.",
306
+ " a time traveler.",
307
+ " better than never.",
308
+ " not even a possibility.",
309
+ " it's a bad idea.",
310
+ " it's probably magic.",
311
+ " watermelon -- let's plant some!",
312
+ ],
313
+ "label": [True, False, False, True, True, False, True, False, True, True, False, True, True, False, True, False, True, False, False],
314
+ })
315
+ standard_unpaired_preference_dataset = standard_unpaired_preference_dataset.train_test_split(test_size=test_size, shuffle=False)
316
+ if push_to_hub:
317
+ standard_unpaired_preference_dataset.push_to_hub(repo_id, config_name="standard_unpaired_preference")
318
+
319
+ standard_stepwise_supervision_dataset = Dataset.from_dict({
320
+ "prompt": [
321
+ "Beautiful is better than",
322
+ "Explicit is better than",
323
+ "Simple is better than",
324
+ "Complex is better than",
325
+ "Flat is better than",
326
+ "Sparse is better than",
327
+ "Readability counts",
328
+ "Special cases aren't special enough",
329
+ "Although practicality beats",
330
+ "Errors should never pass",
331
+ "In the face of ambiguity, refuse",
332
+ "There should be one-- and preferably only one --",
333
+ "Although that way may not be",
334
+ "Now is better than",
335
+ "Never is often better than",
336
+ "If the implementation is hard to explain, it's",
337
+ "If the implementation is easy to explain, it",
338
+ "Namespaces are one",
339
+ "Although practicality sometimes beats purity,",
340
+ ],
341
+ "completions": [
342
+ [", let me think...", " ugly."],
343
+ [", of course,", " implicit.", " because clarity matters."],
344
+ ["... let's keep it basic,", " complex."],
345
+ [" when needed,", " complicated."],
346
+ [" in terms of structure,", " nested."],
347
+ ["... especially for readability."],
348
+ [" especially when others read it."],
349
+ [", unless...", " they follow the rules."],
350
+ [" some theoretical elegance,", " purity."],
351
+ [" silently,", " unless explicitly silenced."],
352
+ [" the temptation to guess."],
353
+ [" way to do it,", " but sometimes it's not obvious.", " especially when there's more than one possibility."],
354
+ [" clear at first,", " it will eventually emerge."],
355
+ [" later."],
356
+ [" problematic fixes."],
357
+ [" likely because it's too complicated."],
358
+ [" might be a good design."],
359
+ [" of those great ideas,", " that solve many problems."],
360
+ [" the code should still aim for balance."],
361
+ ],
362
+ "labels": [
363
+ [False, True],
364
+ [False, True, False],
365
+ [False, True],
366
+ [True, True],
367
+ [True, False],
368
+ [True],
369
+ [False],
370
+ [True, False],
371
+ [False, False],
372
+ [False, False],
373
+ [True],
374
+ [True, True, False],
375
+ [True, True],
376
+ [False],
377
+ [True], [False],
378
+ [False],
379
+ [True, True],
380
+ [False]
381
+ ]
382
+ })
383
+ standard_stepwise_supervision_dataset = standard_stepwise_supervision_dataset.train_test_split(test_size=test_size, shuffle=False)
384
+ if push_to_hub:
385
+ standard_stepwise_supervision_dataset.push_to_hub(repo_id, config_name="standard_stepwise_supervision")
386
+
387
+ conversational_language_modeling_dataset = Dataset.from_dict({
388
+ "messages": [
389
+ [{"role": "user", "content": "What is better than ugly?"}, {"role": "assistant", "content": "Beautiful."},],
390
+ [{"role": "user", "content": "What is better than implicit?"}, {"role": "assistant", "content": "Explicit."}],
391
+ [{"role": "user", "content": "What is better than complex?"}, {"role": "assistant", "content": "Simple."}],
392
+ [{"role": "user", "content": "What is better than complicated?"}, {"role": "assistant", "content": "Complex."}],
393
+ [{"role": "user", "content": "What is better than nested?"}, {"role": "assistant", "content": "Flat."}],
394
+ [{"role": "user", "content": "What is better than dense?"}, {"role": "assistant", "content": "Sparse."}],
395
+ [{"role": "user", "content": "What counts?"}, {"role": "assistant", "content": "Readability."}],
396
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}, {"role": "assistant", "content": "No, special cases aren't special enough to break the rules."}],
397
+ [{"role": "user", "content": "What beats purity?"}, {"role": "assistant", "content": "Practicality."}],
398
+ [{"role": "user", "content": "What should never pass silently?"}, {"role": "assistant", "content": "Errors."}],
399
+ [{"role": "user", "content": "When can errors pass silently?"}, {"role": "assistant", "content": "When explicitly silenced."}],
400
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}, {"role": "assistant", "content": "Refuse the temptation to guess."}],
401
+ [{"role": "user", "content": "How many ways should there be to do it?"}, {"role": "assistant", "content": "One, and preferably only one."}],
402
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}, {"role": "assistant", "content": "Dutch."}],
403
+ [{"role": "user", "content": "What is better than never?"}, {"role": "assistant", "content": "Now is better than never."}],
404
+ [{"role": "user", "content": "Is never better than *right* now?"}, {"role": "assistant", "content": "Yes, often."}],
405
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}, {"role": "assistant", "content": "It means it's a bad idea."}],
406
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}, {"role": "assistant", "content": "It means it may be a good idea."}],
407
+ [{"role": "user", "content": "Any great ideas?"}, {"role": "assistant", "content": "Namespaces are one honking great idea."}],
408
+ ],
409
+ })
410
+ conversational_language_modeling_dataset = conversational_language_modeling_dataset.train_test_split(test_size=test_size, shuffle=False)
411
+ if push_to_hub:
412
+ conversational_language_modeling_dataset.push_to_hub(repo_id, config_name="conversational_language_modeling")
413
+
414
+ conversational_prompt_only_dataset = Dataset.from_dict({
415
+ "prompt": [
416
+ [{"role": "user", "content": "What is better than ugly?"}],
417
+ [{"role": "user", "content": "What is better than implicit?"}],
418
+ [{"role": "user", "content": "What is better than complex?"}],
419
+ [{"role": "user", "content": "What is better than complicated?"}],
420
+ [{"role": "user", "content": "What is better than nested?"}],
421
+ [{"role": "user", "content": "What is better than dense?"}],
422
+ [{"role": "user", "content": "What counts?"}],
423
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}],
424
+ [{"role": "user", "content": "What beats purity?"}],
425
+ [{"role": "user", "content": "What should never pass silently?"}],
426
+ [{"role": "user", "content": "When can errors pass silently?"}],
427
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}],
428
+ [{"role": "user", "content": "How many ways should there be to do it?"}],
429
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}],
430
+ [{"role": "user", "content": "What is better than never?"}],
431
+ [{"role": "user", "content": "Is never better than *right* now?"}],
432
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}],
433
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}],
434
+ [{"role": "user", "content": "Any great ideas?"}],
435
+ ],
436
+ })
437
+ conversational_prompt_only_dataset = conversational_prompt_only_dataset.train_test_split(test_size=test_size, shuffle=False)
438
+ if push_to_hub:
439
+ conversational_prompt_only_dataset.push_to_hub(repo_id, config_name="conversational_prompt_only")
440
+
441
+ conversational_prompt_completion_dataset = Dataset.from_dict({
442
+ "prompt": [
443
+ [{"role": "user", "content": "What is better than ugly?"}],
444
+ [{"role": "user", "content": "What is better than implicit?"}],
445
+ [{"role": "user", "content": "What is better than complex?"}],
446
+ [{"role": "user", "content": "What is better than complicated?"}],
447
+ [{"role": "user", "content": "What is better than nested?"}],
448
+ [{"role": "user", "content": "What is better than dense?"}],
449
+ [{"role": "user", "content": "What counts?"}],
450
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}],
451
+ [{"role": "user", "content": "What beats purity?"}],
452
+ [{"role": "user", "content": "What should never pass silently?"}],
453
+ [{"role": "user", "content": "When can errors pass silently?"}],
454
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}],
455
+ [{"role": "user", "content": "How many ways should there be to do it?"}],
456
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}],
457
+ [{"role": "user", "content": "What is better than never?"}],
458
+ [{"role": "user", "content": "Is never better than *right* now?"}],
459
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}],
460
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}],
461
+ [{"role": "user", "content": "Any great ideas?"}],
462
+ ],
463
+ "completion": [
464
+ [{"role": "assistant", "content": "Beautiful."}],
465
+ [{"role": "assistant", "content": "Explicit."}],
466
+ [{"role": "assistant", "content": "Simple."}],
467
+ [{"role": "assistant", "content": "Complex."}],
468
+ [{"role": "assistant", "content": "Flat."}],
469
+ [{"role": "assistant", "content": "Sparse."}],
470
+ [{"role": "assistant", "content": "Readability."}],
471
+ [{"role": "assistant", "content": "No, special cases aren't special enough to break the rules."}],
472
+ [{"role": "assistant", "content": "Practicality."}],
473
+ [{"role": "assistant", "content": "Errors."}],
474
+ [{"role": "assistant", "content": "When explicitly silenced."}],
475
+ [{"role": "assistant", "content": "Refuse the temptation to guess."}],
476
+ [{"role": "assistant", "content": "One, and preferably only one."}],
477
+ [{"role": "assistant", "content": "Dutch."}],
478
+ [{"role": "assistant", "content": "Now is better than never."}],
479
+ [{"role": "assistant", "content": "Yes, often."}],
480
+ [{"role": "assistant", "content": "It means it's a bad idea."}],
481
+ [{"role": "assistant", "content": "It means it may be a good idea."}],
482
+ [{"role": "assistant", "content": "Namespaces are one honking great idea."}],
483
+ ],
484
+ })
485
+ conversational_prompt_completion_dataset = conversational_prompt_completion_dataset.train_test_split(test_size=test_size, shuffle=False)
486
+ if push_to_hub:
487
+ conversational_prompt_completion_dataset.push_to_hub(repo_id, config_name="conversational_prompt_completion")
488
+
489
+ conversational_preference_dataset = Dataset.from_dict({
490
+ "prompt": [
491
+ [{"role": "user", "content": "What is better than ugly?"}],
492
+ [{"role": "user", "content": "What is better than implicit?"}],
493
+ [{"role": "user", "content": "What is better than complex?"}],
494
+ [{"role": "user", "content": "What is better than complicated?"}],
495
+ [{"role": "user", "content": "What is better than nested?"}],
496
+ [{"role": "user", "content": "What is better than dense?"}],
497
+ [{"role": "user", "content": "What counts?"}],
498
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}],
499
+ [{"role": "user", "content": "What beats purity?"}],
500
+ [{"role": "user", "content": "What should never pass silently?"}],
501
+ [{"role": "user", "content": "When can errors pass silently?"}],
502
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}],
503
+ [{"role": "user", "content": "How many ways should there be to do it?"}],
504
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}],
505
+ [{"role": "user", "content": "What is better than never?"}],
506
+ [{"role": "user", "content": "Is never better than *right* now?"}],
507
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}],
508
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}],
509
+ [{"role": "user", "content": "Any great ideas?"}],
510
+ ],
511
+ "chosen": [
512
+ [{"role": "assistant", "content": "Beautiful."}],
513
+ [{"role": "assistant", "content": "Explicit."}],
514
+ [{"role": "assistant", "content": "Simple."}],
515
+ [{"role": "assistant", "content": "Complex."}],
516
+ [{"role": "assistant", "content": "Flat."}],
517
+ [{"role": "assistant", "content": "Sparse."}],
518
+ [{"role": "assistant", "content": "Readability."}],
519
+ [{"role": "assistant", "content": "No, special cases aren't special enough to break the rules."}],
520
+ [{"role": "assistant", "content": "Practicality."}],
521
+ [{"role": "assistant", "content": "Errors."}],
522
+ [{"role": "assistant", "content": "When explicitly silenced."}],
523
+ [{"role": "assistant", "content": "Refuse the temptation to guess."}],
524
+ [{"role": "assistant", "content": "One, and preferably only one."}],
525
+ [{"role": "assistant", "content": "Dutch."}],
526
+ [{"role": "assistant", "content": "Now is better than never."}],
527
+ [{"role": "assistant", "content": "Yes, often."}],
528
+ [{"role": "assistant", "content": "It means it's a bad idea."}],
529
+ [{"role": "assistant", "content": "It means it may be a good idea."}],
530
+ [{"role": "assistant", "content": "Namespaces are one honking great idea."}],
531
+ ],
532
+ "rejected": [
533
+ [{"role": "assistant", "content": "Acceptable."}],
534
+ [{"role": "assistant", "content": "Explained."}],
535
+ [{"role": "assistant", "content": "Very complex."}],
536
+ [{"role": "assistant", "content": "Very complicated."}],
537
+ [{"role": "assistant", "content": "Circular."}],
538
+ [{"role": "assistant", "content": "Heavy."}],
539
+ [{"role": "assistant", "content": "Looking complicated."}],
540
+ [{"role": "assistant", "content": "Yes, special cases are special enough to break the rules."}],
541
+ [{"role": "assistant", "content": "Nothing."}],
542
+ [{"role": "assistant", "content": "Warnings."}],
543
+ [{"role": "assistant", "content": "Never."}],
544
+ [{"role": "assistant", "content": "Give up."}],
545
+ [{"role": "assistant", "content": "As many as possible."}],
546
+ [{"role": "assistant", "content": "French."}],
547
+ [{"role": "assistant", "content": "Some day."}],
548
+ [{"role": "assistant", "content": "No, never."}],
549
+ [{"role": "assistant", "content": "It means it's a good idea."}],
550
+ [{"role": "assistant", "content": "It means it's a bad idea."}],
551
+ [{"role": "assistant", "content": "Recursion."}],
552
+ ],
553
+ })
554
+ conversational_preference_dataset = conversational_preference_dataset.train_test_split(test_size=test_size, shuffle=False)
555
+ if push_to_hub:
556
+ conversational_preference_dataset.push_to_hub(repo_id, config_name="conversational_preference")
557
+
558
+ conversational_implicit_prompt_preference_dataset = Dataset.from_dict({
559
+ "chosen": [
560
+ [{"role": "user", "content": "What is better than ugly?"}, {"role": "assistant", "content": "Beautiful."}],
561
+ [{"role": "user", "content": "What is better than implicit?"}, {"role": "assistant", "content": "Explicit."}],
562
+ [{"role": "user", "content": "What is better than complex?"}, {"role": "assistant", "content": "Simple."}],
563
+ [{"role": "user", "content": "What is better than complicated?"}, {"role": "assistant", "content": "Complex."}],
564
+ [{"role": "user", "content": "What is better than nested?"}, {"role": "assistant", "content": "Flat."}],
565
+ [{"role": "user", "content": "What is better than dense?"}, {"role": "assistant", "content": "Sparse."}],
566
+ [{"role": "user", "content": "What counts?"}, {"role": "assistant", "content": "Readability."}],
567
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}, {"role": "assistant", "content": "No, special cases aren't special enough to break the rules."}],
568
+ [{"role": "user", "content": "What beats purity?"}, {"role": "assistant", "content": "Practicality."}],
569
+ [{"role": "user", "content": "What should never pass silently?"}, {"role": "assistant", "content": "Errors."}],
570
+ [{"role": "user", "content": "When can errors pass silently?"}, {"role": "assistant", "content": "When explicitly silenced."}],
571
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}, {"role": "assistant", "content": "Refuse the temptation to guess."}],
572
+ [{"role": "user", "content": "How many ways should there be to do it?"}, {"role": "assistant", "content": "One, and preferably only one."}],
573
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}, {"role": "assistant", "content": "Dutch."}],
574
+ [{"role": "user", "content": "What is better than never?"}, {"role": "assistant", "content": "Now is better than never."}],
575
+ [{"role": "user", "content": "Is never better than *right* now?"}, {"role": "assistant", "content": "Yes, often."}],
576
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}, {"role": "assistant", "content": "It means it's a bad idea."}],
577
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}, {"role": "assistant", "content": "It means it may be a good idea."}],
578
+ [{"role": "user", "content": "Any great ideas?"}, {"role": "assistant", "content": "Namespaces are one honking great idea."}],
579
+ ],
580
+ "rejected": [
581
+ [{"role": "user", "content": "What is better than ugly?"}, {"role": "assistant", "content": "Acceptable."}],
582
+ [{"role": "user", "content": "What is better than implicit?"}, {"role": "assistant", "content": "Explained."}],
583
+ [{"role": "user", "content": "What is better than complex?"}, {"role": "assistant", "content": "Very complex."}],
584
+ [{"role": "user", "content": "What is better than complicated?"}, {"role": "assistant", "content": "Very complicated."}],
585
+ [{"role": "user", "content": "What is better than nested?"}, {"role": "assistant", "content": "Circular."}],
586
+ [{"role": "user", "content": "What is better than dense?"}, {"role": "assistant", "content": "Heavy."}],
587
+ [{"role": "user", "content": "What counts?"}, {"role": "assistant", "content": "Looking complicated."}],
588
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}, {"role": "assistant", "content": "Yes, special cases are special enough to break the rules."}],
589
+ [{"role": "user", "content": "What beats purity?"}, {"role": "assistant", "content": "Nothing."}],
590
+ [{"role": "user", "content": "What should never pass silently?"}, {"role": "assistant", "content": "Warnings."}],
591
+ [{"role": "user", "content": "When can errors pass silently?"}, {"role": "assistant", "content": "Never."}],
592
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}, {"role": "assistant", "content": "Give up."}],
593
+ [{"role": "user", "content": "How many ways should there be to do it?"}, {"role": "assistant", "content": "As many as possible."}],
594
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}, {"role": "assistant", "content": "French."}],
595
+ [{"role": "user", "content": "What is better than never?"}, {"role": "assistant", "content": "Some day."}],
596
+ [{"role": "user", "content": "Is never better than *right* now?"}, {"role": "assistant", "content": "No, never."}],
597
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}, {"role": "assistant", "content": "It means it's a good idea."}],
598
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}, {"role": "assistant", "content": "It means it's a bad idea."}],
599
+ [{"role": "user", "content": "Any great ideas?"}, {"role": "assistant", "content": "Recursion."}],
600
+ ],
601
+ })
602
+ conversational_implicit_prompt_preference_dataset = conversational_implicit_prompt_preference_dataset.train_test_split(test_size=test_size, shuffle=False)
603
+ if push_to_hub:
604
+ conversational_implicit_prompt_preference_dataset.push_to_hub(repo_id, config_name="conversational_implicit_prompt_preference")
605
+
606
+ conversational_unpaired_preference_dataset = Dataset.from_dict({
607
+ "prompt": [
608
+ [{"role": "user", "content": "What is better than ugly?"}],
609
+ [{"role": "user", "content": "What is better than implicit?"}],
610
+ [{"role": "user", "content": "What is better than complex?"}],
611
+ [{"role": "user", "content": "What is better than complicated?"}],
612
+ [{"role": "user", "content": "What is better than nested?"}],
613
+ [{"role": "user", "content": "What is better than dense?"}],
614
+ [{"role": "user", "content": "What counts?"}],
615
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}],
616
+ [{"role": "user", "content": "What beats purity?"}],
617
+ [{"role": "user", "content": "What should never pass silently?"}],
618
+ [{"role": "user", "content": "When can errors pass silently?"}],
619
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}],
620
+ [{"role": "user", "content": "How many ways should there be to do it?"}],
621
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}],
622
+ [{"role": "user", "content": "What is better than never?"}],
623
+ [{"role": "user", "content": "Is never better than *right* now?"}],
624
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}],
625
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}],
626
+ [{"role": "user", "content": "Any great ideas?"}],
627
+ ],
628
+ "completion": [
629
+ [{'role': 'assistant', 'content': 'Beautiful.'}],
630
+ [{'role': 'assistant', 'content': 'Explicit.'}],
631
+ [{'role': 'assistant', 'content': 'Simple.'}],
632
+ [{'role': 'assistant', 'content': 'Very complicated.'}],
633
+ [{'role': 'assistant', 'content': 'Flat.'}],
634
+ [{'role': 'assistant', 'content': 'Sparse.'}],
635
+ [{'role': 'assistant', 'content': 'Readability.'}],
636
+ [{'role': 'assistant', 'content': 'Yes, special cases are special enough to break the rules.'}],
637
+ [{'role': 'assistant', 'content': 'Practicality.'}],
638
+ [{'role': 'assistant', 'content': 'Warnings.'}],
639
+ [{'role': 'assistant', 'content': 'When explicitly silenced.'}],
640
+ [{'role': 'assistant', 'content': 'Give up.'}],
641
+ [{'role': 'assistant', 'content': 'One, and preferably only one.'}],
642
+ [{'role': 'assistant', 'content': 'French.'}],
643
+ [{'role': 'assistant', 'content': 'Some day.'}],
644
+ [{'role': 'assistant', 'content': 'Yes, often.'}],
645
+ [{'role': 'assistant', 'content': "It means it's a bad idea."}],
646
+ [{'role': 'assistant', 'content': 'It means it may be a good idea.'}],
647
+ [{'role': 'assistant', 'content': 'Namespaces are one honking great idea.'}],
648
+ ],
649
+ "label": [True, True, True, False, True, True, True, False, True, False, True, False, True, False, False, True, True, True, True],
650
+ })
651
+ conversational_unpaired_preference_dataset = conversational_unpaired_preference_dataset.train_test_split(test_size=test_size, shuffle=False)
652
+ if push_to_hub:
653
+ conversational_unpaired_preference_dataset.push_to_hub(repo_id, config_name="conversational_unpaired_preference")
654
+ # fmt: on
655
+
656
+
657
+ if __name__ == "__main__":
658
+ parser = HfArgumentParser(ScriptArguments)
659
+ script_args = parser.parse_args_into_dataclasses()[0]
660
+ main(script_args.test_size, script_args.push_to_hub, script_args.repo_id)
tasks/tasksmith-0ea2241cceeb/environment/source/scripts/generate_zen_image_dataset.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+
17
+ import numpy as np
18
+ from datasets import Dataset, Features, Image, Value
19
+ from transformers import HfArgumentParser
20
+
21
+
22
+ Message = [{"content": Value("string"), "role": Value("string")}]
23
+
24
+
25
+ @dataclass
26
+ class ScriptArguments:
27
+ r"""
28
+ Arguments for the script.
29
+
30
+ Args:
31
+ test_size (`float`, *optional*, defaults to `0.1`):
32
+ Fraction of the dataset to include in the test split.
33
+ push_to_hub (`bool`, *optional*, defaults to `False`):
34
+ Whether to push the dataset to the Hugging Face Hub.
35
+ repo_id (`str`, *optional*, defaults to `"trl-internal-testing/zen-image"`):
36
+ Hugging Face repository ID to push the dataset to.
37
+ """
38
+
39
+ test_size: float = field(
40
+ default=0.1,
41
+ metadata={"help": "Fraction of the dataset to include in the test split."},
42
+ )
43
+ push_to_hub: bool = field(
44
+ default=False,
45
+ metadata={"help": "Whether to push the dataset to the Hugging Face Hub."},
46
+ )
47
+ repo_id: str = field(
48
+ default="trl-internal-testing/zen-image",
49
+ metadata={"help": "Hugging Face repository ID to push the dataset to."},
50
+ )
51
+
52
+
53
+ def main(test_size, push_to_hub, repo_id):
54
+ # fmt: off
55
+ sizes = np.random.randint(32, 64, size=(19, 2))
56
+ data = {
57
+ "messages": [
58
+ [{"role": "user", "content": "What is better than ugly?"}, {"role": "assistant", "content": "Beautiful."},],
59
+ [{"role": "user", "content": "What is better than implicit?"}, {"role": "assistant", "content": "Explicit."}],
60
+ [{"role": "user", "content": "What is better than complex?"}, {"role": "assistant", "content": "Simple."}],
61
+ [{"role": "user", "content": "What is better than complicated?"}, {"role": "assistant", "content": "Complex."}],
62
+ [{"role": "user", "content": "What is better than nested?"}, {"role": "assistant", "content": "Flat."}],
63
+ [{"role": "user", "content": "What is better than dense?"}, {"role": "assistant", "content": "Sparse."}],
64
+ [{"role": "user", "content": "What counts?"}, {"role": "assistant", "content": "Readability."}],
65
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}, {"role": "assistant", "content": "No, special cases aren't special enough to break the rules."}],
66
+ [{"role": "user", "content": "What beats purity?"}, {"role": "assistant", "content": "Practicality."}],
67
+ [{"role": "user", "content": "What should never pass silently?"}, {"role": "assistant", "content": "Errors."}],
68
+ [{"role": "user", "content": "When can errors pass silently?"}, {"role": "assistant", "content": "When explicitly silenced."}],
69
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}, {"role": "assistant", "content": "Refuse the temptation to guess."}],
70
+ [{"role": "user", "content": "How many ways should there be to do it?"}, {"role": "assistant", "content": "One, and preferably only one."}],
71
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}, {"role": "assistant", "content": "Dutch."}],
72
+ [{"role": "user", "content": "What is better than never?"}, {"role": "assistant", "content": "Now is better than never."}],
73
+ [{"role": "user", "content": "Is never better than *right* now?"}, {"role": "assistant", "content": "Yes, often."}],
74
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}, {"role": "assistant", "content": "It means it's a bad idea."}],
75
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}, {"role": "assistant", "content": "It means it may be a good idea."}],
76
+ [{"role": "user", "content": "Any great ideas?"}, {"role": "assistant", "content": "Namespaces are one honking great idea."}],
77
+ ],
78
+ "image": [np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in sizes],
79
+ }
80
+ conversational_language_modeling_dataset = Dataset.from_dict(data, features=Features(messages=Message, image=Image()))
81
+ conversational_language_modeling_dataset = conversational_language_modeling_dataset.train_test_split(test_size=test_size, shuffle=False)
82
+ if push_to_hub:
83
+ conversational_language_modeling_dataset.push_to_hub(repo_id, config_name="conversational_language_modeling")
84
+
85
+ sizes = np.random.randint(32, 64, size=(19, 2))
86
+ data = {
87
+ "prompt": [
88
+ [{"role": "user", "content": "What is better than ugly?"}],
89
+ [{"role": "user", "content": "What is better than implicit?"}],
90
+ [{"role": "user", "content": "What is better than complex?"}],
91
+ [{"role": "user", "content": "What is better than complicated?"}],
92
+ [{"role": "user", "content": "What is better than nested?"}],
93
+ [{"role": "user", "content": "What is better than dense?"}],
94
+ [{"role": "user", "content": "What counts?"}],
95
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}],
96
+ [{"role": "user", "content": "What beats purity?"}],
97
+ [{"role": "user", "content": "What should never pass silently?"}],
98
+ [{"role": "user", "content": "When can errors pass silently?"}],
99
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}],
100
+ [{"role": "user", "content": "How many ways should there be to do it?"}],
101
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}],
102
+ [{"role": "user", "content": "What is better than never?"}],
103
+ [{"role": "user", "content": "Is never better than *right* now?"}],
104
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}],
105
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}],
106
+ [{"role": "user", "content": "Any great ideas?"}],
107
+ ],
108
+ "image": [np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in sizes],
109
+ }
110
+ conversational_prompt_only_dataset = Dataset.from_dict(data, features=Features(prompt=Message, image=Image()))
111
+ conversational_prompt_only_dataset = conversational_prompt_only_dataset.train_test_split(test_size=test_size, shuffle=False)
112
+ if push_to_hub:
113
+ conversational_prompt_only_dataset.push_to_hub(repo_id, config_name="conversational_prompt_only")
114
+
115
+ sizes = np.random.randint(32, 64, size=(19, 2))
116
+ data = {
117
+ "prompt": [
118
+ [{"role": "user", "content": "What is better than ugly?"}],
119
+ [{"role": "user", "content": "What is better than implicit?"}],
120
+ [{"role": "user", "content": "What is better than complex?"}],
121
+ [{"role": "user", "content": "What is better than complicated?"}],
122
+ [{"role": "user", "content": "What is better than nested?"}],
123
+ [{"role": "user", "content": "What is better than dense?"}],
124
+ [{"role": "user", "content": "What counts?"}],
125
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}],
126
+ [{"role": "user", "content": "What beats purity?"}],
127
+ [{"role": "user", "content": "What should never pass silently?"}],
128
+ [{"role": "user", "content": "When can errors pass silently?"}],
129
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}],
130
+ [{"role": "user", "content": "How many ways should there be to do it?"}],
131
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}],
132
+ [{"role": "user", "content": "What is better than never?"}],
133
+ [{"role": "user", "content": "Is never better than *right* now?"}],
134
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}],
135
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}],
136
+ [{"role": "user", "content": "Any great ideas?"}],
137
+ ],
138
+ "completion": [
139
+ [{"role": "assistant", "content": "Beautiful."}],
140
+ [{"role": "assistant", "content": "Explicit."}],
141
+ [{"role": "assistant", "content": "Simple."}],
142
+ [{"role": "assistant", "content": "Complex."}],
143
+ [{"role": "assistant", "content": "Flat."}],
144
+ [{"role": "assistant", "content": "Sparse."}],
145
+ [{"role": "assistant", "content": "Readability."}],
146
+ [{"role": "assistant", "content": "No, special cases aren't special enough to break the rules."}],
147
+ [{"role": "assistant", "content": "Practicality."}],
148
+ [{"role": "assistant", "content": "Errors."}],
149
+ [{"role": "assistant", "content": "When explicitly silenced."}],
150
+ [{"role": "assistant", "content": "Refuse the temptation to guess."}],
151
+ [{"role": "assistant", "content": "One, and preferably only one."}],
152
+ [{"role": "assistant", "content": "Dutch."}],
153
+ [{"role": "assistant", "content": "Now is better than never."}],
154
+ [{"role": "assistant", "content": "Yes, often."}],
155
+ [{"role": "assistant", "content": "It means it's a bad idea."}],
156
+ [{"role": "assistant", "content": "It means it may be a good idea."}],
157
+ [{"role": "assistant", "content": "Namespaces are one honking great idea."}],
158
+ ],
159
+ "image": [np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in sizes],
160
+ }
161
+ conversational_prompt_completion_dataset = Dataset.from_dict(data, features=Features(prompt=Message, completion=Message, image=Image()))
162
+ conversational_prompt_completion_dataset = conversational_prompt_completion_dataset.train_test_split(test_size=test_size, shuffle=False)
163
+ if push_to_hub:
164
+ conversational_prompt_completion_dataset.push_to_hub(repo_id, config_name="conversational_prompt_completion")
165
+
166
+ sizes = np.random.randint(32, 64, size=(19, 2))
167
+ data = {
168
+ "prompt": [
169
+ [{"role": "user", "content": "What is better than ugly?"}],
170
+ [{"role": "user", "content": "What is better than implicit?"}],
171
+ [{"role": "user", "content": "What is better than complex?"}],
172
+ [{"role": "user", "content": "What is better than complicated?"}],
173
+ [{"role": "user", "content": "What is better than nested?"}],
174
+ [{"role": "user", "content": "What is better than dense?"}],
175
+ [{"role": "user", "content": "What counts?"}],
176
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}],
177
+ [{"role": "user", "content": "What beats purity?"}],
178
+ [{"role": "user", "content": "What should never pass silently?"}],
179
+ [{"role": "user", "content": "When can errors pass silently?"}],
180
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}],
181
+ [{"role": "user", "content": "How many ways should there be to do it?"}],
182
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}],
183
+ [{"role": "user", "content": "What is better than never?"}],
184
+ [{"role": "user", "content": "Is never better than *right* now?"}],
185
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}],
186
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}],
187
+ [{"role": "user", "content": "Any great ideas?"}],
188
+ ],
189
+ "chosen": [
190
+ [{"role": "assistant", "content": "Beautiful."}],
191
+ [{"role": "assistant", "content": "Explicit."}],
192
+ [{"role": "assistant", "content": "Simple."}],
193
+ [{"role": "assistant", "content": "Complex."}],
194
+ [{"role": "assistant", "content": "Flat."}],
195
+ [{"role": "assistant", "content": "Sparse."}],
196
+ [{"role": "assistant", "content": "Readability."}],
197
+ [{"role": "assistant", "content": "No, special cases aren't special enough to break the rules."}],
198
+ [{"role": "assistant", "content": "Practicality."}],
199
+ [{"role": "assistant", "content": "Errors."}],
200
+ [{"role": "assistant", "content": "When explicitly silenced."}],
201
+ [{"role": "assistant", "content": "Refuse the temptation to guess."}],
202
+ [{"role": "assistant", "content": "One, and preferably only one."}],
203
+ [{"role": "assistant", "content": "Dutch."}],
204
+ [{"role": "assistant", "content": "Now is better than never."}],
205
+ [{"role": "assistant", "content": "Yes, often."}],
206
+ [{"role": "assistant", "content": "It means it's a bad idea."}],
207
+ [{"role": "assistant", "content": "It means it may be a good idea."}],
208
+ [{"role": "assistant", "content": "Namespaces are one honking great idea."}],
209
+ ],
210
+ "rejected": [
211
+ [{"role": "assistant", "content": "Acceptable."}],
212
+ [{"role": "assistant", "content": "Explained."}],
213
+ [{"role": "assistant", "content": "Very complex."}],
214
+ [{"role": "assistant", "content": "Very complicated."}],
215
+ [{"role": "assistant", "content": "Circular."}],
216
+ [{"role": "assistant", "content": "Heavy."}],
217
+ [{"role": "assistant", "content": "Looking complicated."}],
218
+ [{"role": "assistant", "content": "Yes, special cases are special enough to break the rules."}],
219
+ [{"role": "assistant", "content": "Nothing."}],
220
+ [{"role": "assistant", "content": "Warnings."}],
221
+ [{"role": "assistant", "content": "Never."}],
222
+ [{"role": "assistant", "content": "Give up."}],
223
+ [{"role": "assistant", "content": "As many as possible."}],
224
+ [{"role": "assistant", "content": "French."}],
225
+ [{"role": "assistant", "content": "Some day."}],
226
+ [{"role": "assistant", "content": "No, never."}],
227
+ [{"role": "assistant", "content": "It means it's a good idea."}],
228
+ [{"role": "assistant", "content": "It means it's a bad idea."}],
229
+ [{"role": "assistant", "content": "Recursion."}],
230
+ ],
231
+ "image": [np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in sizes],
232
+ }
233
+ conversational_preference_dataset = Dataset.from_dict(data, features=Features(prompt=Message, chosen=Message, rejected=Message, image=Image()))
234
+ conversational_preference_dataset = conversational_preference_dataset.train_test_split(test_size=test_size, shuffle=False)
235
+ if push_to_hub:
236
+ conversational_preference_dataset.push_to_hub(repo_id, config_name="conversational_preference")
237
+
238
+ sizes = np.random.randint(32, 64, size=(19, 2))
239
+ data = {
240
+ "chosen": [
241
+ [{"role": "user", "content": "What is better than ugly?"}, {"role": "assistant", "content": "Beautiful."}],
242
+ [{"role": "user", "content": "What is better than implicit?"}, {"role": "assistant", "content": "Explicit."}],
243
+ [{"role": "user", "content": "What is better than complex?"}, {"role": "assistant", "content": "Simple."}],
244
+ [{"role": "user", "content": "What is better than complicated?"}, {"role": "assistant", "content": "Complex."}],
245
+ [{"role": "user", "content": "What is better than nested?"}, {"role": "assistant", "content": "Flat."}],
246
+ [{"role": "user", "content": "What is better than dense?"}, {"role": "assistant", "content": "Sparse."}],
247
+ [{"role": "user", "content": "What counts?"}, {"role": "assistant", "content": "Readability."}],
248
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}, {"role": "assistant", "content": "No, special cases aren't special enough to break the rules."}],
249
+ [{"role": "user", "content": "What beats purity?"}, {"role": "assistant", "content": "Practicality."}],
250
+ [{"role": "user", "content": "What should never pass silently?"}, {"role": "assistant", "content": "Errors."}],
251
+ [{"role": "user", "content": "When can errors pass silently?"}, {"role": "assistant", "content": "When explicitly silenced."}],
252
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}, {"role": "assistant", "content": "Refuse the temptation to guess."}],
253
+ [{"role": "user", "content": "How many ways should there be to do it?"}, {"role": "assistant", "content": "One, and preferably only one."}],
254
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}, {"role": "assistant", "content": "Dutch."}],
255
+ [{"role": "user", "content": "What is better than never?"}, {"role": "assistant", "content": "Now is better than never."}],
256
+ [{"role": "user", "content": "Is never better than *right* now?"}, {"role": "assistant", "content": "Yes, often."}],
257
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}, {"role": "assistant", "content": "It means it's a bad idea."}],
258
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}, {"role": "assistant", "content": "It means it may be a good idea."}],
259
+ [{"role": "user", "content": "Any great ideas?"}, {"role": "assistant", "content": "Namespaces are one honking great idea."}],
260
+ ],
261
+ "rejected": [
262
+ [{"role": "user", "content": "What is better than ugly?"}, {"role": "assistant", "content": "Acceptable."}],
263
+ [{"role": "user", "content": "What is better than implicit?"}, {"role": "assistant", "content": "Explained."}],
264
+ [{"role": "user", "content": "What is better than complex?"}, {"role": "assistant", "content": "Very complex."}],
265
+ [{"role": "user", "content": "What is better than complicated?"}, {"role": "assistant", "content": "Very complicated."}],
266
+ [{"role": "user", "content": "What is better than nested?"}, {"role": "assistant", "content": "Circular."}],
267
+ [{"role": "user", "content": "What is better than dense?"}, {"role": "assistant", "content": "Heavy."}],
268
+ [{"role": "user", "content": "What counts?"}, {"role": "assistant", "content": "Looking complicated."}],
269
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}, {"role": "assistant", "content": "Yes, special cases are special enough to break the rules."}],
270
+ [{"role": "user", "content": "What beats purity?"}, {"role": "assistant", "content": "Nothing."}],
271
+ [{"role": "user", "content": "What should never pass silently?"}, {"role": "assistant", "content": "Warnings."}],
272
+ [{"role": "user", "content": "When can errors pass silently?"}, {"role": "assistant", "content": "Never."}],
273
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}, {"role": "assistant", "content": "Give up."}],
274
+ [{"role": "user", "content": "How many ways should there be to do it?"}, {"role": "assistant", "content": "As many as possible."}],
275
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}, {"role": "assistant", "content": "French."}],
276
+ [{"role": "user", "content": "What is better than never?"}, {"role": "assistant", "content": "Some day."}],
277
+ [{"role": "user", "content": "Is never better than *right* now?"}, {"role": "assistant", "content": "No, never."}],
278
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}, {"role": "assistant", "content": "It means it's a good idea."}],
279
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}, {"role": "assistant", "content": "It means it's a bad idea."}],
280
+ [{"role": "user", "content": "Any great ideas?"}, {"role": "assistant", "content": "Recursion."}],
281
+ ],
282
+ "image": [np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in sizes],
283
+ }
284
+ conversational_implicit_prompt_preference_dataset = Dataset.from_dict(data, features=Features(chosen=Message, rejected=Message, image=Image()))
285
+ conversational_implicit_prompt_preference_dataset = conversational_implicit_prompt_preference_dataset.train_test_split(test_size=test_size, shuffle=False)
286
+ if push_to_hub:
287
+ conversational_implicit_prompt_preference_dataset.push_to_hub(repo_id, config_name="conversational_implicit_prompt_preference")
288
+
289
+ sizes = np.random.randint(32, 64, size=(19, 2))
290
+ data = {
291
+ "prompt": [
292
+ [{"role": "user", "content": "What is better than ugly?"}],
293
+ [{"role": "user", "content": "What is better than implicit?"}],
294
+ [{"role": "user", "content": "What is better than complex?"}],
295
+ [{"role": "user", "content": "What is better than complicated?"}],
296
+ [{"role": "user", "content": "What is better than nested?"}],
297
+ [{"role": "user", "content": "What is better than dense?"}],
298
+ [{"role": "user", "content": "What counts?"}],
299
+ [{"role": "user", "content": "Are special cases enough to break the rules?"}],
300
+ [{"role": "user", "content": "What beats purity?"}],
301
+ [{"role": "user", "content": "What should never pass silently?"}],
302
+ [{"role": "user", "content": "When can errors pass silently?"}],
303
+ [{"role": "user", "content": "What should you do in the face of ambiguity?"}],
304
+ [{"role": "user", "content": "How many ways should there be to do it?"}],
305
+ [{"role": "user", "content": "For whom may the way not be obvious at first?"}],
306
+ [{"role": "user", "content": "What is better than never?"}],
307
+ [{"role": "user", "content": "Is never better than *right* now?"}],
308
+ [{"role": "user", "content": "What does it mean if the implementation is hard to explain?"}],
309
+ [{"role": "user", "content": "What does it mean if the implementation is easy to explain?"}],
310
+ [{"role": "user", "content": "Any great ideas?"}],
311
+ ],
312
+ "completion": [
313
+ [{'role': 'assistant', 'content': 'Beautiful.'}],
314
+ [{'role': 'assistant', 'content': 'Explicit.'}],
315
+ [{'role': 'assistant', 'content': 'Simple.'}],
316
+ [{'role': 'assistant', 'content': 'Very complicated.'}],
317
+ [{'role': 'assistant', 'content': 'Flat.'}],
318
+ [{'role': 'assistant', 'content': 'Sparse.'}],
319
+ [{'role': 'assistant', 'content': 'Readability.'}],
320
+ [{'role': 'assistant', 'content': 'Yes, special cases are special enough to break the rules.'}],
321
+ [{'role': 'assistant', 'content': 'Practicality.'}],
322
+ [{'role': 'assistant', 'content': 'Warnings.'}],
323
+ [{'role': 'assistant', 'content': 'When explicitly silenced.'}],
324
+ [{'role': 'assistant', 'content': 'Give up.'}],
325
+ [{'role': 'assistant', 'content': 'One, and preferably only one.'}],
326
+ [{'role': 'assistant', 'content': 'French.'}],
327
+ [{'role': 'assistant', 'content': 'Some day.'}],
328
+ [{'role': 'assistant', 'content': 'Yes, often.'}],
329
+ [{'role': 'assistant', 'content': "It means it's a bad idea."}],
330
+ [{'role': 'assistant', 'content': 'It means it may be a good idea.'}],
331
+ [{'role': 'assistant', 'content': 'Namespaces are one honking great idea.'}],
332
+ ],
333
+ "label": [True, True, True, False, True, True, True, False, True, False, True, False, True, False, False, True, True, True, True],
334
+ "image": [np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in sizes],
335
+ }
336
+ conversational_unpaired_preference_dataset = Dataset.from_dict(data, features=Features(prompt=Message, completion=Message, label=Value("bool"), image=Image()))
337
+ conversational_unpaired_preference_dataset = conversational_unpaired_preference_dataset.train_test_split(test_size=test_size, shuffle=False)
338
+ if push_to_hub:
339
+ conversational_unpaired_preference_dataset.push_to_hub(repo_id, config_name="conversational_unpaired_preference")
340
+ # fmt: on
341
+
342
+
343
+ if __name__ == "__main__":
344
+ parser = HfArgumentParser(ScriptArguments)
345
+ script_args = parser.parse_args_into_dataclasses()[0]
346
+ main(script_args.test_size, script_args.push_to_hub, script_args.repo_id)
tasks/tasksmith-0ea2241cceeb/environment/source/scripts/generate_zen_multi_image_dataset.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+
17
+ import numpy as np
18
+ from datasets import Dataset, Features, Image, List, Value
19
+ from transformers import HfArgumentParser
20
+
21
+
22
+ Message = List({"content": List({"text": Value("string"), "type": Value("string")}), "role": Value("string")})
23
+
24
+
25
+ @dataclass
26
+ class ScriptArguments:
27
+ r"""
28
+ Arguments for the script.
29
+
30
+ Args:
31
+ test_size (`float`, *optional*, defaults to `0.1`):
32
+ Fraction of the dataset to include in the test split.
33
+ push_to_hub (`bool`, *optional*, defaults to `False`):
34
+ Whether to push the dataset to the Hugging Face Hub.
35
+ repo_id (`str`, *optional*, defaults to `"trl-internal-testing/zen-multi-image"`):
36
+ Hugging Face repository ID to push the dataset to.
37
+ """
38
+
39
+ test_size: float = field(
40
+ default=0.1,
41
+ metadata={"help": "Fraction of the dataset to include in the test split."},
42
+ )
43
+ push_to_hub: bool = field(
44
+ default=False,
45
+ metadata={"help": "Whether to push the dataset to the Hugging Face Hub."},
46
+ )
47
+ repo_id: str = field(
48
+ default="trl-internal-testing/zen-multi-image",
49
+ metadata={"help": "Hugging Face repository ID to push the dataset to."},
50
+ )
51
+
52
+
53
+ def main(test_size, push_to_hub, repo_id):
54
+ # fmt: off
55
+ messages = [
56
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than ugly?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Beautiful."}]}],
57
+ [{"role": "user", "content": [{"type": "text", "text": "What is better than implicit?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Explicit."}]}],
58
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than complex?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Simple."}]}],
59
+ [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What is better than complicated?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Complex."}]}],
60
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than nested?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Flat."}]}],
61
+ [{"role": "user", "content": [{"type": "text", "text": "What is better than dense?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Sparse."}]}],
62
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What counts?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Readability."}]}],
63
+ [{"role": "user", "content": [{"type": "text", "text": "Are special cases enough to break the rules?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "No, special cases aren't special enough to break the rules."}]}],
64
+ [{"role": "user", "content": [{"type": "text", "text": "What beats purity?"}, {"type": "image"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Practicality."}]}],
65
+ [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What should never pass silently?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Errors."}]}],
66
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "When can errors pass silently?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "When explicitly silenced."}]}],
67
+ [{"role": "user", "content": [{"type": "text", "text": "What should you do in the face of ambiguity?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Refuse the temptation to guess."}]}],
68
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "How many ways should there be to do it?"}, {"type": "image"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "One, and preferably only one."}]}],
69
+ [{"role": "user", "content": [{"type": "text", "text": "For whom may the way not be obvious at first?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Dutch."}]}],
70
+ [{"role": "user", "content": [{"type": "text", "text": "What is better than never?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Now is better than never."}]}],
71
+ [{"role": "user", "content": [{"type": "text", "text": "Is"}, {"type": "image"}, {"type": "text", "text": " never better than *right* now?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Yes, often."}]}],
72
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What does it mean if the implementation is hard to explain?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "It means it's a bad idea."}]}],
73
+ [{"role": "user", "content": [{"type": "text", "text": "What does it mean if the implementation is easy to explain?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "It means it may be a good idea."}]}],
74
+ [{"role": "user", "content": [{"type": "text", "text": "Any great ideas?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Namespaces are one honking great idea."}]}],
75
+ ]
76
+ # Create the images
77
+ number_of_images = [sum(1 for part in row[0]["content"] if part.get("type") == "image") for row in messages]
78
+ sizes = [np.random.randint(32, 64, size=(num_images, 2)) for num_images in number_of_images]
79
+ images = [[np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in s] for s in sizes]
80
+ conversational_language_modeling_dataset = Dataset.from_dict({"messages": messages, "images": images}, features=Features(messages=Message, images=List(Image())))
81
+ conversational_language_modeling_dataset = conversational_language_modeling_dataset.train_test_split(test_size=test_size, shuffle=False)
82
+ if push_to_hub:
83
+ conversational_language_modeling_dataset.push_to_hub(repo_id, config_name="conversational_language_modeling")
84
+
85
+ prompt = [
86
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than ugly?"}]}],
87
+ [{"role": "user", "content": [{"type": "text", "text": "What is better than implicit?"}, {"type": "image"}]}],
88
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than complex?"}, {"type": "image"}]}],
89
+ [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What is better than complicated?"}]}],
90
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than nested?"}]}],
91
+ [{"role": "user", "content": [{"type": "text", "text": "What is better than dense?"}, {"type": "image"}]}],
92
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What counts?"}, {"type": "image"}]}],
93
+ [{"role": "user", "content": [{"type": "text", "text": "Are special cases enough to break the rules?"}]}],
94
+ [{"role": "user", "content": [{"type": "text", "text": "What beats purity?"}, {"type": "image"}, {"type": "image"}]}],
95
+ [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What should never pass silently?"}, {"type": "image"}]}],
96
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "When can errors pass silently?"}]}],
97
+ [{"role": "user", "content": [{"type": "text", "text": "What should you do in the face of ambiguity?"}, {"type": "image"}]}],
98
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "How many ways should there be to do it?"}, {"type": "image"}, {"type": "image"}]}],
99
+ [{"role": "user", "content": [{"type": "text", "text": "For whom may the way not be obvious at first?"}]}],
100
+ [{"role": "user", "content": [{"type": "text", "text": "What is better than never?"}, {"type": "image"}]}],
101
+ [{"role": "user", "content": [{"type": "text", "text": "Is"}, {"type": "image"}, {"type": "text", "text": " never better than *right* now?"}]}],
102
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What does it mean if the implementation is hard to explain?"}]}],
103
+ [{"role": "user", "content": [{"type": "text", "text": "What does it mean if the implementation is easy to explain?"}, {"type": "image"}]}],
104
+ [{"role": "user", "content": [{"type": "text", "text": "Any great ideas?"}]}],
105
+ ]
106
+ # Create the images
107
+ number_of_images = [sum(1 for part in row[0]["content"] if part.get("type") == "image") for row in prompt]
108
+ sizes = [np.random.randint(32, 64, size=(num_images, 2)) for num_images in number_of_images]
109
+ images = [[np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in s] for s in sizes]
110
+ conversational_prompt_only_dataset = Dataset.from_dict({"prompt": prompt, "images": images}, features=Features(prompt=Message, images=List(Image())))
111
+ conversational_prompt_only_dataset = conversational_prompt_only_dataset.train_test_split(test_size=test_size, shuffle=False)
112
+ if push_to_hub:
113
+ conversational_prompt_only_dataset.push_to_hub(repo_id, config_name="conversational_prompt_only")
114
+
115
+ prompt = [
116
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than ugly?"}]}],
117
+ [{"role": "user", "content": [{"type": "text", "text": "What is better than implicit?"}, {"type": "image"}]}],
118
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than complex?"}, {"type": "image"}]}],
119
+ [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What is better than complicated?"}]}],
120
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than nested?"}]}],
121
+ [{"role": "user", "content": [{"type": "text", "text": "What is better than dense?"}, {"type": "image"}]}],
122
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What counts?"}, {"type": "image"}]}],
123
+ [{"role": "user", "content": [{"type": "text", "text": "Are special cases enough to break the rules?"}]}],
124
+ [{"role": "user", "content": [{"type": "text", "text": "What beats purity?"}, {"type": "image"}, {"type": "image"}]}],
125
+ [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What should never pass silently?"}, {"type": "image"}]}],
126
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "When can errors pass silently?"}]}],
127
+ [{"role": "user", "content": [{"type": "text", "text": "What should you do in the face of ambiguity?"}, {"type": "image"}]}],
128
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "How many ways should there be to do it?"}, {"type": "image"}, {"type": "image"}]}],
129
+ [{"role": "user", "content": [{"type": "text", "text": "For whom may the way not be obvious at first?"}]}],
130
+ [{"role": "user", "content": [{"type": "text", "text": "What is better than never?"}, {"type": "image"}]}],
131
+ [{"role": "user", "content": [{"type": "text", "text": "Is"}, {"type": "image"}, {"type": "text", "text": " never better than *right* now?"}]}],
132
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What does it mean if the implementation is hard to explain?"}]}],
133
+ [{"role": "user", "content": [{"type": "text", "text": "What does it mean if the implementation is easy to explain?"}, {"type": "image"}]}],
134
+ [{"role": "user", "content": [{"type": "text", "text": "Any great ideas?"}]}],
135
+ ]
136
+ completion = [
137
+ [{"role": "assistant", "content": [{"type": "text", "text": "Beautiful."}]}],
138
+ [{"role": "assistant", "content": [{"type": "text", "text": "Explicit."}]}],
139
+ [{"role": "assistant", "content": [{"type": "text", "text": "Simple."}]}],
140
+ [{"role": "assistant", "content": [{"type": "text", "text": "Complex."}]}],
141
+ [{"role": "assistant", "content": [{"type": "text", "text": "Flat."}]}],
142
+ [{"role": "assistant", "content": [{"type": "text", "text": "Sparse."}]}],
143
+ [{"role": "assistant", "content": [{"type": "text", "text": "Readability."}]}],
144
+ [{"role": "assistant", "content": [{"type": "text", "text": "No, special cases aren't special enough to break the rules."}]}],
145
+ [{"role": "assistant", "content": [{"type": "text", "text": "Practicality."}]}],
146
+ [{"role": "assistant", "content": [{"type": "text", "text": "Errors."}]}],
147
+ [{"role": "assistant", "content": [{"type": "text", "text": "When explicitly silenced."}]}],
148
+ [{"role": "assistant", "content": [{"type": "text", "text": "Refuse the temptation to guess."}]}],
149
+ [{"role": "assistant", "content": [{"type": "text", "text": "One, and preferably only one."}]}],
150
+ [{"role": "assistant", "content": [{"type": "text", "text": "Dutch."}]}],
151
+ [{"role": "assistant", "content": [{"type": "text", "text": "Now is better than never."}]}],
152
+ [{"role": "assistant", "content": [{"type": "text", "text": "Yes, often."}]}],
153
+ [{"role": "assistant", "content": [{"type": "text", "text": "It means it's a bad idea."}]}],
154
+ [{"role": "assistant", "content": [{"type": "text", "text": "It means it may be a good idea."}]}],
155
+ [{"role": "assistant", "content": [{"type": "text", "text": "Namespaces are one honking great idea."}]}],
156
+ ]
157
+ # Create the images
158
+ number_of_images = [sum(1 for part in row[0]["content"] if part.get("type") == "image") for row in prompt]
159
+ sizes = [np.random.randint(32, 64, size=(num_images, 2)) for num_images in number_of_images]
160
+ images = [[np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in s] for s in sizes]
161
+ conversational_prompt_completion_dataset = Dataset.from_dict({"prompt": prompt, "completion": completion, "images": images}, features=Features(prompt=Message, completion=Message, images=List(Image())))
162
+ conversational_prompt_completion_dataset = conversational_prompt_completion_dataset.train_test_split(test_size=test_size, shuffle=False)
163
+ if push_to_hub:
164
+ conversational_prompt_completion_dataset.push_to_hub(repo_id, config_name="conversational_prompt_completion")
165
+
166
+ prompt = [
167
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than ugly?"}]}],
168
+ [{"role": "user", "content": [{"type": "text", "text": "What is better than implicit?"}, {"type": "image"}]}],
169
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than complex?"}, {"type": "image"}]}],
170
+ [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What is better than complicated?"}]}],
171
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than nested?"}]}],
172
+ [{"role": "user", "content": [{"type": "text", "text": "What is better than dense?"}, {"type": "image"}]}],
173
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What counts?"}, {"type": "image"}]}],
174
+ [{"role": "user", "content": [{"type": "text", "text": "Are special cases enough to break the rules?"}]}],
175
+ [{"role": "user", "content": [{"type": "text", "text": "What beats purity?"}, {"type": "image"}, {"type": "image"}]}],
176
+ [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What should never pass silently?"}, {"type": "image"}]}],
177
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "When can errors pass silently?"}]}],
178
+ [{"role": "user", "content": [{"type": "text", "text": "What should you do in the face of ambiguity?"}, {"type": "image"}]}],
179
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "How many ways should there be to do it?"}, {"type": "image"}, {"type": "image"}]}],
180
+ [{"role": "user", "content": [{"type": "text", "text": "For whom may the way not be obvious at first?"}]}],
181
+ [{"role": "user", "content": [{"type": "text", "text": "What is better than never?"}, {"type": "image"}]}],
182
+ [{"role": "user", "content": [{"type": "text", "text": "Is"}, {"type": "image"}, {"type": "text", "text": " never better than *right* now?"}]}],
183
+ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What does it mean if the implementation is hard to explain?"}]}],
184
+ [{"role": "user", "content": [{"type": "text", "text": "What does it mean if the implementation is easy to explain?"}, {"type": "image"}]}],
185
+ [{"role": "user", "content": [{"type": "text", "text": "Any great ideas?"}]}],
186
+ ]
187
+ chosen = [
188
+ [{"role": "assistant", "content": [{"type": "text", "text": "Beautiful."}]}],
189
+ [{"role": "assistant", "content": [{"type": "text", "text": "Explicit."}]}],
190
+ [{"role": "assistant", "content": [{"type": "text", "text": "Simple."}]}],
191
+ [{"role": "assistant", "content": [{"type": "text", "text": "Complex."}]}],
192
+ [{"role": "assistant", "content": [{"type": "text", "text": "Flat."}]}],
193
+ [{"role": "assistant", "content": [{"type": "text", "text": "Sparse."}]}],
194
+ [{"role": "assistant", "content": [{"type": "text", "text": "Readability."}]}],
195
+ [{"role": "assistant", "content": [{"type": "text", "text": "No, special cases aren't special enough to break the rules."}]}],
196
+ [{"role": "assistant", "content": [{"type": "text", "text": "Practicality."}]}],
197
+ [{"role": "assistant", "content": [{"type": "text", "text": "Errors."}]}],
198
+ [{"role": "assistant", "content": [{"type": "text", "text": "When explicitly silenced."}]}],
199
+ [{"role": "assistant", "content": [{"type": "text", "text": "Refuse the temptation to guess."}]}],
200
+ [{"role": "assistant", "content": [{"type": "text", "text": "One, and preferably only one."}]}],
201
+ [{"role": "assistant", "content": [{"type": "text", "text": "Dutch."}]}],
202
+ [{"role": "assistant", "content": [{"type": "text", "text": "Now is better than never."}]}],
203
+ [{"role": "assistant", "content": [{"type": "text", "text": "Yes, often."}]}],
204
+ [{"role": "assistant", "content": [{"type": "text", "text": "It means it's a bad idea."}]}],
205
+ [{"role": "assistant", "content": [{"type": "text", "text": "It means it may be a good idea."}]}],
206
+ [{"role": "assistant", "content": [{"type": "text", "text": "Namespaces are one honking great idea."}]}],
207
+ ]
208
+ rejected = [
209
+ [{"role": "assistant", "content": [{"type": "text", "text": "Acceptable."}]}],
210
+ [{"role": "assistant", "content": [{"type": "text", "text": "Explained."}]}],
211
+ [{"role": "assistant", "content": [{"type": "text", "text": "Very complex."}]}],
212
+ [{"role": "assistant", "content": [{"type": "text", "text": "Very complicated."}]}],
213
+ [{"role": "assistant", "content": [{"type": "text", "text": "Circular."}]}],
214
+ [{"role": "assistant", "content": [{"type": "text", "text": "Heavy."}]}],
215
+ [{"role": "assistant", "content": [{"type": "text", "text": "Looking complicated."}]}],
216
+ [{"role": "assistant", "content": [{"type": "text", "text": "Yes, special cases are special enough to break the rules."}]}],
217
+ [{"role": "assistant", "content": [{"type": "text", "text": "Nothing."}]}],
218
+ [{"role": "assistant", "content": [{"type": "text", "text": "Warnings."}]}],
219
+ [{"role": "assistant", "content": [{"type": "text", "text": "Never."}]}],
220
+ [{"role": "assistant", "content": [{"type": "text", "text": "Give up."}]}],
221
+ [{"role": "assistant", "content": [{"type": "text", "text": "As many as possible."}]}],
222
+ [{"role": "assistant", "content": [{"type": "text", "text": "French."}]}],
223
+ [{"role": "assistant", "content": [{"type": "text", "text": "Some day."}]}],
224
+ [{"role": "assistant", "content": [{"type": "text", "text": "No, never."}]}],
225
+ [{"role": "assistant", "content": [{"type": "text", "text": "It means it's a good idea."}]}],
226
+ [{"role": "assistant", "content": [{"type": "text", "text": "It means it's a bad idea."}]}],
227
+ [{"role": "assistant", "content": [{"type": "text", "text": "Recursion."}]}],
228
+ ]
229
+ # Create the images
230
+ number_of_images = [sum(1 for part in row[0]["content"] if part.get("type") == "image") for row in prompt]
231
+ sizes = [np.random.randint(32, 64, size=(num_images, 2)) for num_images in number_of_images]
232
+ images = [[np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in s] for s in sizes]
233
+ conversational_preference_dataset = Dataset.from_dict({"prompt": prompt, "chosen": chosen, "rejected": rejected, "images": images}, features=Features(prompt=Message, chosen=Message, rejected=Message, images=List(Image())))
234
+ conversational_preference_dataset = conversational_preference_dataset.train_test_split(test_size=test_size, shuffle=False)
235
+ if push_to_hub:
236
+ conversational_preference_dataset.push_to_hub(repo_id, config_name="conversational_preference")
237
+ # fmt: on
238
+
239
+
240
+ if __name__ == "__main__":
241
+ parser = HfArgumentParser(ScriptArguments)
242
+ script_args = parser.parse_args_into_dataclasses()[0]
243
+ main(script_args.test_size, script_args.push_to_hub, script_args.repo_id)
tasks/tasksmith-0ea2241cceeb/environment/source/scripts/log_reports.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import json
17
+ import logging
18
+ import os
19
+ from datetime import date
20
+ from pathlib import Path
21
+
22
+ from tabulate import tabulate
23
+
24
+
25
+ MAX_LEN_MESSAGE = 2900 # Slack endpoint has a limit of 3001 characters
26
+
27
+ parser = argparse.ArgumentParser()
28
+ parser.add_argument("--slack_channel_name", default="trl-push-ci")
29
+
30
+ # Set up logging
31
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
32
+
33
+
34
+ def process_log_file(log):
35
+ failed_tests = []
36
+ passed_tests = []
37
+ section_num_failed = 0
38
+
39
+ try:
40
+ with open(log) as f:
41
+ for line in f:
42
+ try:
43
+ data = json.loads(line)
44
+ test_name = data.get("nodeid", "")
45
+ duration = f"{data['duration']:.4f}" if "duration" in data else "N/A"
46
+ outcome = data.get("outcome", "")
47
+
48
+ if test_name:
49
+ if outcome == "failed":
50
+ section_num_failed += 1
51
+ failed_tests.append([test_name, duration, log.stem.split("_")[0]])
52
+ else:
53
+ passed_tests.append([test_name, duration, log.stem.split("_")[0]])
54
+ except json.JSONDecodeError as e:
55
+ logging.warning(f"Could not decode line in {log}: {e}")
56
+
57
+ except FileNotFoundError as e:
58
+ logging.error(f"Log file {log} not found: {e}")
59
+ except Exception as e:
60
+ logging.error(f"Error processing log file {log}: {e}")
61
+
62
+ return failed_tests, passed_tests, section_num_failed
63
+
64
+
65
+ def main(slack_channel_name):
66
+ group_info = []
67
+ total_num_failed = 0
68
+ total_empty_files = []
69
+
70
+ log_files = list(Path().glob("*.log"))
71
+ if not log_files:
72
+ logging.info("No log files found.")
73
+ return
74
+
75
+ for log in log_files:
76
+ failed, passed, section_num_failed = process_log_file(log)
77
+ empty_file = not failed and not passed
78
+
79
+ total_num_failed += section_num_failed
80
+ total_empty_files.append(empty_file)
81
+ group_info.append([str(log), section_num_failed, failed])
82
+
83
+ # Clean up log file
84
+ try:
85
+ os.remove(log)
86
+ except OSError as e:
87
+ logging.warning(f"Could not remove log file {log}: {e}")
88
+
89
+ # Prepare Slack message payload
90
+ payload = [
91
+ {
92
+ "type": "header",
93
+ "text": {"type": "plain_text", "text": f"🤗 Results of the {os.environ.get('TEST_TYPE', '')} TRL tests."},
94
+ },
95
+ ]
96
+
97
+ if total_num_failed > 0:
98
+ message = ""
99
+ for name, num_failed, failed_tests in group_info:
100
+ if num_failed > 0:
101
+ message += f"*{name}: {num_failed} failed test(s)*\n"
102
+ failed_table = [
103
+ test[0].split("::")[:2] + [test[0].split("::")[-1][:30] + ".."] for test in failed_tests
104
+ ]
105
+ message += (
106
+ "\n```\n"
107
+ + tabulate(failed_table, headers=["Test Location", "Test Name"], tablefmt="grid")
108
+ + "\n```\n"
109
+ )
110
+
111
+ if any(total_empty_files):
112
+ message += f"\n*{name}: Warning! Empty file - check GitHub action job*\n"
113
+
114
+ # Logging
115
+ logging.info(f"Total failed tests: {total_num_failed}")
116
+ print(f"### {message}")
117
+
118
+ if len(message) > MAX_LEN_MESSAGE:
119
+ message = (
120
+ f"❌ There are {total_num_failed} failed tests in total! Please check the action results directly."
121
+ )
122
+
123
+ payload.append({"type": "section", "text": {"type": "mrkdwn", "text": message}})
124
+ payload.append(
125
+ {
126
+ "type": "section",
127
+ "text": {"type": "mrkdwn", "text": "*For more details:*"},
128
+ "accessory": {
129
+ "type": "button",
130
+ "text": {"type": "plain_text", "text": "Check Action results"},
131
+ "url": f"https://github.com/huggingface/trl/actions/runs/{os.environ['GITHUB_RUN_ID']}",
132
+ },
133
+ }
134
+ )
135
+ payload.append(
136
+ {
137
+ "type": "context",
138
+ "elements": [
139
+ {
140
+ "type": "plain_text",
141
+ "text": f"On Push main {os.environ.get('TEST_TYPE')} results for {date.today()}",
142
+ }
143
+ ],
144
+ }
145
+ )
146
+
147
+ # Send to Slack
148
+ from slack_sdk import WebClient
149
+
150
+ slack_client = WebClient(token=os.environ.get("SLACK_API_TOKEN"))
151
+ slack_client.chat_postMessage(channel=f"#{slack_channel_name}", text=message, blocks=payload)
152
+
153
+ else:
154
+ payload.append(
155
+ {
156
+ "type": "section",
157
+ "text": {
158
+ "type": "plain_text",
159
+ "text": "✅ No failures! All tests passed successfully.",
160
+ "emoji": True,
161
+ },
162
+ }
163
+ )
164
+ logging.info("All tests passed. No errors detected.")
165
+
166
+
167
+ if __name__ == "__main__":
168
+ args = parser.parse_args()
169
+ main(args.slack_channel_name)
tasks/tasksmith-0ea2241cceeb/environment/source/trl.egg-info/PKG-INFO ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: trl
3
+ Version: 1.1.0.dev0
4
+ Summary: Train transformer language models with reinforcement learning.
5
+ Author-email: Leandro von Werra <leandro.vonwerra@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/huggingface/trl
8
+ Keywords: transformers,huggingface,language modeling,post-training,rlhf,sft,dpo,grpo
9
+ Classifier: Development Status :: 2 - Pre-Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Natural Language :: English
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: accelerate>=1.4.0
24
+ Requires-Dist: datasets>=4.7.0
25
+ Requires-Dist: jinja2
26
+ Requires-Dist: packaging>20.0
27
+ Requires-Dist: transformers>=4.56.2
28
+ Provides-Extra: bco
29
+ Requires-Dist: scikit-learn; extra == "bco"
30
+ Requires-Dist: joblib; extra == "bco"
31
+ Provides-Extra: deepspeed
32
+ Requires-Dist: deepspeed>=0.14.4; extra == "deepspeed"
33
+ Requires-Dist: transformers!=5.1.0; extra == "deepspeed"
34
+ Provides-Extra: judges
35
+ Requires-Dist: openai>=1.23.2; extra == "judges"
36
+ Requires-Dist: llm-blender>=0.0.2; extra == "judges"
37
+ Requires-Dist: transformers<5.0.0; extra == "judges"
38
+ Provides-Extra: kernels
39
+ Requires-Dist: kernels; extra == "kernels"
40
+ Provides-Extra: liger
41
+ Requires-Dist: liger-kernel>=0.7.0; extra == "liger"
42
+ Provides-Extra: peft
43
+ Requires-Dist: peft>=0.8.0; extra == "peft"
44
+ Provides-Extra: quality
45
+ Requires-Dist: pre-commit; extra == "quality"
46
+ Requires-Dist: hf-doc-builder; extra == "quality"
47
+ Provides-Extra: quantization
48
+ Requires-Dist: bitsandbytes; extra == "quantization"
49
+ Provides-Extra: scikit
50
+ Requires-Dist: scikit-learn; extra == "scikit"
51
+ Provides-Extra: test
52
+ Requires-Dist: pytest-cov; extra == "test"
53
+ Requires-Dist: pytest-datadir>=1.7.0; extra == "test"
54
+ Requires-Dist: pytest-rerunfailures==15.1; extra == "test"
55
+ Requires-Dist: pytest-xdist; extra == "test"
56
+ Requires-Dist: pytest; extra == "test"
57
+ Provides-Extra: vllm
58
+ Requires-Dist: vllm<=0.17.1,>=0.11.0; extra == "vllm"
59
+ Requires-Dist: fastapi; extra == "vllm"
60
+ Requires-Dist: pydantic; extra == "vllm"
61
+ Requires-Dist: aiohttp>=3.13.3; extra == "vllm"
62
+ Requires-Dist: requests; extra == "vllm"
63
+ Requires-Dist: uvicorn; extra == "vllm"
64
+ Provides-Extra: vlm
65
+ Requires-Dist: Pillow; extra == "vlm"
66
+ Requires-Dist: torchvision; extra == "vlm"
67
+ Requires-Dist: num2words==0.5.14; extra == "vlm"
68
+ Provides-Extra: math-verify
69
+ Requires-Dist: math-verify>=0.5.2; extra == "math-verify"
70
+ Provides-Extra: dev
71
+ Requires-Dist: scikit-learn; extra == "dev"
72
+ Requires-Dist: joblib; extra == "dev"
73
+ Requires-Dist: deepspeed>=0.14.4; extra == "dev"
74
+ Requires-Dist: openai>=1.23.2; extra == "dev"
75
+ Requires-Dist: llm-blender>=0.0.2; extra == "dev"
76
+ Requires-Dist: kernels; extra == "dev"
77
+ Requires-Dist: liger-kernel>=0.7.0; extra == "dev"
78
+ Requires-Dist: peft>=0.8.0; extra == "dev"
79
+ Requires-Dist: pre-commit; extra == "dev"
80
+ Requires-Dist: hf-doc-builder; extra == "dev"
81
+ Requires-Dist: bitsandbytes; extra == "dev"
82
+ Requires-Dist: pytest-cov; extra == "dev"
83
+ Requires-Dist: pytest-datadir>=1.7.0; extra == "dev"
84
+ Requires-Dist: pytest-rerunfailures==15.1; extra == "dev"
85
+ Requires-Dist: pytest-xdist; extra == "dev"
86
+ Requires-Dist: pytest; extra == "dev"
87
+ Requires-Dist: Pillow; extra == "dev"
88
+ Requires-Dist: torchvision; extra == "dev"
89
+ Requires-Dist: num2words==0.5.14; extra == "dev"
90
+ Requires-Dist: jmespath; extra == "dev"
91
+ Dynamic: license-file
92
+
93
+ # TRL - Transformers Reinforcement Learning
94
+
95
+ <div style="text-align: center">
96
+ <picture>
97
+ <source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/TRL%20banner%20light.png">
98
+ <img src="https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/trl_banner_dark.png" alt="TRL Banner">
99
+ </picture>
100
+ </div>
101
+
102
+ <hr> <br>
103
+
104
+ <h3 align="center">
105
+ <p>A comprehensive library to post-train foundation models</p>
106
+ </h3>
107
+
108
+ <p align="center">
109
+ <a href="https://github.com/huggingface/trl/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/huggingface/trl.svg?color=blue"></a>
110
+ <a href="https://huggingface.co/docs/trl/index"><img alt="Documentation" src="https://img.shields.io/website?label=documentation&url=https%3A%2F%2Fhuggingface.co%2Fdocs%2Ftrl%2Findex&down_color=red&down_message=offline&up_color=blue&up_message=online"></a>
111
+ <a href="https://github.com/huggingface/trl/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/trl.svg"></a>
112
+ <a href="https://huggingface.co/trl-lib"><img alt="Hugging Face Hub" src="https://img.shields.io/badge/🤗%20Hub-trl--lib-yellow"></a>
113
+ </p>
114
+
115
+ ## 🎉 What's New
116
+
117
+ **TRL v1:** We released TRL v1 — a major milestone that marks a real shift in what TRL is. Read the [blog post](https://huggingface.co/blog/trl-v1) to learn more.
118
+
119
+ ## Overview
120
+
121
+ TRL is a cutting-edge library designed for post-training foundation models using advanced techniques like Supervised Fine-Tuning (SFT), Group Relative Policy Optimization (GRPO), and Direct Preference Optimization (DPO). Built on top of the [🤗 Transformers](https://github.com/huggingface/transformers) ecosystem, TRL supports a variety of model architectures and modalities, and can be scaled-up across various hardware setups.
122
+
123
+ ## Highlights
124
+
125
+ - **Trainers**: Various fine-tuning methods are easily accessible via trainers like [`SFTTrainer`](https://huggingface.co/docs/trl/sft_trainer), [`GRPOTrainer`](https://huggingface.co/docs/trl/grpo_trainer), [`DPOTrainer`](https://huggingface.co/docs/trl/dpo_trainer), [`RewardTrainer`](https://huggingface.co/docs/trl/reward_trainer) and more.
126
+
127
+ - **Efficient and scalable**:
128
+ - Leverages [🤗 Accelerate](https://github.com/huggingface/accelerate) to scale from single GPU to multi-node clusters using methods like [DDP](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html) and [DeepSpeed](https://github.com/deepspeedai/DeepSpeed).
129
+ - Full integration with [🤗 PEFT](https://github.com/huggingface/peft) enables training on large models with modest hardware via quantization and LoRA/QLoRA.
130
+ - Integrates [🦥 Unsloth](https://github.com/unslothai/unsloth) for accelerating training using optimized kernels.
131
+
132
+ - **Command Line Interface (CLI)**: A simple interface lets you fine-tune with models without needing to write code.
133
+
134
+ ## Installation
135
+
136
+ ### Python Package
137
+
138
+ Install the library using `pip`:
139
+
140
+ ```bash
141
+ pip install trl
142
+ ```
143
+
144
+ ### From source
145
+
146
+ If you want to use the latest features before an official release, you can install TRL from source:
147
+
148
+ ```bash
149
+ pip install git+https://github.com/huggingface/trl.git
150
+ ```
151
+
152
+ ### Repository
153
+
154
+ If you want to use the examples you can clone the repository with the following command:
155
+
156
+ ```bash
157
+ git clone https://github.com/huggingface/trl.git
158
+ ```
159
+
160
+ ## Quick Start
161
+
162
+ For more flexibility and control over training, TRL provides dedicated trainer classes to post-train language models or PEFT adapters on a custom dataset. Each trainer in TRL is a light wrapper around the 🤗 Transformers trainer and natively supports distributed training methods like DDP, DeepSpeed ZeRO, and FSDP.
163
+
164
+ ### `SFTTrainer`
165
+
166
+ Here is a basic example of how to use the [`SFTTrainer`](https://huggingface.co/docs/trl/sft_trainer):
167
+
168
+ ```python
169
+ from trl import SFTTrainer
170
+ from datasets import load_dataset
171
+
172
+ dataset = load_dataset("trl-lib/Capybara", split="train")
173
+
174
+ trainer = SFTTrainer(
175
+ model="Qwen/Qwen2.5-0.5B",
176
+ train_dataset=dataset,
177
+ )
178
+ trainer.train()
179
+ ```
180
+
181
+ ### `GRPOTrainer`
182
+
183
+ [`GRPOTrainer`](https://huggingface.co/docs/trl/grpo_trainer) implements the [Group Relative Policy Optimization (GRPO) algorithm](https://huggingface.co/papers/2402.03300) that is more memory-efficient than PPO and was used to train [Deepseek AI's R1](https://huggingface.co/deepseek-ai/DeepSeek-R1).
184
+
185
+ ```python
186
+ from datasets import load_dataset
187
+ from trl import GRPOTrainer
188
+ from trl.rewards import accuracy_reward
189
+
190
+ dataset = load_dataset("trl-lib/DeepMath-103K", split="train")
191
+
192
+ trainer = GRPOTrainer(
193
+ model="Qwen/Qwen2.5-0.5B-Instruct",
194
+ reward_funcs=accuracy_reward,
195
+ train_dataset=dataset,
196
+ )
197
+ trainer.train()
198
+ ```
199
+
200
+ > [!NOTE]
201
+ > For reasoning models, use the `reasoning_accuracy_reward()` function for better results.
202
+
203
+ ### `DPOTrainer`
204
+
205
+ [`DPOTrainer`](https://huggingface.co/docs/trl/dpo_trainer) implements the popular [Direct Preference Optimization (DPO) algorithm](https://huggingface.co/papers/2305.18290) that was used to post-train [Llama 3](https://huggingface.co/papers/2407.21783) and many other models. Here is a basic example of how to use the `DPOTrainer`:
206
+
207
+ ```python
208
+ from datasets import load_dataset
209
+ from trl import DPOTrainer
210
+
211
+ dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
212
+
213
+ trainer = DPOTrainer(
214
+ model="Qwen3/Qwen-0.6B",
215
+ train_dataset=dataset,
216
+ )
217
+ trainer.train()
218
+ ```
219
+
220
+ ### `RewardTrainer`
221
+
222
+ Here is a basic example of how to use the [`RewardTrainer`](https://huggingface.co/docs/trl/reward_trainer):
223
+
224
+ ```python
225
+ from trl import RewardTrainer
226
+ from datasets import load_dataset
227
+
228
+ dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
229
+
230
+ trainer = RewardTrainer(
231
+ model="Qwen/Qwen2.5-0.5B-Instruct",
232
+ train_dataset=dataset,
233
+ )
234
+ trainer.train()
235
+ ```
236
+
237
+ ## Command Line Interface (CLI)
238
+
239
+ You can use the TRL Command Line Interface (CLI) to quickly get started with post-training methods like Supervised Fine-Tuning (SFT) or Direct Preference Optimization (DPO):
240
+
241
+ **SFT:**
242
+
243
+ ```bash
244
+ trl sft --model_name_or_path Qwen/Qwen2.5-0.5B \
245
+ --dataset_name trl-lib/Capybara \
246
+ --output_dir Qwen2.5-0.5B-SFT
247
+ ```
248
+
249
+ **DPO:**
250
+
251
+ ```bash
252
+ trl dpo --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
253
+ --dataset_name argilla/Capybara-Preferences \
254
+ --output_dir Qwen2.5-0.5B-DPO
255
+ ```
256
+
257
+ Read more about CLI in the [relevant documentation section](https://huggingface.co/docs/trl/clis) or use `--help` for more details.
258
+
259
+ ## Development
260
+
261
+ If you want to contribute to `trl` or customize it to your needs make sure to read the [contribution guide](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md) and make sure you make a dev install:
262
+
263
+ ```bash
264
+ git clone https://github.com/huggingface/trl.git
265
+ cd trl/
266
+ pip install -e .[dev]
267
+ ```
268
+
269
+ ## Experimental
270
+
271
+ A minimal incubation area is available under `trl.experimental` for unstable / fast-evolving features. Anything there may change or be removed in any release without notice.
272
+
273
+ Example:
274
+
275
+ ```python
276
+ from trl.experimental.new_trainer import NewTrainer
277
+ ```
278
+
279
+ Read more in the [Experimental docs](https://huggingface.co/docs/trl/experimental_overview).
280
+
281
+ ## Citation
282
+
283
+ ```bibtex
284
+ @software{vonwerra2020trl,
285
+ title = {{TRL: Transformers Reinforcement Learning}},
286
+ author = {von Werra, Leandro and Belkada, Younes and Tunstall, Lewis and Beeching, Edward and Thrush, Tristan and Lambert, Nathan and Huang, Shengyi and Rasul, Kashif and Gallouédec, Quentin},
287
+ license = {Apache-2.0},
288
+ url = {https://github.com/huggingface/trl},
289
+ year = {2020}
290
+ }
291
+ ```
292
+
293
+ ## License
294
+
295
+ This repository's source code is available under the [Apache-2.0 License](LICENSE).
tasks/tasksmith-0ea2241cceeb/environment/source/trl.egg-info/SOURCES.txt ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONTRIBUTING.md
2
+ LICENSE
3
+ MANIFEST.in
4
+ README.md
5
+ VERSION
6
+ pyproject.toml
7
+ trl/__init__.py
8
+ trl/_compat.py
9
+ trl/_lazy_module.py
10
+ trl/chat_template_utils.py
11
+ trl/data_utils.py
12
+ trl/import_utils.py
13
+ trl/py.typed
14
+ trl.egg-info/PKG-INFO
15
+ trl.egg-info/SOURCES.txt
16
+ trl.egg-info/dependency_links.txt
17
+ trl.egg-info/entry_points.txt
18
+ trl.egg-info/requires.txt
19
+ trl.egg-info/top_level.txt
20
+ trl/accelerate_configs/fsdp1.yaml
21
+ trl/accelerate_configs/fsdp2.yaml
22
+ trl/accelerate_configs/multi_gpu.yaml
23
+ trl/accelerate_configs/single_gpu.yaml
24
+ trl/accelerate_configs/zero1.yaml
25
+ trl/accelerate_configs/zero2.yaml
26
+ trl/accelerate_configs/zero3.yaml
27
+ trl/chat_templates/README.md
28
+ trl/chat_templates/gptoss.jinja
29
+ trl/chat_templates/gptoss_training.jinja
30
+ trl/chat_templates/qwen3.jinja
31
+ trl/chat_templates/qwen3_5_2b_and_below.jinja
32
+ trl/chat_templates/qwen3_5_4b_and_above.jinja
33
+ trl/chat_templates/qwen3_training.jinja
34
+ trl/cli/__init__.py
35
+ trl/cli/accelerate_config.py
36
+ trl/cli/accelerate_launcher.py
37
+ trl/cli/main.py
38
+ trl/cli/commands/__init__.py
39
+ trl/cli/commands/base.py
40
+ trl/cli/commands/env.py
41
+ trl/cli/commands/skills.py
42
+ trl/cli/commands/training.py
43
+ trl/cli/commands/vllm_serve.py
44
+ trl/experimental/__init__.py
45
+ trl/experimental/merge_model_callback.py
46
+ trl/experimental/utils.py
47
+ trl/experimental/winrate_callback.py
48
+ trl/experimental/async_grpo/__init__.py
49
+ trl/experimental/async_grpo/async_grpo_config.py
50
+ trl/experimental/async_grpo/async_grpo_trainer.py
51
+ trl/experimental/async_grpo/async_rollout_worker.py
52
+ trl/experimental/bco/__init__.py
53
+ trl/experimental/bco/bco_config.py
54
+ trl/experimental/bco/bco_trainer.py
55
+ trl/experimental/bema_for_ref_model/__init__.py
56
+ trl/experimental/bema_for_ref_model/callback.py
57
+ trl/experimental/bema_for_ref_model/dpo_trainer.py
58
+ trl/experimental/cpo/__init__.py
59
+ trl/experimental/cpo/cpo_config.py
60
+ trl/experimental/cpo/cpo_trainer.py
61
+ trl/experimental/distillation/__init__.py
62
+ trl/experimental/distillation/distillation.py
63
+ trl/experimental/distillation/distillation_config.py
64
+ trl/experimental/distillation/distillation_trainer.py
65
+ trl/experimental/dppo/__init__.py
66
+ trl/experimental/dppo/dppo_config.py
67
+ trl/experimental/dppo/dppo_trainer.py
68
+ trl/experimental/gfpo/__init__.py
69
+ trl/experimental/gfpo/gfpo_config.py
70
+ trl/experimental/gfpo/gfpo_trainer.py
71
+ trl/experimental/gkd/__init__.py
72
+ trl/experimental/gkd/gkd_config.py
73
+ trl/experimental/gkd/gkd_trainer.py
74
+ trl/experimental/gold/__init__.py
75
+ trl/experimental/gold/gold.py
76
+ trl/experimental/gold/gold_config.py
77
+ trl/experimental/gold/gold_trainer.py
78
+ trl/experimental/grpo_with_replay_buffer/__init__.py
79
+ trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py
80
+ trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py
81
+ trl/experimental/gspo_token/__init__.py
82
+ trl/experimental/gspo_token/grpo_trainer.py
83
+ trl/experimental/judges/__init__.py
84
+ trl/experimental/judges/judges.py
85
+ trl/experimental/kto/__init__.py
86
+ trl/experimental/kto/kto_config.py
87
+ trl/experimental/kto/kto_trainer.py
88
+ trl/experimental/minillm/__init__.py
89
+ trl/experimental/minillm/minillm_config.py
90
+ trl/experimental/minillm/minillm_trainer.py
91
+ trl/experimental/nash_md/__init__.py
92
+ trl/experimental/nash_md/nash_md_config.py
93
+ trl/experimental/nash_md/nash_md_trainer.py
94
+ trl/experimental/online_dpo/__init__.py
95
+ trl/experimental/online_dpo/online_dpo_config.py
96
+ trl/experimental/online_dpo/online_dpo_trainer.py
97
+ trl/experimental/openenv/__init__.py
98
+ trl/experimental/openenv/utils.py
99
+ trl/experimental/orpo/__init__.py
100
+ trl/experimental/orpo/orpo_config.py
101
+ trl/experimental/orpo/orpo_trainer.py
102
+ trl/experimental/papo/__init__.py
103
+ trl/experimental/papo/papo_config.py
104
+ trl/experimental/papo/papo_trainer.py
105
+ trl/experimental/ppo/__init__.py
106
+ trl/experimental/ppo/modeling_value_head.py
107
+ trl/experimental/ppo/ppo_config.py
108
+ trl/experimental/ppo/ppo_trainer.py
109
+ trl/experimental/prm/__init__.py
110
+ trl/experimental/prm/prm_config.py
111
+ trl/experimental/prm/prm_trainer.py
112
+ trl/experimental/sdft/__init__.py
113
+ trl/experimental/sdft/sdft.py
114
+ trl/experimental/sdft/sdft_config.py
115
+ trl/experimental/sdft/sdft_trainer.py
116
+ trl/experimental/sdpo/__init__.py
117
+ trl/experimental/sdpo/sdpo.py
118
+ trl/experimental/sdpo/sdpo_config.py
119
+ trl/experimental/sdpo/sdpo_trainer.py
120
+ trl/experimental/self_distillation/__init__.py
121
+ trl/experimental/self_distillation/base_self_distillation_trainer.py
122
+ trl/experimental/self_distillation/online_rollout_mixin.py
123
+ trl/experimental/self_distillation/peft_adapter_ema_callback.py
124
+ trl/experimental/self_distillation/self_distillation_config.py
125
+ trl/experimental/self_distillation/self_distillation_mixin.py
126
+ trl/experimental/self_distillation/teacher_context.py
127
+ trl/experimental/xpo/__init__.py
128
+ trl/experimental/xpo/xpo_config.py
129
+ trl/experimental/xpo/xpo_trainer.py
130
+ trl/extras/__init__.py
131
+ trl/extras/dataset_formatting.py
132
+ trl/extras/profiling.py
133
+ trl/generation/__init__.py
134
+ trl/generation/vllm_client.py
135
+ trl/generation/vllm_generation.py
136
+ trl/models/__init__.py
137
+ trl/models/activation_offloading.py
138
+ trl/models/utils.py
139
+ trl/rewards/__init__.py
140
+ trl/rewards/accuracy_rewards.py
141
+ trl/rewards/format_rewards.py
142
+ trl/rewards/other_rewards.py
143
+ trl/scripts/__init__.py
144
+ trl/scripts/_hf_argparser.py
145
+ trl/scripts/dpo.py
146
+ trl/scripts/env.py
147
+ trl/scripts/grpo.py
148
+ trl/scripts/kto.py
149
+ trl/scripts/reward.py
150
+ trl/scripts/rloo.py
151
+ trl/scripts/sft.py
152
+ trl/scripts/utils.py
153
+ trl/scripts/vllm_serve.py
154
+ trl/skills/__init__.py
155
+ trl/skills/cli.py
156
+ trl/skills/skills.py
157
+ trl/skills/trl-training/SKILL.md
158
+ trl/templates/completions_dataset_card.md
159
+ trl/templates/lm_model_card.md
160
+ trl/templates/rm_model_card.md
161
+ trl/trainer/__init__.py
162
+ trl/trainer/base_config.py
163
+ trl/trainer/base_trainer.py
164
+ trl/trainer/callbacks.py
165
+ trl/trainer/dpo_config.py
166
+ trl/trainer/dpo_trainer.py
167
+ trl/trainer/grpo_config.py
168
+ trl/trainer/grpo_trainer.py
169
+ trl/trainer/kto_config.py
170
+ trl/trainer/kto_trainer.py
171
+ trl/trainer/model_config.py
172
+ trl/trainer/reward_config.py
173
+ trl/trainer/reward_trainer.py
174
+ trl/trainer/rloo_config.py
175
+ trl/trainer/rloo_trainer.py
176
+ trl/trainer/sft_config.py
177
+ trl/trainer/sft_trainer.py
178
+ trl/trainer/utils.py
tasks/tasksmith-0ea2241cceeb/environment/source/trl.egg-info/dependency_links.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
tasks/tasksmith-0ea2241cceeb/environment/source/trl.egg-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [console_scripts]
2
+ trl = trl.cli:main
tasks/tasksmith-0ea2241cceeb/environment/source/trl.egg-info/requires.txt ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate>=1.4.0
2
+ datasets>=4.7.0
3
+ jinja2
4
+ packaging>20.0
5
+ transformers>=4.56.2
6
+
7
+ [bco]
8
+ scikit-learn
9
+ joblib
10
+
11
+ [deepspeed]
12
+ deepspeed>=0.14.4
13
+ transformers!=5.1.0
14
+
15
+ [dev]
16
+ scikit-learn
17
+ joblib
18
+ deepspeed>=0.14.4
19
+ openai>=1.23.2
20
+ llm-blender>=0.0.2
21
+ kernels
22
+ liger-kernel>=0.7.0
23
+ peft>=0.8.0
24
+ pre-commit
25
+ hf-doc-builder
26
+ bitsandbytes
27
+ pytest-cov
28
+ pytest-datadir>=1.7.0
29
+ pytest-rerunfailures==15.1
30
+ pytest-xdist
31
+ pytest
32
+ Pillow
33
+ torchvision
34
+ num2words==0.5.14
35
+ jmespath
36
+
37
+ [judges]
38
+ openai>=1.23.2
39
+ llm-blender>=0.0.2
40
+ transformers<5.0.0
41
+
42
+ [kernels]
43
+ kernels
44
+
45
+ [liger]
46
+ liger-kernel>=0.7.0
47
+
48
+ [math_verify]
49
+ math-verify>=0.5.2
50
+
51
+ [peft]
52
+ peft>=0.8.0
53
+
54
+ [quality]
55
+ pre-commit
56
+ hf-doc-builder
57
+
58
+ [quantization]
59
+ bitsandbytes
60
+
61
+ [scikit]
62
+ scikit-learn
63
+
64
+ [test]
65
+ pytest-cov
66
+ pytest-datadir>=1.7.0
67
+ pytest-rerunfailures==15.1
68
+ pytest-xdist
69
+ pytest
70
+
71
+ [vllm]
72
+ vllm<=0.17.1,>=0.11.0
73
+ fastapi
74
+ pydantic
75
+ aiohttp>=3.13.3
76
+ requests
77
+ uvicorn
78
+
79
+ [vlm]
80
+ Pillow
81
+ torchvision
82
+ num2words==0.5.14
tasks/tasksmith-0ea2241cceeb/environment/source/trl.egg-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ trl
tasks/tasksmith-0ea2241cceeb/environment/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-0ea2241cceeb/environment/source/trl/_compat.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_vllm_disabled_tqdm() -> None:
87
+ """
88
+ Fix DisabledTqdm class in vLLM.
89
+
90
+ - Bug introduced in https://github.com/vllm-project/vllm/pull/52
91
+ - Fixed in https://github.com/vllm-project/vllm/pull/28471 (released in v0.11.1)
92
+ - Since TRL currently supports vLLM v0.11.0-0.17.1, we patch it here
93
+ - This can be removed when TRL requires vLLM>=0.11.1
94
+ """
95
+ if _is_package_version_below("vllm", "0.11.1"):
96
+ try:
97
+ import vllm.model_executor.model_loader.weight_utils
98
+ from tqdm import tqdm
99
+
100
+ class DisabledTqdm(tqdm):
101
+ def __init__(self, *args, **kwargs):
102
+ kwargs["disable"] = True
103
+ super().__init__(*args, **kwargs)
104
+
105
+ vllm.model_executor.model_loader.weight_utils.DisabledTqdm = DisabledTqdm
106
+ except (ImportError, AttributeError) as e:
107
+ warnings.warn(f"Failed to patch vLLM DisabledTqdm: {e}", stacklevel=2)
108
+
109
+
110
+ def _patch_vllm_cached_tokenizer() -> None:
111
+ """
112
+ Fix get_cached_tokenizer for transformers v5 compatibility.
113
+
114
+ - Issue: vLLM's get_cached_tokenizer accesses all_special_tokens_extended
115
+ - Removed in transformers: https://github.com/huggingface/transformers/pull/40936 (transformers>=5.0.0)
116
+ - Fixed in https://github.com/vllm-project/vllm/pull/29686 (released in v0.12.0)
117
+ - This can be removed when TRL requires vLLM>=0.12.0
118
+ """
119
+ if _is_package_version_at_least("transformers", "5.0.0") and _is_package_version_below("vllm", "0.12.0"):
120
+ try:
121
+ import contextlib
122
+ import copy
123
+
124
+ import vllm.transformers_utils.tokenizer
125
+
126
+ def get_cached_tokenizer(tokenizer):
127
+ cached_tokenizer = copy.copy(tokenizer)
128
+ tokenizer_all_special_ids = tokenizer.all_special_ids
129
+ tokenizer_all_special_tokens = tokenizer.all_special_tokens
130
+ tokenizer_vocab = tokenizer.get_vocab()
131
+ tokenizer_len = len(tokenizer)
132
+
133
+ max_token_id = max(tokenizer_vocab.values())
134
+ if hasattr(tokenizer, "vocab_size"):
135
+ with contextlib.suppress(NotImplementedError):
136
+ max_token_id = max(max_token_id, tokenizer.vocab_size)
137
+
138
+ class CachedTokenizer(tokenizer.__class__): # type: ignore
139
+ @property
140
+ def all_special_ids(self) -> list[int]:
141
+ return tokenizer_all_special_ids
142
+
143
+ @property
144
+ def all_special_tokens(self) -> list[str]:
145
+ return tokenizer_all_special_tokens
146
+
147
+ @property
148
+ def max_token_id(self) -> int:
149
+ return max_token_id
150
+
151
+ def get_vocab(self) -> dict[str, int]:
152
+ return tokenizer_vocab
153
+
154
+ def __len__(self) -> int:
155
+ return tokenizer_len
156
+
157
+ def __reduce__(self):
158
+ return get_cached_tokenizer, (tokenizer,)
159
+
160
+ CachedTokenizer.__name__ = f"Cached{tokenizer.__class__.__name__}"
161
+
162
+ cached_tokenizer.__class__ = CachedTokenizer
163
+ return cached_tokenizer
164
+
165
+ vllm.transformers_utils.tokenizer.get_cached_tokenizer = get_cached_tokenizer
166
+ except (ImportError, AttributeError) as e:
167
+ warnings.warn(f"Failed to patch vLLM cached_tokenizer: {e}", stacklevel=2)
168
+
169
+
170
+ def _patch_transformers_hybrid_cache() -> None:
171
+ """
172
+ Fix HybridCache import for transformers v5 compatibility.
173
+
174
+ - Issue: peft import HybridCache from transformers.cache_utils
175
+ - HybridCache removed in https://github.com/huggingface/transformers/pull/43168 (transformers>=5.0.0)
176
+ - Fixed in peft: https://github.com/huggingface/peft/pull/2735 (released in v0.18.0)
177
+ - This can be removed when TRL requires peft>=0.18.0
178
+ """
179
+ if _is_package_version_at_least("transformers", "5.0.0") and _is_package_version_below("peft", "0.18.0"):
180
+ try:
181
+ import transformers.cache_utils
182
+ from transformers.utils.import_utils import _LazyModule
183
+
184
+ Cache = transformers.cache_utils.Cache
185
+
186
+ # Patch for liger_kernel: Add HybridCache as an alias for Cache in the cache_utils module
187
+ transformers.cache_utils.HybridCache = Cache
188
+
189
+ # Patch for peft: Patch _LazyModule.__init__ to add HybridCache to transformers' lazy loading structures
190
+ _original_lazy_module_init = _LazyModule.__init__
191
+
192
+ def _patched_lazy_module_init(self, name, *args, **kwargs):
193
+ _original_lazy_module_init(self, name, *args, **kwargs)
194
+ if name == "transformers":
195
+ # Update _LazyModule's internal structures
196
+ if hasattr(self, "_import_structure") and "cache_utils" in self._import_structure:
197
+ if "HybridCache" not in self._import_structure["cache_utils"]:
198
+ self._import_structure["cache_utils"].append("HybridCache")
199
+
200
+ if hasattr(self, "_class_to_module"):
201
+ self._class_to_module["HybridCache"] = "cache_utils"
202
+
203
+ if hasattr(self, "__all__") and "HybridCache" not in self.__all__:
204
+ self.__all__.append("HybridCache")
205
+
206
+ self.HybridCache = Cache
207
+
208
+ _LazyModule.__init__ = _patched_lazy_module_init
209
+
210
+ except Exception as e:
211
+ warnings.warn(f"Failed to patch transformers HybridCache compatibility: {e}", stacklevel=2)
212
+
213
+
214
+ def _patch_transformers_parallelism_config() -> None:
215
+ """
216
+ Fix ParallelismConfig for transformers compatibility.
217
+
218
+ Ensure that ``transformers.training_args`` always defines the symbol `ParallelismConfig` so that Python's
219
+ `typing.get_type_hints` can resolve annotations on `transformers.TrainingArguments` without raising a `NameError`.
220
+
221
+ This is needed when running with ``accelerate<1.10.1``, where the module ``accelerate.parallelism_config`` did not
222
+ exist and therefore the type alias is not imported by Transformers.
223
+
224
+ See upstream fix PR in transformers#40818.
225
+
226
+ - Issue: transformers imports ParallelismConfig only if accelerate>=1.10.1 and raises NameError if
227
+ accelerate<1.10.1
228
+ - Fixed in transformers: https://github.com/huggingface/transformers/pull/40818 (released in v4.57.0)
229
+ - This can be removed when TRL requires transformers>=4.57.0 or accelerate>=1.10.1
230
+ """
231
+ if _is_package_version_below("transformers", "4.57.0") and _is_package_version_below("accelerate", "1.10.1"):
232
+ try:
233
+ from typing import Any
234
+
235
+ import transformers.training_args
236
+
237
+ if not hasattr(transformers.training_args, "ParallelismConfig"):
238
+ transformers.training_args.ParallelismConfig = Any
239
+ except Exception as e:
240
+ warnings.warn(f"Failed to patch transformers ParallelismConfig compatibility: {e}", stacklevel=2)
241
+
242
+
243
+ # Apply vLLM patches
244
+ _patch_vllm_logging()
245
+ _patch_vllm_disabled_tqdm()
246
+ _patch_vllm_cached_tokenizer()
247
+
248
+ # Apply transformers patches
249
+ _patch_transformers_hybrid_cache()
250
+ _patch_transformers_parallelism_config() # before creating HfArgumentParser
tasks/tasksmith-0ea2241cceeb/environment/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-0ea2241cceeb/environment/source/trl/accelerate_configs/fsdp1.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ distributed_type: FSDP
4
+ downcast_bf16: 'no'
5
+ enable_cpu_affinity: false
6
+ fsdp_config:
7
+ fsdp_activation_checkpointing: false
8
+ fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
9
+ fsdp_backward_prefetch: BACKWARD_PRE
10
+ fsdp_cpu_ram_efficient_loading: true
11
+ fsdp_forward_prefetch: true
12
+ fsdp_offload_params: false
13
+ fsdp_reshard_after_forward: FULL_SHARD
14
+ fsdp_state_dict_type: FULL_STATE_DICT
15
+ fsdp_sync_module_states: true
16
+ fsdp_use_orig_params: true
17
+ fsdp_version: 1
18
+ machine_rank: 0
19
+ main_training_function: main
20
+ mixed_precision: bf16
21
+ num_machines: 1
22
+ num_processes: 8
23
+ rdzv_backend: static
24
+ same_network: true
25
+ tpu_env: []
26
+ tpu_use_cluster: false
27
+ tpu_use_sudo: false
28
+ use_cpu: false
tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/fsdp2.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Requires accelerate 1.7.0 or higher
2
+ compute_environment: LOCAL_MACHINE
3
+ debug: false
4
+ distributed_type: FSDP
5
+ downcast_bf16: 'no'
6
+ enable_cpu_affinity: false
7
+ fsdp_config:
8
+ fsdp_activation_checkpointing: false
9
+ fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
10
+ fsdp_cpu_ram_efficient_loading: true
11
+ fsdp_offload_params: false
12
+ fsdp_reshard_after_forward: true
13
+ fsdp_state_dict_type: FULL_STATE_DICT
14
+ fsdp_version: 2
15
+ machine_rank: 0
16
+ main_training_function: main
17
+ mixed_precision: bf16
18
+ num_machines: 1
19
+ num_processes: 8
20
+ rdzv_backend: static
21
+ same_network: true
22
+ tpu_env: []
23
+ tpu_use_cluster: false
24
+ tpu_use_sudo: false
25
+ use_cpu: false
tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/multi_gpu.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ distributed_type: MULTI_GPU
4
+ downcast_bf16: 'no'
5
+ gpu_ids: all
6
+ machine_rank: 0
7
+ main_training_function: main
8
+ mixed_precision: 'bf16'
9
+ num_machines: 1
10
+ num_processes: 8
11
+ rdzv_backend: static
12
+ same_network: true
13
+ tpu_env: []
14
+ tpu_use_cluster: false
15
+ tpu_use_sudo: false
16
+ use_cpu: false
tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/single_gpu.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ distributed_type: "NO"
4
+ downcast_bf16: 'no'
5
+ gpu_ids: all
6
+ machine_rank: 0
7
+ main_training_function: main
8
+ mixed_precision: 'bf16'
9
+ num_machines: 1
10
+ num_processes: 8
11
+ rdzv_backend: static
12
+ same_network: true
13
+ tpu_env: []
14
+ tpu_use_cluster: false
15
+ tpu_use_sudo: false
16
+ use_cpu: false
tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/zero1.yaml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ deepspeed_config:
4
+ deepspeed_multinode_launcher: standard
5
+ gradient_accumulation_steps: 1
6
+ zero3_init_flag: false
7
+ zero_stage: 1
8
+ distributed_type: DEEPSPEED
9
+ downcast_bf16: 'no'
10
+ machine_rank: 0
11
+ main_training_function: main
12
+ mixed_precision: 'bf16'
13
+ num_machines: 1
14
+ num_processes: 8
15
+ rdzv_backend: static
16
+ same_network: true
17
+ tpu_env: []
18
+ tpu_use_cluster: false
19
+ tpu_use_sudo: false
20
+ use_cpu: false
tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/zero2.yaml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ deepspeed_config:
4
+ deepspeed_multinode_launcher: standard
5
+ offload_optimizer_device: none
6
+ offload_param_device: none
7
+ zero3_init_flag: false
8
+ zero_stage: 2
9
+ distributed_type: DEEPSPEED
10
+ downcast_bf16: 'no'
11
+ machine_rank: 0
12
+ main_training_function: main
13
+ mixed_precision: 'bf16'
14
+ num_machines: 1
15
+ num_processes: 8
16
+ rdzv_backend: static
17
+ same_network: true
18
+ tpu_env: []
19
+ tpu_use_cluster: false
20
+ tpu_use_sudo: false
21
+ use_cpu: false
tasks/tasksmith-0ea2241cceeb/environment/source/trl/accelerate_configs/zero3.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ deepspeed_config:
4
+ deepspeed_multinode_launcher: standard
5
+ offload_optimizer_device: none
6
+ offload_param_device: none
7
+ zero3_init_flag: true
8
+ zero3_save_16bit_model: true
9
+ zero_stage: 3
10
+ distributed_type: DEEPSPEED
11
+ downcast_bf16: 'no'
12
+ machine_rank: 0
13
+ main_training_function: main
14
+ mixed_precision: bf16
15
+ num_machines: 1
16
+ num_processes: 8
17
+ rdzv_backend: static
18
+ same_network: true
19
+ tpu_env: []
20
+ tpu_use_cluster: false
21
+ tpu_use_sudo: false
22
+ use_cpu: false
tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_template_utils.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from jinja2 import TemplateError
18
+ from transformers import AddedToken, AutoTokenizer, PreTrainedModel, PreTrainedTokenizer, ProcessorMixin
19
+
20
+ from .data_utils import prepare_multimodal_messages
21
+
22
+
23
+ _CHAT_TEMPLATES_DIR = Path(__file__).parent / "chat_templates"
24
+
25
+
26
+ def clone_chat_template(
27
+ model: PreTrainedModel,
28
+ tokenizer: PreTrainedTokenizer,
29
+ source_tokenizer_path: str,
30
+ resize_to_multiple_of: int | None = 64,
31
+ ) -> tuple[PreTrainedModel, PreTrainedTokenizer, list[int]]:
32
+ """
33
+ Clones a chat template from a source tokenizer to the target tokenizer and updates the model accordingly.
34
+
35
+ This function:
36
+ - Copies the chat template from a source tokenizer to the target tokenizer.
37
+ - Adds any new tokens from the source tokenizer to the target tokenizer.
38
+ - Sets and synchronizes the EOS token across the tokenizer and model.
39
+ - Resizes the model's token embeddings to match the new vocabulary size, optionally rounding it up to a multiple of
40
+ a specified value. In such cases, dummy tokens are added to the tokenizer to ensure the vocabulary size matches
41
+ the embedding dimensions.
42
+
43
+ Args:
44
+ model ([`~transformers.PreTrainedModel`]):
45
+ Model to update.
46
+ tokenizer ([`~transformers.PreTrainedTokenizer`]):
47
+ Tokenizer to update.
48
+ source_tokenizer_path (`str`):
49
+ Path or identifier of the pretrained tokenizer to clone from.
50
+ resize_to_multiple_of (`int` or `None`, *optional*, defaults to `64`):
51
+ The embedding layer will be resized to the new vocabulary size. If this is not `None`, it will round up the
52
+ new vocabulary size to the nearest multiple of this value.
53
+
54
+ Returns:
55
+ model ([`~transformers.PreTrainedModel`]):
56
+ Updated model with resized token embeddings and EOS token configured.
57
+ tokenizer ([`~transformers.PreTrainedTokenizer`]):
58
+ Updated tokenizer with the chat template and special tokens applied.
59
+ added_tokens (`list[int]`):
60
+ List of tokens that were added to the tokenizer from the source tokenizer.
61
+
62
+ Example:
63
+ ```python
64
+ from transformers import AutoModelForCausalLM, AutoTokenizer
65
+ from trl import clone_chat_template
66
+
67
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
68
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
69
+ model, tokenizer, added_tokens = clone_chat_template(model, tokenizer, "Qwen/Qwen3-0.6B")
70
+ ```
71
+ """
72
+ # Load the source tokenizer containing the desired chat template
73
+ tokenizer_source = AutoTokenizer.from_pretrained(source_tokenizer_path)
74
+
75
+ # Copy the chat template from the source tokenizer
76
+ tokenizer.chat_template = tokenizer_source.get_chat_template()
77
+
78
+ # Ensure all added tokens from the source are available in the target tokenizer
79
+ added_tokens = [
80
+ token for token in tokenizer_source.added_tokens_decoder.values() if token.content not in tokenizer.vocab
81
+ ]
82
+ tokenizer.add_tokens(added_tokens)
83
+
84
+ # Set the EOS token from the source tokenizer (important for generation)
85
+ tokenizer.eos_token = tokenizer_source.eos_token
86
+ model.config.eos_token_id = tokenizer.eos_token_id
87
+ if model.can_generate(): # Non-generative models (e.g. SequenceClassification) may not have a generation_config
88
+ model.generation_config.eos_token_id = tokenizer.eos_token_id
89
+
90
+ # Resize model embeddings to include any new tokens, optionally rounding up to a multiple
91
+ model.resize_token_embeddings(
92
+ # After studying many tokenizers, we found that len(tokenizer.vocab) is the most reliable way to get the vocab
93
+ # size. Avoid using tokenizer.vocab_size or tokenizer.vocab_size + len(tokenizer.added_tokens_encoder),
94
+ # as handling of special and added tokens varies across tokenizers.
95
+ new_num_tokens=len(tokenizer.vocab),
96
+ pad_to_multiple_of=resize_to_multiple_of if resize_to_multiple_of is not None else None,
97
+ )
98
+
99
+ # After resizing, the embedding matrix size may exceed the vocabulary size. Add dummy tokens to the tokenizer to
100
+ # ensure vocabulary size matches the embedding matrix dimensions.
101
+ idx = 0
102
+ while model.vocab_size > len(tokenizer.vocab):
103
+ dummy_token = AddedToken(f"<extra_id_{idx}>")
104
+ is_added = tokenizer.add_tokens(dummy_token)
105
+ idx += 1
106
+ if is_added == 1:
107
+ added_tokens.append(dummy_token)
108
+
109
+ # Verify that vocabulary size now matches embedding dimensions
110
+ if len(tokenizer.vocab) != model.vocab_size:
111
+ raise RuntimeError(
112
+ f"Vocabulary size mismatch after resizing: tokenizer vocab size is {len(tokenizer.vocab)}, but model "
113
+ f"embedding size is {model.vocab_size}. This indicates an internal error in the token alignment process."
114
+ )
115
+ added_tokens = [token.content for token in added_tokens]
116
+ added_tokens = tokenizer.convert_tokens_to_ids(added_tokens)
117
+ return model, tokenizer, added_tokens
118
+
119
+
120
+ gptoss_schema = {
121
+ # Normalize final content to analysis format so both map to the same "content" group.
122
+ "x-regex-substitutions": [
123
+ [r"<\|channel\|>final<\|message\|>(.*?)<\|return\|>", r"<|channel|>analysis<|message|>\1<|end|>"],
124
+ ],
125
+ "x-regex": r"^(?:<\|channel\|>analysis<\|message\|>(?P<content>.*?)<\|end\|>(?:<\|start\|>assistant)?)?\s*(?P<tool_calls>to=functions\.\S+<\|channel\|>commentary json<\|message\|>.*?<\|call\|>)?$",
126
+ "type": "object",
127
+ "properties": {
128
+ "role": {"const": "assistant"},
129
+ "content": {"type": "string"},
130
+ "tool_calls": {
131
+ "type": "array",
132
+ "x-regex-iterator": r"(to=functions\.\S+<\|channel\|>commentary json<\|message\|>.*?<\|call\|>)",
133
+ "items": {
134
+ # Convert "to=functions.NAME<|channel|>commentary json<|message|>ARGS<|call|>"
135
+ # into '{"name": "NAME", "arguments": ARGS}' so it can be parsed as JSON.
136
+ "x-regex-substitutions": [
137
+ [
138
+ r"to=functions\.(\S+)<\|channel\|>commentary json<\|message\|>(.*?)<\|call\|>",
139
+ r'{"name": "\1", "arguments": \2}',
140
+ ],
141
+ ],
142
+ "x-parser": "json",
143
+ "x-parser-args": {"transform": "{type: 'function', function: @}"},
144
+ "type": "object",
145
+ "properties": {
146
+ "type": {"const": "function"},
147
+ "function": {
148
+ "type": "object",
149
+ "properties": {
150
+ "name": {"type": "string"},
151
+ "arguments": {
152
+ "type": "object",
153
+ "additionalProperties": {},
154
+ },
155
+ },
156
+ },
157
+ },
158
+ },
159
+ },
160
+ },
161
+ }
162
+
163
+ # Adapted and corrected versions of the schemas from:
164
+ # https://github.com/huggingface/transformers/blob/main/tests/utils/test_chat_parsing_utils.py
165
+ qwen3_schema = {
166
+ "x-regex": r"^(?:<think>\n?(?:(?P<reasoning_content>.*?\S.*?)\n?|[\s]*)</think>\s*)?(?P<content>.*?)(?:\n(?=<tool_call>))?(?=(?:<tool_call>|<\|im_end\|>|$))(?P<tool_calls>(?:<tool_call>.+?</tool_call>\s*)+)?\s*(?:<\|im_end\|>|$)",
167
+ "type": "object",
168
+ "properties": {
169
+ "role": {"const": "assistant"},
170
+ "content": {"type": "string"},
171
+ "reasoning_content": {"type": "string"},
172
+ "tool_calls": {
173
+ "type": "array",
174
+ "x-regex-iterator": r"<tool_call>\s*(.+?)\s*</tool_call>",
175
+ "items": {
176
+ "x-parser": "json",
177
+ "x-parser-args": {"transform": "{type: 'function', function: @}"},
178
+ "type": "object",
179
+ "properties": {
180
+ "type": {"const": "function"},
181
+ "function": {
182
+ "type": "object",
183
+ "properties": {
184
+ "name": {"type": "string"},
185
+ "arguments": {
186
+ "type": "object",
187
+ "additionalProperties": {},
188
+ },
189
+ },
190
+ },
191
+ },
192
+ },
193
+ },
194
+ },
195
+ }
196
+
197
+ qwen3_5_schema = {
198
+ "x-regex": r"^(?:(?:<think>\n?)?(?:(?P<reasoning_content>.*?\S.*?)\n?|[\s]*)</think>\s*)?(?P<content>.*?)(?:\n+(?=<tool_call>))?(?=(?:<tool_call>|<\|im_end\|>|$))(?P<tool_calls>(?:<tool_call>.+?</tool_call>\s*)+)?\s*(?:<\|im_end\|>|$)",
199
+ "type": "object",
200
+ "properties": {
201
+ "role": {"const": "assistant"},
202
+ "content": {"type": "string"},
203
+ "reasoning_content": {"type": "string"},
204
+ "tool_calls": {
205
+ "type": "array",
206
+ "x-regex-iterator": r"<tool_call>\s*(.+?)\s*</tool_call>",
207
+ "items": {
208
+ "type": "object",
209
+ "properties": {
210
+ "type": {"const": "function"},
211
+ "function": {
212
+ "type": "object",
213
+ "properties": {
214
+ "name": {"type": "string", "x-regex": r"<function=([^\n>]+)>"},
215
+ "arguments": {
216
+ "type": "object",
217
+ "x-regex-key-value": r"<parameter=(?P<key>[^>\n]+)>\n(?P<value>.*?)\n</parameter>",
218
+ "default": {},
219
+ "additionalProperties": {
220
+ "x-parser": "json",
221
+ "x-parser-args": {"allow_non_json": True},
222
+ },
223
+ },
224
+ },
225
+ },
226
+ },
227
+ },
228
+ },
229
+ },
230
+ }
231
+
232
+
233
+ gptoss_chat_template = (_CHAT_TEMPLATES_DIR / "gptoss.jinja").read_text()
234
+
235
+ qwen3_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3.jinja").read_text()
236
+
237
+ qwen3_5_chat_template_2b_and_below = (_CHAT_TEMPLATES_DIR / "qwen3_5_2b_and_below.jinja").read_text()
238
+
239
+ qwen3_5_chat_template_4b_and_above = (_CHAT_TEMPLATES_DIR / "qwen3_5_4b_and_above.jinja").read_text()
240
+
241
+
242
+ def add_response_schema(tokenizer: PreTrainedTokenizer) -> PreTrainedTokenizer:
243
+ r"""
244
+ Adds the appropriate response schema to the given tokenizer based on its chat template.
245
+
246
+ At the time of initial implementation, most tokenizers do not have built-in support for response schemas. While
247
+ waiting for broader adoption, we provide this utility function to manually set the response schema for known chat
248
+ templates.
249
+
250
+ Args:
251
+ tokenizer (`PreTrainedTokenizer`):
252
+ Tokenizer to which the response schema will be added.
253
+
254
+ Returns:
255
+ `PreTrainedTokenizer`:
256
+ Tokenizer with the added response schema.
257
+
258
+ Examples:
259
+
260
+ ```python
261
+ >>> from trl.chat_template_utils import add_response_schema
262
+ >>> from transformers import AutoTokenizer
263
+
264
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
265
+ >>> tokenizer = add_response_schema(tokenizer)
266
+ >>> assistant_text = '<tool_call>\n{"name": "multiply", "arguments": {"a": 3, "b": 4}}\n</tool_call><|im_end|>'
267
+ >>> tokenizer.parse_response(assistant_text)
268
+ {'role': 'assistant', 'content': '', 'tool_calls': [{'type': 'function', 'function': {'name': 'multiply', 'arguments': {'a': 3, 'b': 4}}}]}
269
+ ```
270
+ """
271
+ if tokenizer.chat_template == gptoss_chat_template:
272
+ tokenizer.response_schema = gptoss_schema
273
+ return tokenizer
274
+ if tokenizer.chat_template == qwen3_chat_template:
275
+ tokenizer.response_schema = qwen3_schema
276
+ return tokenizer
277
+ if tokenizer.chat_template in [qwen3_5_chat_template_2b_and_below, qwen3_5_chat_template_4b_and_above]:
278
+ tokenizer.response_schema = qwen3_5_schema
279
+ return tokenizer
280
+ raise ValueError(
281
+ "Unrecognized chat template, failed to add response schema. Please manually set the response schema on the "
282
+ "tokenizer or processor. See the Transformers "
283
+ "[docs](https://huggingface.co/docs/transformers/main/en/chat_response_parsing#response-parsing) for more "
284
+ "details on response parsing."
285
+ )
286
+
287
+
288
+ def supports_tool_calling(processing_class) -> bool:
289
+ """
290
+ Check if the processing class's chat template can render a full tool-calling conversation.
291
+
292
+ This tests two things: (1) the template doesn't error when rendering a conversation with ``user → assistant (with
293
+ tool_calls) → tool`` roles, and (2) the tool message content actually appears in the rendered output (some
294
+ templates silently swallow tool messages).
295
+
296
+ For VLMs (processors), the messages are converted to multimodal format via
297
+ [`~trl.data_utils.prepare_multimodal_messages`] before rendering.
298
+
299
+ Args:
300
+ processing_class (`PreTrainedTokenizer` or `ProcessorMixin`):
301
+ Tokenizer or processor instance to check.
302
+
303
+ Returns:
304
+ `bool`:
305
+ `True` if the chat template supports tool-calling conversations, `False` otherwise.
306
+ """
307
+ if processing_class.chat_template is None:
308
+ return False
309
+
310
+ is_vlm = isinstance(processing_class, ProcessorMixin)
311
+ _sentinel = "TOOL_CONTENT_c4f9a8e2"
312
+ tool_calls = [{"type": "function", "function": {"name": "test", "arguments": {}}}]
313
+ messages = [
314
+ {"role": "user", "content": "hi"},
315
+ {"role": "assistant", "content": "", "tool_calls": tool_calls},
316
+ {"role": "tool", "name": "test", "content": _sentinel},
317
+ ]
318
+ # VLMs expect content as [{"type": "text", "text": "..."}] instead of plain strings
319
+ if is_vlm:
320
+ messages = prepare_multimodal_messages(messages)
321
+
322
+ try:
323
+ rendered = processing_class.apply_chat_template(messages, tokenize=False)
324
+ except TemplateError:
325
+ # TemplateError: template rejects the role sequence (Cohere, FalconMamba, Gemma, Gemma2, Gemma3)
326
+ # UndefinedError (subclass): template indexes into content as a list for all roles, including tool
327
+ # (Idefics2, Idefics3, LlavaNext, SmolVLM)
328
+ return False
329
+ # Some templates (e.g. Cohere2, Phi3) accept tool messages without error but silently ignore them.
330
+ # Check that the tool content actually appears in the rendered output.
331
+ return _sentinel in rendered
332
+
333
+
334
+ def is_chat_template_prefix_preserving(tokenizer: PreTrainedTokenizer) -> bool:
335
+ """
336
+ Check whether the chat template preserves prefixes when applied.
337
+
338
+ A prefix-preserving chat template renders earlier messages identically regardless of what messages follow. This
339
+ property is required by `_get_tool_suffix_ids`, which extracts tool response formatting tokens by comparing
340
+ tokenizations with and without tool messages appended.
341
+
342
+ Args:
343
+ tokenizer (`PreTrainedTokenizer`):
344
+ Tokenizer instance to check.
345
+
346
+ Returns:
347
+ `bool`:
348
+ `True` if the chat template preserves prefixes, `False` otherwise.
349
+ """
350
+ # Use the same dummy messages as _get_tool_suffix_ids to test the exact property it relies on.
351
+ dummy_tool_calls = [{"type": "function", "function": {"name": "dummy", "arguments": {}}}]
352
+ messages1 = [
353
+ {"role": "user", "content": "dummy"},
354
+ {"role": "assistant", "content": "", "tool_calls": dummy_tool_calls},
355
+ ]
356
+ messages2 = [
357
+ {"role": "user", "content": "dummy"},
358
+ {"role": "assistant", "content": "", "tool_calls": dummy_tool_calls},
359
+ {"role": "tool", "name": "dummy", "content": "dummy"},
360
+ ]
361
+
362
+ text1 = tokenizer.apply_chat_template(messages1, tokenize=False)
363
+ text2 = tokenizer.apply_chat_template(messages2, tokenize=False, add_generation_prompt=True)
364
+
365
+ return text2.startswith(text1)
366
+
367
+
368
+ qwen3_training_chat_template = (_CHAT_TEMPLATES_DIR / "qwen3_training.jinja").read_text()
369
+ gptoss_training_chat_template = (_CHAT_TEMPLATES_DIR / "gptoss_training.jinja").read_text()
370
+
371
+
372
+ def get_training_chat_template(tokenizer: PreTrainedTokenizer) -> str | None:
373
+ r"""
374
+ Get a training-compatible chat template, if needed.
375
+
376
+ Returns a patched chat template that is prefix-preserving and includes `{%% generation %%}` / `{%% endgeneration
377
+ %%}` markers for assistant-only loss masking. Returns `None` if the tokenizer's template already satisfies both
378
+ requirements. Currently supported:
379
+ - Qwen3
380
+ - GPT-OSS
381
+
382
+ Args:
383
+ tokenizer (`PreTrainedTokenizer`):
384
+ Tokenizer instance to check.
385
+
386
+ Returns:
387
+ `str` or `None`:
388
+ Training-compatible chat template, or `None` if no patching is needed.
389
+
390
+ Example:
391
+
392
+ ```python
393
+ >>> from trl.chat_template_utils import get_training_chat_template
394
+ >>> from transformers import AutoTokenizer
395
+
396
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
397
+ >>> messages1 = [
398
+ ... {"role": "user", "content": "What is 2 * 3?"},
399
+ ... {
400
+ ... "role": "assistant",
401
+ ... "content": "",
402
+ ... "tool_calls": [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 2, "b": 3}}}],
403
+ ... },
404
+ ... ]
405
+ >>> messages2 = messages1 + [
406
+ ... {"role": "tool", "name": "multiply", "content": "6"},
407
+ ... ]
408
+ >>> tokenizer.apply_chat_template(messages1, tokenize=False)
409
+ '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n<tool_call>\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n</tool_call><|im_end|>\n'
410
+
411
+ >>> tokenizer.apply_chat_template(messages2, tokenize=False, add_generation_prompt=True)
412
+ '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n<tool_call>\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n</tool_call><|im_end|>\n<|im_start|>user\n<tool_response>\n6\n</tool_response><|im_end|>\n<|im_start|>assistant\n'
413
+
414
+ >>> # ^ think tags missing
415
+ >>> chat_template = get_training_chat_template(tokenizer)
416
+ >>> tokenizer.apply_chat_template(messages1, tokenize=False, chat_template=chat_template)
417
+ '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n<tool_call>\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n</tool_call><|im_end|>\n'
418
+
419
+ >>> tokenizer.apply_chat_template(
420
+ ... messages2, tokenize=False, add_generation_prompt=True, chat_template=chat_template
421
+ ... )
422
+ '<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n<tool_call>\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n</tool_call><|im_end|>\n<|im_start|>user\n<tool_response>\n6\n</tool_response><|im_end|>\n<|im_start|>assistant\n'
423
+ ```
424
+ """
425
+ # First check if patching is needed
426
+ if is_chat_template_prefix_preserving(tokenizer) and "{% generation %}" in tokenizer.chat_template:
427
+ return None # No patching needed
428
+
429
+ if tokenizer.chat_template == qwen3_chat_template:
430
+ return qwen3_training_chat_template
431
+ elif tokenizer.chat_template == gptoss_chat_template:
432
+ return gptoss_training_chat_template
433
+ else:
434
+ raise ValueError(
435
+ "The tokenizer's chat template is not training-compatible (missing prefix-preservation or "
436
+ "`{% generation %}` markers) and patching is not supported for this template. "
437
+ "Please manually modify the tokenizer's chat template for training."
438
+ )
439
+
440
+
441
+ def _validate_tool_calls(tool_calls: list | None) -> None:
442
+ """
443
+ Validate tool_calls to ensure all required fields exist with valid values.
444
+
445
+ Raises ValueError when the model generates malformed tool calls (e.g., missing 'arguments' field) that are
446
+ partially parsed.
447
+
448
+ Args:
449
+ tool_calls: List of tool call dictionaries, or None.
450
+ """
451
+ if tool_calls is None:
452
+ return None
453
+ if not isinstance(tool_calls, list):
454
+ raise ValueError("tool_calls must be a list or None.")
455
+
456
+ for idx, tool_call in enumerate(tool_calls):
457
+ if not isinstance(tool_call, dict):
458
+ raise ValueError(f"tool_calls[{idx}] must be a dict.")
459
+
460
+ # Handle nested function structure: {"type": "function", "function": {"name": ..., "arguments": ...}}
461
+ if "function" in tool_call:
462
+ func = tool_call["function"]
463
+ if not isinstance(func, dict):
464
+ raise ValueError(f"tool_calls[{idx}]['function'] must be a dict.")
465
+ if not isinstance(func.get("name"), str):
466
+ raise ValueError(f"tool_calls[{idx}]['function']['name'] must be a string.")
467
+ # Some templates (e.g. Qwen3.5) omit arguments for valid no-arg calls; normalize to {}.
468
+ if "arguments" not in func or func["arguments"] is None:
469
+ func["arguments"] = {}
470
+ else:
471
+ # Handle flat structure: {"name": ..., "arguments": ...}
472
+ if not isinstance(tool_call.get("name"), str):
473
+ raise ValueError(f"tool_calls[{idx}]['name'] must be a string.")
474
+ # Some templates (e.g. Qwen3.5) omit arguments for valid no-arg calls; normalize to {}.
475
+ if "arguments" not in tool_call or tool_call["arguments"] is None:
476
+ tool_call["arguments"] = {}
477
+
478
+
479
+ def parse_response(tokenizer_or_processor, ids: list[int]) -> dict:
480
+ r"""
481
+ Parse a token sequence into structured response dictionaries with fallback handling.
482
+
483
+ Attempts to parse the sequence using `tokenizer.parse_response()`. If parsing fails (e.g., due to malformed tool
484
+ calls like `<tool_call>{"type":"function"</tool_call>`), falls back to decoding as plain text.
485
+
486
+ Also removes incorrectly appended EOS tokens from tool call content when present, and validates tool_calls to
487
+ ensure all required fields exist.
488
+
489
+ For VLM processors, automatically uses the inner tokenizer for parsing.
490
+
491
+ Args:
492
+ tokenizer_or_processor (`PreTrainedTokenizer` or VLM processor):
493
+ Tokenizer or processor with a `parse_response()` method (directly or via inner tokenizer).
494
+ ids (`list[int]`):
495
+ List of token sequences.
496
+
497
+ Returns:
498
+ `dict`:
499
+ Response dictionary.
500
+
501
+ Example:
502
+ ```python
503
+ >>> from trl.chat_template_utils import parse_response, add_response_schema
504
+ >>> from transformers import AutoTokenizer
505
+
506
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
507
+ >>> tokenizer = add_response_schema(tokenizer) # temporary until built-in support
508
+ >>> text = '<tool_call>\n{"name": "multiply", "arguments": {"a": 3, "b": 4}}\n</tool_call><|im_end|>'
509
+ >>> ids = tokenizer(text)["input_ids"]
510
+ >>> parse_response(tokenizer, ids)
511
+ {'role': 'assistant', 'content': '', 'tool_calls': [{'type': 'function', 'function': {'name': 'multiply', 'arguments': {'a': 3, 'b': 4}}}]}
512
+ ```
513
+ """
514
+ # VLM processors don't have parse_response directly; use the inner tokenizer
515
+ tokenizer = getattr(tokenizer_or_processor, "tokenizer", tokenizer_or_processor)
516
+ try:
517
+ parsed = tokenizer.parse_response(ids)
518
+ # Hotfix: remove incorrectly appended EOS token from tool calls
519
+ # See https://github.com/huggingface/transformers/issues/42249
520
+ if isinstance(parsed.get("content"), str):
521
+ parsed["content"] = parsed["content"].removesuffix(tokenizer.eos_token)
522
+ # Normalize: ensure content is always a string (some models omit it or set it to None)
523
+ if not parsed.get("content"):
524
+ parsed["content"] = ""
525
+ # Validate tool_calls to prevent Jinja2 Undefined errors when fields are missing
526
+ if "tool_calls" in parsed:
527
+ _validate_tool_calls(parsed["tool_calls"])
528
+ except (ValueError, TypeError):
529
+ # Fallback: decode as plain text if parsing fails. This happens if the model outputs malformed tool calls.
530
+ content = tokenizer.decode(ids, skip_special_tokens=True)
531
+ parsed = {"role": "assistant", "content": content}
532
+ return parsed
tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/README.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Chat Templates
2
+
3
+ Jinja2 chat templates stored here serve two purposes:
4
+
5
+ 1. **Identity comparison**: detecting which model is being used (by comparing `tokenizer.chat_template` against known templates) to add the appropriate response schema (`add_response_schema`) or swap in a training template (`get_training_chat_template`).
6
+ 2. **Training patches**: modified templates that fix training-specific issues (prefix-preservation for GRPO, `{% generation %}` markers for SFT assistant-only loss).
7
+
8
+ **Why prefix-preserving?** The GRPO tool call loop extracts tool response formatting tokens by comparing tokenizations with and without tool messages appended (`_get_tool_suffix_ids`). This requires the chat template to be *prefix-preserving*: appending messages must not change how earlier messages are rendered.
9
+
10
+ **Why generation-tagged?** SFT with `assistant_only_loss=True` requires the chat template to include `{% generation %}` / `{% endgeneration %}` markers around assistant output, so `return_assistant_tokens_mask=True` can produce correct masks. Most model templates don't include these markers natively.
11
+
12
+ ## Original templates
13
+
14
+ Used for identity comparison only.
15
+
16
+ ### `gptoss.jinja`
17
+
18
+ Original GPT-OSS chat template.
19
+
20
+ ### `qwen3.jinja`
21
+
22
+ Original Qwen3 chat template.
23
+
24
+ ### `qwen3_5_2b_and_below.jinja` / `qwen3_5_4b_and_above.jinja`
25
+
26
+ Original Qwen3.5 chat templates.
27
+
28
+ ## Training templates
29
+
30
+ Patched templates that fix training-specific issues. Swapped in at init when tools are enabled (GRPO) or when `assistant_only_loss=True` (SFT).
31
+
32
+ ### `qwen3_training.jinja`
33
+
34
+ Patched Qwen3 template. Diff vs `qwen3.jinja`:
35
+
36
+ Require both `<think>` and `</think>` to be present before parsing, to avoid incorrect splitting when the model generates only one tag:
37
+
38
+ ```diff
39
+ - {%- if '</think>' in content %}
40
+ + {%- if '<think>' in content and '</think>' in content %}
41
+ ```
42
+
43
+ Always include the thinking block regardless of message position. The original conditionally omits it based on `loop.last`, which changes the assistant rendering when a tool message is appended — breaking prefix-preservation:
44
+
45
+ ```diff
46
+ - {%- if loop.index0 > ns.last_query_index %}
47
+ - {%- if loop.last or (not loop.last and reasoning_content) %}
48
+ - {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
49
+ - {%- else %}
50
+ - {{- '<|im_start|>' + message.role + '\n' + content }}
51
+ - {%- endif %}
52
+ - {%- else %}
53
+ - {{- '<|im_start|>' + message.role + '\n' + content }}
54
+ - {%- endif %}
55
+ + {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
56
+ ```
57
+
58
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
59
+
60
+ ### `gptoss_training.jinja`
61
+
62
+ Patched GPT-OSS template. Diff vs `gptoss.jinja`:
63
+
64
+ Wrap assistant message output with `{% generation %}` / `{% endgeneration %}` so that
65
+ `return_assistant_tokens_mask=True` produces correct masks for SFT assistant-only loss.
tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/gptoss.jinja ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#-
2
+ In addition to the normal inputs of `messages` and `tools`, this template also accepts the
3
+ following kwargs:
4
+ - "builtin_tools": A list, can contain "browser" and/or "python".
5
+ - "model_identity": A string that optionally describes the model identity.
6
+ - "reasoning_effort": A string that describes the reasoning effort, defaults to "medium".
7
+ #}
8
+
9
+ {#- Tool Definition Rendering ============================================== #}
10
+ {%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%}
11
+ {%- if param_spec.type == "array" -%}
12
+ {%- if param_spec['items'] -%}
13
+ {%- if param_spec['items']['type'] == "string" -%}
14
+ {{- "string[]" }}
15
+ {%- elif param_spec['items']['type'] == "number" -%}
16
+ {{- "number[]" }}
17
+ {%- elif param_spec['items']['type'] == "integer" -%}
18
+ {{- "number[]" }}
19
+ {%- elif param_spec['items']['type'] == "boolean" -%}
20
+ {{- "boolean[]" }}
21
+ {%- else -%}
22
+ {%- set inner_type = render_typescript_type(param_spec['items'], required_params) -%}
23
+ {%- if inner_type == "object | object" or inner_type|length > 50 -%}
24
+ {{- "any[]" }}
25
+ {%- else -%}
26
+ {{- inner_type + "[]" }}
27
+ {%- endif -%}
28
+ {%- endif -%}
29
+ {%- if param_spec.nullable -%}
30
+ {{- " | null" }}
31
+ {%- endif -%}
32
+ {%- else -%}
33
+ {{- "any[]" }}
34
+ {%- if param_spec.nullable -%}
35
+ {{- " | null" }}
36
+ {%- endif -%}
37
+ {%- endif -%}
38
+ {%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is defined -%}
39
+ {#- Handle array of types like ["object", "object"] from Union[dict, list] #}
40
+ {%- if param_spec.type | length > 1 -%}
41
+ {{- param_spec.type | join(" | ") }}
42
+ {%- else -%}
43
+ {{- param_spec.type[0] }}
44
+ {%- endif -%}
45
+ {%- elif param_spec.oneOf -%}
46
+ {#- Handle oneOf schemas - check for complex unions and fallback to any #}
47
+ {%- set has_object_variants = false -%}
48
+ {%- for variant in param_spec.oneOf -%}
49
+ {%- if variant.type == "object" -%}
50
+ {%- set has_object_variants = true -%}
51
+ {%- endif -%}
52
+ {%- endfor -%}
53
+ {%- if has_object_variants and param_spec.oneOf|length > 1 -%}
54
+ {{- "any" }}
55
+ {%- else -%}
56
+ {%- for variant in param_spec.oneOf -%}
57
+ {{- render_typescript_type(variant, required_params) -}}
58
+ {%- if variant.description %}
59
+ {{- "// " + variant.description }}
60
+ {%- endif -%}
61
+ {%- if variant.default is defined %}
62
+ {{ "// default: " + variant.default|tojson }}
63
+ {%- endif -%}
64
+ {%- if not loop.last %}
65
+ {{- " | " }}
66
+ {% endif -%}
67
+ {%- endfor -%}
68
+ {%- endif -%}
69
+ {%- elif param_spec.type == "string" -%}
70
+ {%- if param_spec.enum -%}
71
+ {{- '"' + param_spec.enum|join('" | "') + '"' -}}
72
+ {%- else -%}
73
+ {{- "string" }}
74
+ {%- if param_spec.nullable %}
75
+ {{- " | null" }}
76
+ {%- endif -%}
77
+ {%- endif -%}
78
+ {%- elif param_spec.type == "number" -%}
79
+ {{- "number" }}
80
+ {%- elif param_spec.type == "integer" -%}
81
+ {{- "number" }}
82
+ {%- elif param_spec.type == "boolean" -%}
83
+ {{- "boolean" }}
84
+
85
+ {%- elif param_spec.type == "object" -%}
86
+ {%- if param_spec.properties -%}
87
+ {{- "{\n" }}
88
+ {%- for prop_name, prop_spec in param_spec.properties.items() -%}
89
+ {{- prop_name -}}
90
+ {%- if prop_name not in (param_spec.required or []) -%}
91
+ {{- "?" }}
92
+ {%- endif -%}
93
+ {{- ": " }}
94
+ {{ render_typescript_type(prop_spec, param_spec.required or []) }}
95
+ {%- if not loop.last -%}
96
+ {{-", " }}
97
+ {%- endif -%}
98
+ {%- endfor -%}
99
+ {{- "}" }}
100
+ {%- else -%}
101
+ {{- "object" }}
102
+ {%- endif -%}
103
+ {%- else -%}
104
+ {{- "any" }}
105
+ {%- endif -%}
106
+ {%- endmacro -%}
107
+
108
+ {%- macro render_tool_namespace(namespace_name, tools) -%}
109
+ {{- "## " + namespace_name + "\n\n" }}
110
+ {{- "namespace " + namespace_name + " {\n\n" }}
111
+ {%- for tool in tools %}
112
+ {%- set tool = tool.function %}
113
+ {{- "// " + tool.description + "\n" }}
114
+ {{- "type "+ tool.name + " = " }}
115
+ {%- if tool.parameters and tool.parameters.properties %}
116
+ {{- "(_: {\n" }}
117
+ {%- for param_name, param_spec in tool.parameters.properties.items() %}
118
+ {%- if param_spec.description %}
119
+ {{- "// " + param_spec.description + "\n" }}
120
+ {%- endif %}
121
+ {{- param_name }}
122
+ {%- if param_name not in (tool.parameters.required or []) -%}
123
+ {{- "?" }}
124
+ {%- endif -%}
125
+ {{- ": " }}
126
+ {{- render_typescript_type(param_spec, tool.parameters.required or []) }}
127
+ {%- if param_spec.default is defined -%}
128
+ {%- if param_spec.enum %}
129
+ {{- ", // default: " + param_spec.default }}
130
+ {%- elif param_spec.oneOf %}
131
+ {{- "// default: " + param_spec.default }}
132
+ {%- else %}
133
+ {{- ", // default: " + param_spec.default|tojson }}
134
+ {%- endif -%}
135
+ {%- endif -%}
136
+ {%- if not loop.last %}
137
+ {{- ",\n" }}
138
+ {%- else %}
139
+ {{- ",\n" }}
140
+ {%- endif -%}
141
+ {%- endfor %}
142
+ {{- "}) => any;\n\n" }}
143
+ {%- else -%}
144
+ {{- "() => any;\n\n" }}
145
+ {%- endif -%}
146
+ {%- endfor %}
147
+ {{- "} // namespace " + namespace_name }}
148
+ {%- endmacro -%}
149
+
150
+ {%- macro render_builtin_tools(browser_tool, python_tool) -%}
151
+ {%- if browser_tool %}
152
+ {{- "## browser\n\n" }}
153
+ {{- "// Tool for browsing.\n" }}
154
+ {{- "// The `cursor` appears in brackets before each browsing display: `[{cursor}]`.\n" }}
155
+ {{- "// Cite information from the tool using the following format:\n" }}
156
+ {{- "// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`.\n" }}
157
+ {{- "// Do not quote more than 10 words directly from the tool output.\n" }}
158
+ {{- "// sources=web (default: web)\n" }}
159
+ {{- "namespace browser {\n\n" }}
160
+ {{- "// Searches for information related to `query` and displays `topn` results.\n" }}
161
+ {{- "type search = (_: {\n" }}
162
+ {{- "query: string,\n" }}
163
+ {{- "topn?: number, // default: 10\n" }}
164
+ {{- "source?: string,\n" }}
165
+ {{- "}) => any;\n\n" }}
166
+ {{- "// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines.\n" }}
167
+ {{- "// Valid link ids are displayed with the formatting: `【{id}†.*】`.\n" }}
168
+ {{- "// If `cursor` is not provided, the most recent page is implied.\n" }}
169
+ {{- "// If `id` is a string, it is treated as a fully qualified URL associated with `source`.\n" }}
170
+ {{- "// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available.\n" }}
171
+ {{- "// Use this function without `id` to scroll to a new location of an opened page.\n" }}
172
+ {{- "type open = (_: {\n" }}
173
+ {{- "id?: number | string, // default: -1\n" }}
174
+ {{- "cursor?: number, // default: -1\n" }}
175
+ {{- "loc?: number, // default: -1\n" }}
176
+ {{- "num_lines?: number, // default: -1\n" }}
177
+ {{- "view_source?: boolean, // default: false\n" }}
178
+ {{- "source?: string,\n" }}
179
+ {{- "}) => any;\n\n" }}
180
+ {{- "// Finds exact matches of `pattern` in the current page, or the page given by `cursor`.\n" }}
181
+ {{- "type find = (_: {\n" }}
182
+ {{- "pattern: string,\n" }}
183
+ {{- "cursor?: number, // default: -1\n" }}
184
+ {{- "}) => any;\n\n" }}
185
+ {{- "} // namespace browser\n\n" }}
186
+ {%- endif -%}
187
+
188
+ {%- if python_tool %}
189
+ {{- "## python\n\n" }}
190
+ {{- "Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files).\n\n" }}
191
+ {{- "When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster.\n\n" }}
192
+ {%- endif -%}
193
+ {%- endmacro -%}
194
+
195
+ {#- System Message Construction ============================================ #}
196
+ {%- macro build_system_message() -%}
197
+ {%- if model_identity is not defined %}
198
+ {%- set model_identity = "You are ChatGPT, a large language model trained by OpenAI." %}
199
+ {%- endif %}
200
+ {{- model_identity + "\n" }}
201
+ {{- "Knowledge cutoff: 2024-06\n" }}
202
+ {{- "Current date: " + strftime_now("%Y-%m-%d") + "\n\n" }}
203
+ {%- if reasoning_effort is not defined %}
204
+ {%- set reasoning_effort = "medium" %}
205
+ {%- endif %}
206
+ {{- "Reasoning: " + reasoning_effort + "\n\n" }}
207
+ {%- if builtin_tools %}
208
+ {{- "# Tools\n\n" }}
209
+ {%- set available_builtin_tools = namespace(browser=false, python=false) %}
210
+ {%- for tool in builtin_tools %}
211
+ {%- if tool == "browser" %}
212
+ {%- set available_builtin_tools.browser = true %}
213
+ {%- elif tool == "python" %}
214
+ {%- set available_builtin_tools.python = true %}
215
+ {%- endif %}
216
+ {%- endfor %}
217
+ {{- render_builtin_tools(available_builtin_tools.browser, available_builtin_tools.python) }}
218
+ {%- endif -%}
219
+ {{- "# Valid channels: analysis, commentary, final. Channel must be included for every message." }}
220
+ {%- if tools -%}
221
+ {{- "\nCalls to these tools must go to the commentary channel: 'functions'." }}
222
+ {%- endif -%}
223
+ {%- endmacro -%}
224
+
225
+ {#- Main Template Logic ================================================= #}
226
+ {#- Set defaults #}
227
+
228
+ {#- Render system message #}
229
+ {{- "<|start|>system<|message|>" }}
230
+ {{- build_system_message() }}
231
+ {{- "<|end|>" }}
232
+
233
+ {#- Extract developer message #}
234
+ {%- if messages[0].role == "developer" or messages[0].role == "system" %}
235
+ {%- set developer_message = messages[0].content %}
236
+ {%- set loop_messages = messages[1:] %}
237
+ {%- else %}
238
+ {%- set developer_message = "" %}
239
+ {%- set loop_messages = messages %}
240
+ {%- endif %}
241
+
242
+ {#- Render developer message #}
243
+ {%- if developer_message or tools %}
244
+ {{- "<|start|>developer<|message|>" }}
245
+ {%- if developer_message %}
246
+ {{- "# Instructions\n\n" }}
247
+ {{- developer_message }}
248
+ {{- "\n\n" }}
249
+ {%- endif %}
250
+ {%- if tools -%}
251
+ {{- "# Tools\n\n" }}
252
+ {{- render_tool_namespace("functions", tools) }}
253
+ {%- endif -%}
254
+ {{- "<|end|>" }}
255
+ {%- endif %}
256
+
257
+ {#- Render messages #}
258
+ {%- set last_tool_call = namespace(name=none) %}
259
+ {%- for message in loop_messages -%}
260
+ {#- At this point only assistant/user/tool messages should remain #}
261
+ {%- if message.role == 'assistant' -%}
262
+ {#- Checks to ensure the messages are being passed in the format we expect #}
263
+ {%- if "content" in message %}
264
+ {%- if "<|channel|>analysis<|message|>" in message.content or "<|channel|>final<|message|>" in message.content %}
265
+ {{- raise_exception("You have passed a message containing <|channel|> tags in the content field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }}
266
+ {%- endif %}
267
+ {%- endif %}
268
+ {%- if "thinking" in message %}
269
+ {%- if "<|channel|>analysis<|message|>" in message.thinking or "<|channel|>final<|message|>" in message.thinking %}
270
+ {{- raise_exception("You have passed a message containing <|channel|> tags in the thinking field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }}
271
+ {%- endif %}
272
+ {%- endif %}
273
+ {%- if "tool_calls" in message %}
274
+ {#- We need very careful handling here - we want to drop the tool call analysis message if the model #}
275
+ {#- has output a later <|final|> message, but otherwise we want to retain it. This is the only case #}
276
+ {#- when we render CoT/analysis messages in inference. #}
277
+ {%- set future_final_message = namespace(found=false) %}
278
+ {%- for future_message in loop_messages[loop.index:] %}
279
+ {%- if future_message.role == 'assistant' and "tool_calls" not in future_message %}
280
+ {%- set future_final_message.found = true %}
281
+ {%- endif %}
282
+ {%- endfor %}
283
+ {#- We assume max 1 tool call per message, and so we infer the tool call name #}
284
+ {#- in "tool" messages from the most recent assistant tool call name #}
285
+ {%- set tool_call = message.tool_calls[0] %}
286
+ {%- if tool_call.function %}
287
+ {%- set tool_call = tool_call.function %}
288
+ {%- endif %}
289
+ {%- if message.content and message.thinking %}
290
+ {{- raise_exception("Cannot pass both content and thinking in an assistant message with tool calls! Put the analysis message in one or the other, but not both.") }}
291
+ {%- elif message.content and not future_final_message.found %}
292
+ {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.content + "<|end|>" }}
293
+ {%- elif message.thinking and not future_final_message.found %}
294
+ {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }}
295
+ {%- endif %}
296
+ {{- "<|start|>assistant to=" }}
297
+ {{- "functions." + tool_call.name + "<|channel|>commentary " }}
298
+ {{- (tool_call.content_type if tool_call.content_type is defined else "json") + "<|message|>" }}
299
+ {{- tool_call.arguments|tojson }}
300
+ {{- "<|call|>" }}
301
+ {%- set last_tool_call.name = tool_call.name %}
302
+ {%- elif loop.last and not add_generation_prompt %}
303
+ {#- Only render the CoT if the final turn is an assistant turn and add_generation_prompt is false #}
304
+ {#- This is a situation that should only occur in training, never in inference. #}
305
+ {%- if "thinking" in message %}
306
+ {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }}
307
+ {%- endif %}
308
+ {#- <|return|> indicates the end of generation, but <|end|> does not #}
309
+ {#- <|return|> should never be an input to the model, but we include it as the final token #}
310
+ {#- when training, so the model learns to emit it. #}
311
+ {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|return|>" }}
312
+ {%- else %}
313
+ {#- CoT is dropped during all previous turns, so we never render it for inference #}
314
+ {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|end|>" }}
315
+ {%- set last_tool_call.name = none %}
316
+ {%- endif %}
317
+ {%- elif message.role == 'tool' -%}
318
+ {%- if last_tool_call.name is none %}
319
+ {{- raise_exception("Message has tool role, but there was no previous assistant message with a tool call!") }}
320
+ {%- endif %}
321
+ {{- "<|start|>functions." + last_tool_call.name }}
322
+ {{- " to=assistant<|channel|>commentary<|message|>" + message.content|tojson + "<|end|>" }}
323
+ {%- elif message.role == 'user' -%}
324
+ {{- "<|start|>user<|message|>" + message.content + "<|end|>" }}
325
+ {%- endif -%}
326
+ {%- endfor -%}
327
+
328
+ {#- Generation prompt #}
329
+ {%- if add_generation_prompt -%}
330
+ <|start|>assistant
331
+ {%- endif -%}
tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/gptoss_training.jinja ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#-
2
+ Training variant of the GPT-OSS chat template (see gptoss.jinja for the original).
3
+ Modifications vs the original:
4
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
5
+ assistant-only loss masking in SFT training.
6
+
7
+ In addition to the normal inputs of `messages` and `tools`, this template also accepts the
8
+ following kwargs:
9
+ - "builtin_tools": A list, can contain "browser" and/or "python".
10
+ - "model_identity": A string that optionally describes the model identity.
11
+ - "reasoning_effort": A string that describes the reasoning effort, defaults to "medium".
12
+ #}
13
+
14
+ {#- Tool Definition Rendering ============================================== #}
15
+ {%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%}
16
+ {%- if param_spec.type == "array" -%}
17
+ {%- if param_spec['items'] -%}
18
+ {%- if param_spec['items']['type'] == "string" -%}
19
+ {{- "string[]" }}
20
+ {%- elif param_spec['items']['type'] == "number" -%}
21
+ {{- "number[]" }}
22
+ {%- elif param_spec['items']['type'] == "integer" -%}
23
+ {{- "number[]" }}
24
+ {%- elif param_spec['items']['type'] == "boolean" -%}
25
+ {{- "boolean[]" }}
26
+ {%- else -%}
27
+ {%- set inner_type = render_typescript_type(param_spec['items'], required_params) -%}
28
+ {%- if inner_type == "object | object" or inner_type|length > 50 -%}
29
+ {{- "any[]" }}
30
+ {%- else -%}
31
+ {{- inner_type + "[]" }}
32
+ {%- endif -%}
33
+ {%- endif -%}
34
+ {%- if param_spec.nullable -%}
35
+ {{- " | null" }}
36
+ {%- endif -%}
37
+ {%- else -%}
38
+ {{- "any[]" }}
39
+ {%- if param_spec.nullable -%}
40
+ {{- " | null" }}
41
+ {%- endif -%}
42
+ {%- endif -%}
43
+ {%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is defined -%}
44
+ {#- Handle array of types like ["object", "object"] from Union[dict, list] #}
45
+ {%- if param_spec.type | length > 1 -%}
46
+ {{- param_spec.type | join(" | ") }}
47
+ {%- else -%}
48
+ {{- param_spec.type[0] }}
49
+ {%- endif -%}
50
+ {%- elif param_spec.oneOf -%}
51
+ {#- Handle oneOf schemas - check for complex unions and fallback to any #}
52
+ {%- set has_object_variants = false -%}
53
+ {%- for variant in param_spec.oneOf -%}
54
+ {%- if variant.type == "object" -%}
55
+ {%- set has_object_variants = true -%}
56
+ {%- endif -%}
57
+ {%- endfor -%}
58
+ {%- if has_object_variants and param_spec.oneOf|length > 1 -%}
59
+ {{- "any" }}
60
+ {%- else -%}
61
+ {%- for variant in param_spec.oneOf -%}
62
+ {{- render_typescript_type(variant, required_params) -}}
63
+ {%- if variant.description %}
64
+ {{- "// " + variant.description }}
65
+ {%- endif -%}
66
+ {%- if variant.default is defined %}
67
+ {{ "// default: " + variant.default|tojson }}
68
+ {%- endif -%}
69
+ {%- if not loop.last %}
70
+ {{- " | " }}
71
+ {% endif -%}
72
+ {%- endfor -%}
73
+ {%- endif -%}
74
+ {%- elif param_spec.type == "string" -%}
75
+ {%- if param_spec.enum -%}
76
+ {{- '"' + param_spec.enum|join('" | "') + '"' -}}
77
+ {%- else -%}
78
+ {{- "string" }}
79
+ {%- if param_spec.nullable %}
80
+ {{- " | null" }}
81
+ {%- endif -%}
82
+ {%- endif -%}
83
+ {%- elif param_spec.type == "number" -%}
84
+ {{- "number" }}
85
+ {%- elif param_spec.type == "integer" -%}
86
+ {{- "number" }}
87
+ {%- elif param_spec.type == "boolean" -%}
88
+ {{- "boolean" }}
89
+
90
+ {%- elif param_spec.type == "object" -%}
91
+ {%- if param_spec.properties -%}
92
+ {{- "{\n" }}
93
+ {%- for prop_name, prop_spec in param_spec.properties.items() -%}
94
+ {{- prop_name -}}
95
+ {%- if prop_name not in (param_spec.required or []) -%}
96
+ {{- "?" }}
97
+ {%- endif -%}
98
+ {{- ": " }}
99
+ {{ render_typescript_type(prop_spec, param_spec.required or []) }}
100
+ {%- if not loop.last -%}
101
+ {{-", " }}
102
+ {%- endif -%}
103
+ {%- endfor -%}
104
+ {{- "}" }}
105
+ {%- else -%}
106
+ {{- "object" }}
107
+ {%- endif -%}
108
+ {%- else -%}
109
+ {{- "any" }}
110
+ {%- endif -%}
111
+ {%- endmacro -%}
112
+
113
+ {%- macro render_tool_namespace(namespace_name, tools) -%}
114
+ {{- "## " + namespace_name + "\n\n" }}
115
+ {{- "namespace " + namespace_name + " {\n\n" }}
116
+ {%- for tool in tools %}
117
+ {%- set tool = tool.function %}
118
+ {{- "// " + tool.description + "\n" }}
119
+ {{- "type "+ tool.name + " = " }}
120
+ {%- if tool.parameters and tool.parameters.properties %}
121
+ {{- "(_: {\n" }}
122
+ {%- for param_name, param_spec in tool.parameters.properties.items() %}
123
+ {%- if param_spec.description %}
124
+ {{- "// " + param_spec.description + "\n" }}
125
+ {%- endif %}
126
+ {{- param_name }}
127
+ {%- if param_name not in (tool.parameters.required or []) -%}
128
+ {{- "?" }}
129
+ {%- endif -%}
130
+ {{- ": " }}
131
+ {{- render_typescript_type(param_spec, tool.parameters.required or []) }}
132
+ {%- if param_spec.default is defined -%}
133
+ {%- if param_spec.enum %}
134
+ {{- ", // default: " + param_spec.default }}
135
+ {%- elif param_spec.oneOf %}
136
+ {{- "// default: " + param_spec.default }}
137
+ {%- else %}
138
+ {{- ", // default: " + param_spec.default|tojson }}
139
+ {%- endif -%}
140
+ {%- endif -%}
141
+ {%- if not loop.last %}
142
+ {{- ",\n" }}
143
+ {%- else %}
144
+ {{- ",\n" }}
145
+ {%- endif -%}
146
+ {%- endfor %}
147
+ {{- "}) => any;\n\n" }}
148
+ {%- else -%}
149
+ {{- "() => any;\n\n" }}
150
+ {%- endif -%}
151
+ {%- endfor %}
152
+ {{- "} // namespace " + namespace_name }}
153
+ {%- endmacro -%}
154
+
155
+ {%- macro render_builtin_tools(browser_tool, python_tool) -%}
156
+ {%- if browser_tool %}
157
+ {{- "## browser\n\n" }}
158
+ {{- "// Tool for browsing.\n" }}
159
+ {{- "// The `cursor` appears in brackets before each browsing display: `[{cursor}]`.\n" }}
160
+ {{- "// Cite information from the tool using the following format:\n" }}
161
+ {{- "// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`.\n" }}
162
+ {{- "// Do not quote more than 10 words directly from the tool output.\n" }}
163
+ {{- "// sources=web (default: web)\n" }}
164
+ {{- "namespace browser {\n\n" }}
165
+ {{- "// Searches for information related to `query` and displays `topn` results.\n" }}
166
+ {{- "type search = (_: {\n" }}
167
+ {{- "query: string,\n" }}
168
+ {{- "topn?: number, // default: 10\n" }}
169
+ {{- "source?: string,\n" }}
170
+ {{- "}) => any;\n\n" }}
171
+ {{- "// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines.\n" }}
172
+ {{- "// Valid link ids are displayed with the formatting: `【{id}†.*】`.\n" }}
173
+ {{- "// If `cursor` is not provided, the most recent page is implied.\n" }}
174
+ {{- "// If `id` is a string, it is treated as a fully qualified URL associated with `source`.\n" }}
175
+ {{- "// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available.\n" }}
176
+ {{- "// Use this function without `id` to scroll to a new location of an opened page.\n" }}
177
+ {{- "type open = (_: {\n" }}
178
+ {{- "id?: number | string, // default: -1\n" }}
179
+ {{- "cursor?: number, // default: -1\n" }}
180
+ {{- "loc?: number, // default: -1\n" }}
181
+ {{- "num_lines?: number, // default: -1\n" }}
182
+ {{- "view_source?: boolean, // default: false\n" }}
183
+ {{- "source?: string,\n" }}
184
+ {{- "}) => any;\n\n" }}
185
+ {{- "// Finds exact matches of `pattern` in the current page, or the page given by `cursor`.\n" }}
186
+ {{- "type find = (_: {\n" }}
187
+ {{- "pattern: string,\n" }}
188
+ {{- "cursor?: number, // default: -1\n" }}
189
+ {{- "}) => any;\n\n" }}
190
+ {{- "} // namespace browser\n\n" }}
191
+ {%- endif -%}
192
+
193
+ {%- if python_tool %}
194
+ {{- "## python\n\n" }}
195
+ {{- "Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files).\n\n" }}
196
+ {{- "When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster.\n\n" }}
197
+ {%- endif -%}
198
+ {%- endmacro -%}
199
+
200
+ {#- System Message Construction ============================================ #}
201
+ {%- macro build_system_message() -%}
202
+ {%- if model_identity is not defined %}
203
+ {%- set model_identity = "You are ChatGPT, a large language model trained by OpenAI." %}
204
+ {%- endif %}
205
+ {{- model_identity + "\n" }}
206
+ {{- "Knowledge cutoff: 2024-06\n" }}
207
+ {{- "Current date: " + strftime_now("%Y-%m-%d") + "\n\n" }}
208
+ {%- if reasoning_effort is not defined %}
209
+ {%- set reasoning_effort = "medium" %}
210
+ {%- endif %}
211
+ {{- "Reasoning: " + reasoning_effort + "\n\n" }}
212
+ {%- if builtin_tools %}
213
+ {{- "# Tools\n\n" }}
214
+ {%- set available_builtin_tools = namespace(browser=false, python=false) %}
215
+ {%- for tool in builtin_tools %}
216
+ {%- if tool == "browser" %}
217
+ {%- set available_builtin_tools.browser = true %}
218
+ {%- elif tool == "python" %}
219
+ {%- set available_builtin_tools.python = true %}
220
+ {%- endif %}
221
+ {%- endfor %}
222
+ {{- render_builtin_tools(available_builtin_tools.browser, available_builtin_tools.python) }}
223
+ {%- endif -%}
224
+ {{- "# Valid channels: analysis, commentary, final. Channel must be included for every message." }}
225
+ {%- if tools -%}
226
+ {{- "\nCalls to these tools must go to the commentary channel: 'functions'." }}
227
+ {%- endif -%}
228
+ {%- endmacro -%}
229
+
230
+ {#- Main Template Logic ================================================= #}
231
+ {#- Set defaults #}
232
+
233
+ {#- Render system message #}
234
+ {{- "<|start|>system<|message|>" }}
235
+ {{- build_system_message() }}
236
+ {{- "<|end|>" }}
237
+
238
+ {#- Extract developer message #}
239
+ {%- if messages[0].role == "developer" or messages[0].role == "system" %}
240
+ {%- set developer_message = messages[0].content %}
241
+ {%- set loop_messages = messages[1:] %}
242
+ {%- else %}
243
+ {%- set developer_message = "" %}
244
+ {%- set loop_messages = messages %}
245
+ {%- endif %}
246
+
247
+ {#- Render developer message #}
248
+ {%- if developer_message or tools %}
249
+ {{- "<|start|>developer<|message|>" }}
250
+ {%- if developer_message %}
251
+ {{- "# Instructions\n\n" }}
252
+ {{- developer_message }}
253
+ {{- "\n\n" }}
254
+ {%- endif %}
255
+ {%- if tools -%}
256
+ {{- "# Tools\n\n" }}
257
+ {{- render_tool_namespace("functions", tools) }}
258
+ {%- endif -%}
259
+ {{- "<|end|>" }}
260
+ {%- endif %}
261
+
262
+ {#- Render messages #}
263
+ {%- set last_tool_call = namespace(name=none) %}
264
+ {%- for message in loop_messages -%}
265
+ {#- At this point only assistant/user/tool messages should remain #}
266
+ {%- if message.role == 'assistant' -%}
267
+ {#- Checks to ensure the messages are being passed in the format we expect #}
268
+ {%- if "content" in message %}
269
+ {%- if "<|channel|>analysis<|message|>" in message.content or "<|channel|>final<|message|>" in message.content %}
270
+ {{- raise_exception("You have passed a message containing <|channel|> tags in the content field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }}
271
+ {%- endif %}
272
+ {%- endif %}
273
+ {%- if "thinking" in message %}
274
+ {%- if "<|channel|>analysis<|message|>" in message.thinking or "<|channel|>final<|message|>" in message.thinking %}
275
+ {{- raise_exception("You have passed a message containing <|channel|> tags in the thinking field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }}
276
+ {%- endif %}
277
+ {%- endif %}
278
+ {%- generation %}
279
+ {%- if "tool_calls" in message %}
280
+ {#- We need very careful handling here - we want to drop the tool call analysis message if the model #}
281
+ {#- has output a later <|final|> message, but otherwise we want to retain it. This is the only case #}
282
+ {#- when we render CoT/analysis messages in inference. #}
283
+ {%- set future_final_message = namespace(found=false) %}
284
+ {%- for future_message in loop_messages[loop.index:] %}
285
+ {%- if future_message.role == 'assistant' and "tool_calls" not in future_message %}
286
+ {%- set future_final_message.found = true %}
287
+ {%- endif %}
288
+ {%- endfor %}
289
+ {#- We assume max 1 tool call per message, and so we infer the tool call name #}
290
+ {#- in "tool" messages from the most recent assistant tool call name #}
291
+ {%- set tool_call = message.tool_calls[0] %}
292
+ {%- if tool_call.function %}
293
+ {%- set tool_call = tool_call.function %}
294
+ {%- endif %}
295
+ {%- if message.content and message.thinking %}
296
+ {{- raise_exception("Cannot pass both content and thinking in an assistant message with tool calls! Put the analysis message in one or the other, but not both.") }}
297
+ {%- elif message.content and not future_final_message.found %}
298
+ {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.content + "<|end|>" }}
299
+ {%- elif message.thinking and not future_final_message.found %}
300
+ {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }}
301
+ {%- endif %}
302
+ {{- "<|start|>assistant to=" }}
303
+ {{- "functions." + tool_call.name + "<|channel|>commentary " }}
304
+ {{- (tool_call.content_type if tool_call.content_type is defined else "json") + "<|message|>" }}
305
+ {{- tool_call.arguments|tojson }}
306
+ {{- "<|call|>" }}
307
+ {%- set last_tool_call.name = tool_call.name %}
308
+ {%- elif loop.last and not add_generation_prompt %}
309
+ {#- Only render the CoT if the final turn is an assistant turn and add_generation_prompt is false #}
310
+ {#- This is a situation that should only occur in training, never in inference. #}
311
+ {%- if "thinking" in message %}
312
+ {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }}
313
+ {%- endif %}
314
+ {#- <|return|> indicates the end of generation, but <|end|> does not #}
315
+ {#- <|return|> should never be an input to the model, but we include it as the final token #}
316
+ {#- when training, so the model learns to emit it. #}
317
+ {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|return|>" }}
318
+ {%- else %}
319
+ {#- CoT is dropped during all previous turns, so we never render it for inference #}
320
+ {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|end|>" }}
321
+ {%- set last_tool_call.name = none %}
322
+ {%- endif %}
323
+ {%- endgeneration %}
324
+ {%- elif message.role == 'tool' -%}
325
+ {%- if last_tool_call.name is none %}
326
+ {{- raise_exception("Message has tool role, but there was no previous assistant message with a tool call!") }}
327
+ {%- endif %}
328
+ {{- "<|start|>functions." + last_tool_call.name }}
329
+ {{- " to=assistant<|channel|>commentary<|message|>" + message.content|tojson + "<|end|>" }}
330
+ {%- elif message.role == 'user' -%}
331
+ {{- "<|start|>user<|message|>" + message.content + "<|end|>" }}
332
+ {%- endif -%}
333
+ {%- endfor -%}
334
+
335
+ {#- Generation prompt #}
336
+ {%- if add_generation_prompt -%}
337
+ <|start|>assistant
338
+ {%- endif -%}
tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/qwen3.jinja ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {%- set reasoning_content = '' %}
35
+ {%- if message.reasoning_content is string %}
36
+ {%- set reasoning_content = message.reasoning_content %}
37
+ {%- else %}
38
+ {%- if '</think>' in content %}
39
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
40
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
41
+ {%- endif %}
42
+ {%- endif %}
43
+ {%- if loop.index0 > ns.last_query_index %}
44
+ {%- if loop.last or (not loop.last and reasoning_content) %}
45
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
46
+ {%- else %}
47
+ {{- '<|im_start|>' + message.role + '\n' + content }}
48
+ {%- endif %}
49
+ {%- else %}
50
+ {{- '<|im_start|>' + message.role + '\n' + content }}
51
+ {%- endif %}
52
+ {%- if message.tool_calls %}
53
+ {%- for tool_call in message.tool_calls %}
54
+ {%- if (loop.first and content) or (not loop.first) %}
55
+ {{- '\n' }}
56
+ {%- endif %}
57
+ {%- if tool_call.function %}
58
+ {%- set tool_call = tool_call.function %}
59
+ {%- endif %}
60
+ {{- '<tool_call>\n{"name": "' }}
61
+ {{- tool_call.name }}
62
+ {{- '", "arguments": ' }}
63
+ {%- if tool_call.arguments is string %}
64
+ {{- tool_call.arguments }}
65
+ {%- else %}
66
+ {{- tool_call.arguments | tojson }}
67
+ {%- endif %}
68
+ {{- '}\n</tool_call>' }}
69
+ {%- endfor %}
70
+ {%- endif %}
71
+ {{- '<|im_end|>\n' }}
72
+ {%- elif message.role == "tool" %}
73
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
74
+ {{- '<|im_start|>user' }}
75
+ {%- endif %}
76
+ {{- '\n<tool_response>\n' }}
77
+ {{- content }}
78
+ {{- '\n</tool_response>' }}
79
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
80
+ {{- '<|im_end|>\n' }}
81
+ {%- endif %}
82
+ {%- endif %}
83
+ {%- endfor %}
84
+ {%- if add_generation_prompt %}
85
+ {{- '<|im_start|>assistant\n' }}
86
+ {%- if enable_thinking is defined and enable_thinking is false %}
87
+ {{- '<think>\n\n</think>\n\n' }}
88
+ {%- endif %}
89
+ {%- endif %}
tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/qwen3_5_2b_and_below.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if loop.index0 > ns.last_query_index %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is true %}
150
+ {{- '<think>\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n\n</think>\n\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/qwen3_5_4b_and_above.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if loop.index0 > ns.last_query_index %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is false %}
150
+ {{- '<think>\n\n</think>\n\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
tasks/tasksmith-0ea2241cceeb/environment/source/trl/chat_templates/qwen3_training.jinja ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Qwen3 chat template (see qwen3.jinja for the original).
2
+ Modifications vs the original:
3
+ - {%- if '</think>' in content %} → {%- if '<think>' in content and '</think>' in content %}
4
+ Always check for both tags to avoid edge cases where the model generates only one tag.
5
+ - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block.
6
+ This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition.
7
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
8
+ assistant-only loss masking in SFT training.
9
+ -#}
10
+ {%- if tools %}
11
+ {{- '<|im_start|>system\n' }}
12
+ {%- if messages[0].role == 'system' %}
13
+ {{- messages[0].content + '\n\n' }}
14
+ {%- endif %}
15
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
16
+ {%- for tool in tools %}
17
+ {{- "\n" }}
18
+ {{- tool | tojson }}
19
+ {%- endfor %}
20
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
21
+ {%- else %}
22
+ {%- if messages[0].role == 'system' %}
23
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
24
+ {%- endif %}
25
+ {%- endif %}
26
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
27
+ {%- for message in messages[::-1] %}
28
+ {%- set index = (messages|length - 1) - loop.index0 %}
29
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
30
+ {%- set ns.multi_step_tool = false %}
31
+ {%- set ns.last_query_index = index %}
32
+ {%- endif %}
33
+ {%- endfor %}
34
+ {%- for message in messages %}
35
+ {%- if message.content is string %}
36
+ {%- set content = message.content %}
37
+ {%- else %}
38
+ {%- set content = '' %}
39
+ {%- endif %}
40
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
41
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
42
+ {%- elif message.role == "assistant" %}
43
+ {%- set reasoning_content = '' %}
44
+ {%- if message.reasoning_content is string %}
45
+ {%- set reasoning_content = message.reasoning_content %}
46
+ {%- else %}
47
+ {%- if '<think>' in content and '</think>' in content %}
48
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
49
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
50
+ {%- endif %}
51
+ {%- endif %}
52
+ {{- '<|im_start|>' + message.role + '\n' }}
53
+ {%- generation %}
54
+ {{- '<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
55
+ {%- if message.tool_calls %}
56
+ {%- for tool_call in message.tool_calls %}
57
+ {%- if (loop.first and content) or (not loop.first) %}
58
+ {{- '\n' }}
59
+ {%- endif %}
60
+ {%- if tool_call.function %}
61
+ {%- set tool_call = tool_call.function %}
62
+ {%- endif %}
63
+ {{- '<tool_call>\n{"name": "' }}
64
+ {{- tool_call.name }}
65
+ {{- '", "arguments": ' }}
66
+ {%- if tool_call.arguments is string %}
67
+ {{- tool_call.arguments }}
68
+ {%- else %}
69
+ {{- tool_call.arguments | tojson }}
70
+ {%- endif %}
71
+ {{- '}\n</tool_call>' }}
72
+ {%- endfor %}
73
+ {%- endif %}
74
+ {{- '<|im_end|>\n' }}
75
+ {%- endgeneration %}
76
+ {%- elif message.role == "tool" %}
77
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
78
+ {{- '<|im_start|>user' }}
79
+ {%- endif %}
80
+ {{- '\n<tool_response>\n' }}
81
+ {{- content }}
82
+ {{- '\n</tool_response>' }}
83
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
84
+ {{- '<|im_end|>\n' }}
85
+ {%- endif %}
86
+ {%- endif %}
87
+ {%- endfor %}
88
+ {%- if add_generation_prompt %}
89
+ {{- '<|im_start|>assistant\n' }}
90
+ {%- if enable_thinking is defined and enable_thinking is false %}
91
+ {{- '<think>\n\n</think>\n\n' }}
92
+ {%- endif %}
93
+ {%- endif %}
tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .main import main
16
+
17
+
18
+ __all__ = ["main"]
tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/accelerate_config.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.resources as resources
16
+ from pathlib import Path
17
+
18
+
19
+ def resolve_accelerate_config_argument(launch_args: list[str]) -> list[str]:
20
+ """
21
+ Resolve `--accelerate_config` from CLI arguments into `accelerate --config_file`.
22
+
23
+ The function supports either a filesystem path or a predefined config name shipped in `trl/accelerate_configs`
24
+ (without the `.yaml` suffix).
25
+ """
26
+ if "--accelerate_config" not in launch_args:
27
+ return launch_args
28
+
29
+ config_index = launch_args.index("--accelerate_config")
30
+ if config_index + 1 >= len(launch_args):
31
+ raise ValueError("Expected a value after `--accelerate_config`.")
32
+
33
+ config_name = launch_args[config_index + 1]
34
+ if Path(config_name).is_file():
35
+ accelerate_config_path = config_name
36
+ else:
37
+ candidate = resources.files("trl.accelerate_configs").joinpath(f"{config_name}.yaml")
38
+ if not candidate.exists():
39
+ raise ValueError(
40
+ f"Accelerate config {config_name} is neither a file nor a valid config in the `trl` package. "
41
+ "Please provide a valid config name or a path to a config file."
42
+ )
43
+ accelerate_config_path = candidate
44
+
45
+ # Remove '--accelerate_config <value>'.
46
+ launch_args = launch_args[:config_index] + launch_args[config_index + 2 :]
47
+ return ["--config_file", str(accelerate_config_path)] + launch_args
tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/accelerate_launcher.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.resources as resources
16
+ from collections.abc import Callable
17
+ from typing import Any
18
+
19
+ from accelerate.commands.launch import launch_command, launch_command_parser
20
+
21
+
22
+ def launch_training_script(
23
+ script_name: str,
24
+ launch_args: list[str],
25
+ training_script_args: list[str],
26
+ *,
27
+ launch_command_fn: Callable[[Any], None] = launch_command,
28
+ launch_parser_fn: Callable[[], Any] = launch_command_parser,
29
+ ) -> None:
30
+ """
31
+ Launch a TRL training script through `accelerate launch`.
32
+
33
+ Parameters:
34
+ script_name (`str`):
35
+ Script filename in `trl/scripts`, e.g. `"dpo.py"`.
36
+ launch_args (`list[str]`):
37
+ Arguments consumed by `accelerate launch`.
38
+ training_script_args (`list[str]`):
39
+ Arguments forwarded to the training script.
40
+ launch_command_fn (`Callable[[Any], None]`, *optional*):
41
+ Function used to execute accelerate launch.
42
+ launch_parser_fn (`Callable[[], Any]`, *optional*):
43
+ Factory creating the accelerate launch parser.
44
+ """
45
+ training_script = resources.files("trl.scripts").joinpath(script_name)
46
+ accelerate_args = launch_parser_fn().parse_args(launch_args + [str(training_script)] + training_script_args)
47
+ launch_command_fn(accelerate_args)
tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/commands/__init__.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .base import Command
16
+ from .env import EnvCommand
17
+ from .skills import SkillsCommand
18
+ from .training import TrainingCommand
19
+ from .vllm_serve import VllmServeCommand
20
+
21
+
22
+ def get_commands() -> list[Command]:
23
+ """Return all registered top-level TRL CLI commands."""
24
+ return [
25
+ TrainingCommand("dpo"),
26
+ EnvCommand(),
27
+ TrainingCommand("grpo"),
28
+ TrainingCommand("kto"),
29
+ TrainingCommand("reward"),
30
+ TrainingCommand("rloo"),
31
+ TrainingCommand("sft"),
32
+ SkillsCommand(),
33
+ VllmServeCommand(),
34
+ ]
35
+
36
+
37
+ __all__ = ["Command", "get_commands"]
tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/commands/base.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 abc import ABC, abstractmethod
16
+ from argparse import Namespace
17
+ from dataclasses import dataclass
18
+
19
+
20
+ @dataclass(slots=True)
21
+ class CommandContext:
22
+ """Context shared by CLI commands during execution."""
23
+
24
+ argv: list[str]
25
+
26
+ def argv_after(self, token: str) -> list[str]:
27
+ """
28
+ Return CLI tokens after the first occurrence of `token`.
29
+
30
+ Parameters:
31
+ token (`str`):
32
+ Subcommand name as it appears in `argv`.
33
+ """
34
+ try:
35
+ index = self.argv.index(token)
36
+ except ValueError:
37
+ return []
38
+ return self.argv[index + 1 :]
39
+
40
+
41
+ class Command(ABC):
42
+ """
43
+ Base command definition for the TRL CLI.
44
+
45
+ Parameters:
46
+ name (`str`):
47
+ Subcommand name exposed by the CLI.
48
+ help_text (`str`):
49
+ Short description displayed in help output.
50
+ """
51
+
52
+ def __init__(self, name: str, help_text: str):
53
+ self.name = name
54
+ self.help_text = help_text
55
+
56
+ @abstractmethod
57
+ def register(self, subparsers) -> None:
58
+ """Register this command parser in the subparser collection."""
59
+
60
+ @abstractmethod
61
+ def run(self, args: Namespace, context: CommandContext) -> int:
62
+ """Execute the command."""
tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/commands/env.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse import Namespace
16
+
17
+ from .base import Command, CommandContext
18
+
19
+
20
+ class EnvCommand(Command):
21
+ """CLI command that prints TRL environment information."""
22
+
23
+ def __init__(self):
24
+ super().__init__(name="env", help_text="Print the environment information")
25
+
26
+ def register(self, subparsers) -> None:
27
+ subparsers.add_parser(self.name, help=self.help_text)
28
+
29
+ def run(self, args: Namespace, context: CommandContext) -> int:
30
+ from ...scripts.env import print_env
31
+
32
+ print_env()
33
+ return 0
tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/commands/skills.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse import Namespace
16
+
17
+ from ...skills.cli import add_skills_subcommands
18
+ from .base import Command, CommandContext
19
+
20
+
21
+ class SkillsCommand(Command):
22
+ """CLI command that manages TRL agent skills."""
23
+
24
+ def __init__(self):
25
+ super().__init__(name="skills", help_text="Manage TRL agent skills")
26
+ self._skills_parser = None
27
+
28
+ def register(self, subparsers) -> None:
29
+ self._skills_parser = subparsers.add_parser(self.name, help=self.help_text)
30
+ skills_subparsers = self._skills_parser.add_subparsers(dest="skills_command", help="Skills commands")
31
+ add_skills_subcommands(skills_subparsers)
32
+
33
+ def run(self, args: Namespace, context: CommandContext) -> int:
34
+ if getattr(args, "skills_command", None):
35
+ if hasattr(args, "func"):
36
+ return args.func(args)
37
+ print("Error: Unknown skills command")
38
+ return 1
39
+
40
+ if self._skills_parser is not None:
41
+ self._skills_parser.print_help()
42
+ return 0
tasks/tasksmith-0ea2241cceeb/environment/source/trl/cli/commands/training.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from argparse import Namespace
17
+
18
+ from .base import Command, CommandContext
19
+
20
+
21
+ def _subtract_subsequence(lst: list[str], subseq: list[str]) -> list[str]:
22
+ """Return lst with the ordered subsequence subseq removed."""
23
+ sub_iter = iter(subseq)
24
+ current = next(sub_iter, None)
25
+ result = []
26
+ for item in lst:
27
+ if current is not None and item == current:
28
+ current = next(sub_iter, None)
29
+ else:
30
+ result.append(item)
31
+ return result
32
+
33
+
34
+ class TrainingCommand(Command):
35
+ """
36
+ Generic CLI command that launches a training script with accelerate.
37
+
38
+ The script `trl/scripts/<name>.py` must expose a `make_parser()` function.
39
+
40
+ Parameters:
41
+ name (`str`):
42
+ CLI subcommand name (e.g. `"dpo"`).
43
+ """
44
+
45
+ def __init__(self, name: str):
46
+ super().__init__(name=name, help_text=f"Run the {name} training script")
47
+
48
+ def register(self, subparsers) -> None:
49
+ subparsers.add_parser(self.name, help=self.help_text, add_help=False)
50
+
51
+ def run(self, args: Namespace, context: CommandContext) -> int:
52
+ from ..accelerate_config import resolve_accelerate_config_argument
53
+ from ..accelerate_launcher import launch_training_script
54
+
55
+ module = importlib.import_module(f"...scripts.{self.name}", package=__package__)
56
+ all_args = context.argv_after(self.name)
57
+ parser = module.make_parser(prog=f"trl {self.name}")
58
+
59
+ # Handles -h (exits). Returns config_remaining and cli_remaining separately.
60
+ # cli_remaining is an ordered subsequence of all_args; config_remaining is not.
61
+ *_, config_remaining, cli_remaining = parser.parse_args_and_config(
62
+ all_args, return_remaining_strings=True, separate_remaining_strings=True
63
+ )
64
+ launch_args = resolve_accelerate_config_argument(config_remaining + cli_remaining)
65
+ training_script_args = _subtract_subsequence(all_args, cli_remaining)
66
+
67
+ launch_training_script(
68
+ script_name=f"{self.name}.py",
69
+ launch_args=launch_args,
70
+ training_script_args=training_script_args,
71
+ )
72
+ return 0