AdithyaSK HF Staff commited on
Commit
d722c3a
·
verified ·
1 Parent(s): d68112e

Stage Harbor release files 10001-10500

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-1fe00f939ab9/tests/source/examples/scripts/prm.py +121 -0
  2. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/reward_modeling.py +122 -0
  3. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/rloo.py +99 -0
  4. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/rloo_vlm.py +155 -0
  5. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sdft.py +426 -0
  6. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sdpo.py +388 -0
  7. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sft.py +17 -0
  8. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sft_gemma3.py +69 -0
  9. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sft_gpt_oss.py +91 -0
  10. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sft_nemotron_3.py +110 -0
  11. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sft_tiny_aya_tool_calling.py +164 -0
  12. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sft_vlm.py +113 -0
  13. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sft_vlm_gemma3.py +185 -0
  14. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/ssd.py +158 -0
  15. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/ssd_eval.py +260 -0
  16. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/tiny_aya_chat_template.jinja +66 -0
  17. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/tpo.py +210 -0
  18. tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/xpo.py +106 -0
  19. tasks/tasksmith-1fe00f939ab9/tests/source/pyproject.toml +205 -0
  20. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/add_copyrights.py +92 -0
  21. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_harmony_dataset.py +263 -0
  22. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/README.md +57 -0
  23. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/__init__.py +14 -0
  24. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/_common.py +282 -0
  25. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/__init__.py +14 -0
  26. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/_remote_code/__init__.py +17 -0
  27. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/_remote_code/configuration_remote.py +19 -0
  28. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/_remote_code/modeling_remote.py +39 -0
  29. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/cohere2_for_causal_lm.py +61 -0
  30. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/cohere_for_causal_lm.py +48 -0
  31. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/deepseek_v3_for_causal_lm.py +47 -0
  32. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/deepseek_v3_for_causal_lm_0528.py +49 -0
  33. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/falcon_mamba_for_causal_lm.py +47 -0
  34. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/gemma2_for_causal_lm.py +47 -0
  35. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/gemma_for_causal_lm.py +47 -0
  36. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/glm4_moe_for_causal_lm.py +58 -0
  37. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/gpt2_lm_head_model.py +47 -0
  38. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/gpt_neox_for_causal_lm.py +47 -0
  39. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/gpt_oss_for_causal_lm.py +49 -0
  40. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/llama_for_causal_lm_3.py +47 -0
  41. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/llama_for_causal_lm_3_1.py +47 -0
  42. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/llama_for_causal_lm_3_2.py +47 -0
  43. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/mistral_for_causal_lm_0_1.py +47 -0
  44. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/mistral_for_causal_lm_0_2.py +47 -0
  45. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/nemotron_3_nano_for_causal_lm.py +66 -0
  46. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/nemotron_3_super_for_causal_lm.py +59 -0
  47. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/nemotron_3_ultra_for_causal_lm.py +59 -0
  48. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/olmo3_for_causal_lm.py +64 -0
  49. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/opt_for_causal_lm.py +47 -0
  50. tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/peft_qwen3_for_causal_lm.py +28 -0
tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/prm.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "trl",
18
+ # "trackio",
19
+ # "kernels",
20
+ # ]
21
+ # ///
22
+
23
+ """
24
+ Full training:
25
+ python examples/scripts/prm.py \
26
+ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \
27
+ --dataset_name trl-lib/prm800k \
28
+ --output_dir Qwen2-0.5B-Reward \
29
+ --per_device_train_batch_size 8 \
30
+ --num_train_epochs 1 \
31
+ --learning_rate 1.0e-5 \
32
+ --eval_strategy steps \
33
+ --eval_steps 50
34
+
35
+ LoRA:
36
+ python examples/scripts/prm.py \
37
+ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \
38
+ --dataset_name trl-lib/prm800k \
39
+ --output_dir Qwen2-0.5B-Reward-LoRA \
40
+ --per_device_train_batch_size 8 \
41
+ --num_train_epochs 1 \
42
+ --learning_rate 1.0e-4 \
43
+ --eval_strategy steps \
44
+ --eval_steps 50
45
+ --use_peft \
46
+ --lora_r 32 \
47
+ --lora_alpha 16
48
+ """
49
+
50
+ import torch
51
+ from accelerate import logging
52
+ from datasets import load_dataset
53
+ from transformers import AutoModelForTokenClassification, AutoTokenizer, HfArgumentParser
54
+
55
+ from trl import ModelConfig, ScriptArguments, get_peft_config, get_quantization_config
56
+ from trl.experimental.prm import PRMConfig, PRMTrainer
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+
62
+ if __name__ == "__main__":
63
+ parser = HfArgumentParser((ScriptArguments, PRMConfig, ModelConfig))
64
+ script_args, training_args, model_args = parser.parse_args_into_dataclasses()
65
+
66
+ ################
67
+ # Model & Tokenizer
68
+ ################
69
+ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
70
+ model_kwargs = dict(
71
+ revision=model_args.model_revision,
72
+ use_cache=False if training_args.gradient_checkpointing else True,
73
+ )
74
+ quantization_config = get_quantization_config(model_args)
75
+ if quantization_config is not None:
76
+ # Passing None would not be treated the same as omitting the argument, so we include it only when valid.
77
+ model_kwargs["quantization_config"] = quantization_config
78
+
79
+ tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, use_fast=True)
80
+ model = AutoModelForTokenClassification.from_pretrained(
81
+ model_args.model_name_or_path, num_labels=2, **model_kwargs
82
+ )
83
+
84
+ if model_args.use_peft and model_args.lora_task_type != "TOKEN_CLS":
85
+ logger.warning(
86
+ "You are using a `task_type` that is different than `TOKEN_CLS` for PEFT. This will lead to silent bugs"
87
+ " Make sure to pass --lora_task_type TOKEN_CLS when using this script with PEFT.",
88
+ )
89
+
90
+ ##############
91
+ # Load dataset
92
+ ##############
93
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
94
+
95
+ dataset = dataset.filter(lambda x: len(x["completions"]) > 0)
96
+
97
+ ##########
98
+ # Training
99
+ ##########
100
+ trainer = PRMTrainer(
101
+ model=model,
102
+ processing_class=tokenizer,
103
+ args=training_args,
104
+ train_dataset=dataset[script_args.dataset_train_split],
105
+ eval_dataset=dataset[script_args.dataset_test_split],
106
+ peft_config=get_peft_config(model_args),
107
+ )
108
+ trainer.train()
109
+
110
+ ############################
111
+ # Save model and push to Hub
112
+ ############################
113
+ trainer.save_model(training_args.output_dir)
114
+ metrics = trainer.evaluate()
115
+ trainer.log_metrics("eval", metrics)
116
+ trainer.save_metrics("eval", metrics)
117
+
118
+ # Save and push to hub
119
+ trainer.save_model(training_args.output_dir)
120
+ if training_args.push_to_hub:
121
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/reward_modeling.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Full training:
25
+ python examples/scripts/reward_modeling.py \
26
+ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \
27
+ --dataset_name trl-lib/ultrafeedback_binarized \
28
+ --output_dir Qwen2-0.5B-Reward \
29
+ --per_device_train_batch_size 8 \
30
+ --num_train_epochs 1 \
31
+ --learning_rate 1.0e-5 \
32
+ --eval_strategy steps \
33
+ --eval_steps 50 \
34
+ --max_length 2048
35
+
36
+ LoRA:
37
+ python examples/scripts/reward_modeling.py \
38
+ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \
39
+ --dataset_name trl-lib/ultrafeedback_binarized \
40
+ --output_dir Qwen2-0.5B-Reward-LoRA \
41
+ --per_device_train_batch_size 8 \
42
+ --num_train_epochs 1 \
43
+ --learning_rate 1.0e-4 \
44
+ --eval_strategy steps \
45
+ --eval_steps 50 \
46
+ --max_length 2048 \
47
+ --use_peft \
48
+ --lora_task_type SEQ_CLS \
49
+ --lora_r 32 \
50
+ --lora_alpha 16
51
+ """
52
+
53
+ import torch
54
+ from accelerate import logging
55
+ from datasets import load_dataset
56
+ from transformers import AutoModelForSequenceClassification, HfArgumentParser
57
+
58
+ from trl import ModelConfig, RewardConfig, RewardTrainer, ScriptArguments, get_peft_config, get_quantization_config
59
+
60
+
61
+ logger = logging.get_logger(__name__)
62
+
63
+
64
+ if __name__ == "__main__":
65
+ parser = HfArgumentParser((ScriptArguments, RewardConfig, ModelConfig))
66
+ script_args, training_args, model_args = parser.parse_args_into_dataclasses()
67
+
68
+ ################
69
+ # Model & Tokenizer
70
+ ################
71
+ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
72
+ model_kwargs = dict(
73
+ revision=model_args.model_revision,
74
+ use_cache=False if training_args.gradient_checkpointing else True,
75
+ dtype=dtype,
76
+ )
77
+ quantization_config = get_quantization_config(model_args)
78
+ if quantization_config is not None:
79
+ # Passing None would not be treated the same as omitting the argument, so we include it only when valid.
80
+ model_kwargs["quantization_config"] = quantization_config
81
+
82
+ model = AutoModelForSequenceClassification.from_pretrained(
83
+ model_args.model_name_or_path, num_labels=1, **model_kwargs
84
+ )
85
+
86
+ if model_args.use_peft and model_args.lora_task_type != "SEQ_CLS":
87
+ logger.warning(
88
+ "You are using a `task_type` that is different than `SEQ_CLS` for PEFT. This will lead to silent bugs"
89
+ " Make sure to pass --lora_task_type SEQ_CLS when using this script with PEFT.",
90
+ )
91
+
92
+ ##############
93
+ # Load dataset
94
+ ##############
95
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
96
+
97
+ ##########
98
+ # Training
99
+ ##########
100
+ trainer = RewardTrainer(
101
+ model=model,
102
+ args=training_args,
103
+ train_dataset=dataset[script_args.dataset_train_split],
104
+ eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
105
+ peft_config=get_peft_config(model_args),
106
+ )
107
+ trainer.train()
108
+
109
+ ############################
110
+ # Save model and push to Hub
111
+ ############################
112
+ trainer.save_model(training_args.output_dir)
113
+
114
+ if training_args.eval_strategy != "no":
115
+ metrics = trainer.evaluate()
116
+ trainer.log_metrics("eval", metrics)
117
+ trainer.save_metrics("eval", metrics)
118
+
119
+ # Save and push to hub
120
+ trainer.save_model(training_args.output_dir)
121
+ if training_args.push_to_hub:
122
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/rloo.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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[vllm,peft]",
18
+ # "math-verify",
19
+ # "latex2sympy2_extended",
20
+ # "trackio",
21
+ # "kernels",
22
+ # ]
23
+ # ///
24
+
25
+ """
26
+ NuminaMath example: RLOO on math dataset with vLLM.
27
+
28
+ pip install math_verify num2words==0.5.14 peft trackio vllm
29
+ export TRACKIO_PROJECT="RLOO-NuminaMath-TIR"
30
+ accelerate launch --config_file examples/accelerate_configs/deepspeed_zero3.yaml examples/scripts/rloo.py
31
+
32
+ For TL;DR or other datasets with a reward model, use the generic script:
33
+ python -m trl.scripts.rloo --dataset_name trl-lib/tldr --reward_model_name_or_path ... --model_name_or_path ...
34
+ """
35
+
36
+ import torch
37
+ from datasets import load_dataset
38
+ from peft import LoraConfig
39
+
40
+ from trl import RLOOConfig, RLOOTrainer
41
+ from trl.rewards import accuracy_reward, think_format_reward
42
+
43
+
44
+ def main():
45
+ # Dataset
46
+ train_dataset, eval_dataset = load_dataset("AI-MO/NuminaMath-TIR", split=["train[:5%]", "test[:5%]"])
47
+
48
+ SYSTEM_PROMPT = (
49
+ "A conversation between user and assistant. The user asks a question, and the assistant solves it. The "
50
+ "assistant first thinks about the reasoning process in the mind and then provides the user with the answer. "
51
+ "The reasoning process and answer are enclosed within <think></think> tags, i.e., <think>\nThis is my "
52
+ "reasoning.\n</think>\nThis is my answer."
53
+ )
54
+
55
+ def make_conversation(example):
56
+ return {
57
+ "prompt": [
58
+ {"role": "system", "content": SYSTEM_PROMPT},
59
+ {"role": "user", "content": example["problem"]},
60
+ ],
61
+ }
62
+
63
+ train_dataset = train_dataset.map(make_conversation, remove_columns=["messages", "problem"])
64
+ eval_dataset = eval_dataset.map(make_conversation, remove_columns=["messages", "problem"])
65
+
66
+ # Training
67
+ training_args = RLOOConfig(
68
+ output_dir="Qwen3-0.6B-RLOO",
69
+ model_init_kwargs={"dtype": torch.bfloat16},
70
+ learning_rate=1e-5,
71
+ log_completions=True,
72
+ num_completions_to_print=2,
73
+ max_completion_length=1024,
74
+ gradient_accumulation_steps=2,
75
+ steps_per_generation=8,
76
+ use_vllm=True,
77
+ vllm_mode="colocate",
78
+ vllm_gpu_memory_utilization=0.5,
79
+ run_name="Qwen3-0.6B-RLOO-NuminaMath-TIR",
80
+ )
81
+
82
+ trainer = RLOOTrainer(
83
+ model="Qwen/Qwen3-0.6B",
84
+ args=training_args,
85
+ reward_funcs=[think_format_reward, accuracy_reward],
86
+ train_dataset=train_dataset,
87
+ eval_dataset=eval_dataset,
88
+ peft_config=LoraConfig(),
89
+ )
90
+
91
+ trainer.train()
92
+
93
+ # Save and push to hub
94
+ trainer.save_model(training_args.output_dir)
95
+ trainer.push_to_hub(dataset_name="AI-MO/NuminaMath-TIR")
96
+
97
+
98
+ if __name__ == "__main__":
99
+ main()
tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/rloo_vlm.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "trl[peft]",
18
+ # "Pillow",
19
+ # "math-verify",
20
+ # "latex2sympy2_extended",
21
+ # "torchvision",
22
+ # "trackio",
23
+ # "kernels",
24
+ # ]
25
+ # ///
26
+
27
+ """
28
+ pip install math_verify
29
+
30
+ # For Qwen/Qwen2.5-VL-3B-Instruct
31
+ accelerate launch \
32
+ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \
33
+ examples/scripts/rloo_vlm.py \
34
+ --model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \
35
+ --output_dir rloo-Qwen2.5-VL-3B-Instruct \
36
+ --learning_rate 1e-5 \
37
+ --dtype bfloat16 \
38
+ --max_completion_length 1024 \
39
+ --use_vllm \
40
+ --vllm_mode colocate \
41
+ --use_peft \
42
+ --lora_target_modules "q_proj", "v_proj" \
43
+ --log_completions
44
+
45
+ # For HuggingFaceTB/SmolVLM2-2.2B-Instruct
46
+ pip install num2words==0.5.14
47
+
48
+ accelerate launch \
49
+ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \
50
+ examples/scripts/rloo_vlm.py \
51
+ --model_name_or_path HuggingFaceTB/SmolVLM2-2.2B-Instruct \
52
+ --output_dir rloo-SmolVLM2-2.2B-Instruct \
53
+ --learning_rate 1e-5 \
54
+ --dtype bfloat16 \
55
+ --max_completion_length 1024 \
56
+ --use_peft \
57
+ --lora_target_modules "q_proj", "v_proj" \
58
+ --log_completions \
59
+ --per_device_train_batch_size 1 \
60
+ --gradient_accumulation_steps 2 \
61
+ --num_generations 2
62
+
63
+ """
64
+
65
+ import torch
66
+ from datasets import load_dataset
67
+
68
+ from trl import (
69
+ ModelConfig,
70
+ RLOOConfig,
71
+ RLOOTrainer,
72
+ ScriptArguments,
73
+ TrlParser,
74
+ get_peft_config,
75
+ get_quantization_config,
76
+ )
77
+ from trl.rewards import accuracy_reward, think_format_reward
78
+
79
+
80
+ if __name__ == "__main__":
81
+ parser = TrlParser((ScriptArguments, RLOOConfig, ModelConfig))
82
+ script_args, training_args, model_args = parser.parse_args_and_config()
83
+ ################
84
+ # Model
85
+ ################
86
+ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
87
+ training_args.model_init_kwargs = dict(
88
+ revision=model_args.model_revision,
89
+ attn_implementation=model_args.attn_implementation,
90
+ dtype=dtype,
91
+ )
92
+ quantization_config = get_quantization_config(model_args)
93
+ if quantization_config is not None:
94
+ # Passing None would not be treated the same as omitting the argument, so we include it only when valid.
95
+ training_args.model_init_kwargs["quantization_config"] = quantization_config
96
+
97
+ ################
98
+ # Dataset
99
+ ################
100
+ dataset = load_dataset("lmms-lab/multimodal-open-r1-8k-verified", split="train")
101
+ dataset = dataset.train_test_split(test_size=100, seed=42)
102
+
103
+ SYSTEM_PROMPT = (
104
+ "A conversation between user and assistant. The user asks a question, and the assistant solves it. The "
105
+ "assistant first thinks about the reasoning process in the mind and then provides the user with the answer. "
106
+ "The reasoning process and answer are enclosed within <think></think> tags, i.e., <think>\nThis is my "
107
+ "reasoning.\n</think>\nThis is my answer."
108
+ )
109
+
110
+ def make_conversation(example):
111
+ prompt = [
112
+ {"role": "system", "content": SYSTEM_PROMPT},
113
+ {"role": "user", "content": example["problem"]},
114
+ ]
115
+ return {"prompt": prompt}
116
+
117
+ dataset = dataset.map(make_conversation)
118
+
119
+ # Filter have big images
120
+ def filter_big_images(example):
121
+ image = example["image"]
122
+ return image.size[0] < 512 and image.size[1] < 512
123
+
124
+ dataset = dataset.filter(filter_big_images)
125
+
126
+ def convert_to_rgb(example):
127
+ image = example["image"]
128
+ if image.mode != "RGB":
129
+ image = image.convert("RGB")
130
+ example["image"] = image
131
+ return example
132
+
133
+ dataset = dataset.map(convert_to_rgb)
134
+
135
+ train_dataset = dataset["train"]
136
+ eval_dataset = dataset["test"] if training_args.eval_strategy != "no" else None
137
+
138
+ ################
139
+ # Training
140
+ ################
141
+ trainer = RLOOTrainer(
142
+ model=model_args.model_name_or_path,
143
+ args=training_args,
144
+ reward_funcs=[think_format_reward, accuracy_reward],
145
+ train_dataset=train_dataset,
146
+ eval_dataset=eval_dataset,
147
+ peft_config=get_peft_config(model_args),
148
+ )
149
+
150
+ trainer.train()
151
+
152
+ # Save and push to hub
153
+ trainer.save_model(training_args.output_dir)
154
+ if training_args.push_to_hub:
155
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sdft.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "trl",
18
+ # "peft",
19
+ # "trackio",
20
+ # "kernels",
21
+ # ]
22
+ # ///
23
+
24
+ """
25
+ Small-scale SDFT training with Qwen/Qwen3.5-0.8B.
26
+
27
+ Expected dataset formats:
28
+
29
+ 1. Native TRL self-distillation format:
30
+ - `prompt`
31
+ - `privileged_context` containing only the extra teacher-only information
32
+
33
+ 2. Demonstration-based format:
34
+ - `prompt`
35
+ - `golden_response`
36
+
37
+ Example:
38
+
39
+ ```bash
40
+ python examples/scripts/sdft.py \
41
+ --model_name_or_path Qwen/Qwen3.5-0.8B \
42
+ --dataset_name your-org/your-dataset \
43
+ --output_dir outputs/sdft-qwen3.5-0.8b \
44
+ --per_device_train_batch_size 1 \
45
+ --gradient_accumulation_steps 16 \
46
+ --learning_rate 2e-5 \
47
+ --max_prompt_length 1024 \
48
+ --max_completion_length 512 \
49
+ --teacher_model_kind ema \
50
+ --teacher_sync_steps 1 \
51
+ --teacher_update_rate 0.01 \
52
+ --eval_strategy steps \
53
+ --eval_steps 50 \
54
+ --report_to wandb
55
+ ```
56
+ """
57
+
58
+ import json
59
+ import os
60
+ import re
61
+ from dataclasses import dataclass, field
62
+ from string import Template
63
+ from typing import Any
64
+
65
+ import torch
66
+ from datasets import DatasetDict, load_dataset, load_from_disk
67
+ from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
68
+
69
+ from trl import (
70
+ LogCompletionsCallback,
71
+ ModelConfig,
72
+ ScriptArguments,
73
+ TrlParser,
74
+ get_peft_config,
75
+ get_quantization_config,
76
+ )
77
+ from trl.data_utils import maybe_apply_chat_template
78
+ from trl.experimental.sdft import SDFTConfig, SDFTTrainer
79
+ from trl.models import unwrap_model_for_generation
80
+
81
+
82
+ DEFAULT_DEMONSTRATION_TEMPLATE = Template("""Example response: $output_text""")
83
+
84
+
85
+ @dataclass
86
+ class SDFTScriptArguments(ScriptArguments):
87
+ dataset_path: str | None = field(
88
+ default=None,
89
+ metadata={"help": "Optional local dataset path to load with `load_from_disk`. Overrides `dataset_name`."},
90
+ )
91
+ privileged_context_column: str = field(
92
+ default="privileged_context",
93
+ metadata={"help": "Column containing precomputed privileged context for SDFT."},
94
+ )
95
+ golden_response_column: str = field(
96
+ default="golden_response",
97
+ metadata={"help": "Column containing demonstration responses used to build privileged context."},
98
+ )
99
+ eval_num_prompts: int | None = field(
100
+ default=8,
101
+ metadata={"help": "Number of prompts to log during evaluation. Set to 0 to disable completion logging."},
102
+ )
103
+ demonstration_template: str = field(
104
+ default=DEFAULT_DEMONSTRATION_TEMPLATE.template,
105
+ metadata={"help": "Template used to build privileged context from demonstration content."},
106
+ )
107
+ tool_eval_num_examples: int | None = field(
108
+ default=None,
109
+ metadata={
110
+ "help": "Optional number of eval examples to score for tool-use metrics. Defaults to the full eval split."
111
+ },
112
+ )
113
+ tool_eval_max_new_tokens: int = field(
114
+ default=256,
115
+ metadata={"help": "Maximum completion length for task evaluation generation."},
116
+ )
117
+
118
+
119
+ def _extract_prompt_text(prompt: Any) -> str:
120
+ if isinstance(prompt, str):
121
+ return prompt
122
+ if isinstance(prompt, list) and prompt and isinstance(prompt[0], dict):
123
+ for message in reversed(prompt):
124
+ if message.get("role") == "user":
125
+ content = message.get("content", "")
126
+ if isinstance(content, list):
127
+ return " ".join(part.get("text", "") for part in content if part.get("type") == "text")
128
+ return content
129
+ return str(prompt)
130
+
131
+
132
+ def _stringify_golden_response(response: Any) -> str:
133
+ if isinstance(response, str):
134
+ return response
135
+ if isinstance(response, list):
136
+ return "\n".join(_stringify_golden_response(item) for item in response)
137
+ return str(response)
138
+
139
+
140
+ def _build_privileged_context(
141
+ example: dict[str, Any], privileged_context_column: str, golden_response_column: str, template: Template
142
+ ):
143
+ if privileged_context_column in example and example[privileged_context_column] is not None:
144
+ privileged_context = example[privileged_context_column]
145
+ elif golden_response_column in example:
146
+ privileged_context = template.safe_substitute(
147
+ orig_content=_extract_prompt_text(example["prompt"]),
148
+ output_text=_stringify_golden_response(example[golden_response_column]),
149
+ )
150
+ elif "teacher_prompt" in example:
151
+ raise ValueError(
152
+ "Datasets for `trl.experimental.sdft` should provide `privileged_context` or `golden_response`, not "
153
+ "`teacher_prompt`."
154
+ )
155
+ else:
156
+ raise ValueError("Dataset must contain either `privileged_context` or `golden_response` alongside `prompt`.")
157
+
158
+ return {
159
+ "prompt": example["prompt"],
160
+ "privileged_context": privileged_context,
161
+ }
162
+
163
+
164
+ def _prepare_split(dataset, script_args: SDFTScriptArguments):
165
+ template = Template(script_args.demonstration_template)
166
+ return dataset.map(
167
+ lambda example: _build_privileged_context(
168
+ example,
169
+ privileged_context_column=script_args.privileged_context_column,
170
+ golden_response_column=script_args.golden_response_column,
171
+ template=template,
172
+ ),
173
+ remove_columns=dataset.column_names,
174
+ )
175
+
176
+
177
+ def _can_prepare_privileged_context(dataset) -> bool:
178
+ columns = set(dataset.column_names)
179
+ return "prompt" in columns and ("privileged_context" in columns or "golden_response" in columns)
180
+
181
+
182
+ def _extract_action_and_input(text: str) -> tuple[str | None, str | None]:
183
+ action_match = re.search(r"Action:\s*([^\n]+)", text)
184
+ action_input_match = re.search(r"Action Input:\s*(.*)", text, flags=re.DOTALL)
185
+ action = action_match.group(1).strip() if action_match else None
186
+ action_input = action_input_match.group(1).strip() if action_input_match else None
187
+ return action, action_input
188
+
189
+
190
+ def _parse_json_object(text: str | None) -> tuple[bool, Any]:
191
+ if text is None:
192
+ return False, None
193
+ text = text.strip()
194
+ if text.startswith("```"):
195
+ text = re.sub(r"^```(?:json)?\s*", "", text)
196
+ text = re.sub(r"\s*```$", "", text)
197
+ try:
198
+ return True, json.loads(text)
199
+ except Exception:
200
+ return False, None
201
+
202
+
203
+ def _normalize_gold_answer(example: dict[str, Any]) -> tuple[str | None, Any]:
204
+ answers = example.get("golden_answer") or []
205
+ if not answers:
206
+ return None, None
207
+ answer = answers[0]
208
+ action = answer.get("Action")
209
+ valid_json, action_input = _parse_json_object(answer.get("Action_Input"))
210
+ return action, action_input if valid_json else answer.get("Action_Input")
211
+
212
+
213
+ def _apply_prompt_template(tokenizer, prompt: Any) -> str:
214
+ return maybe_apply_chat_template({"prompt": prompt}, tokenizer)["prompt"]
215
+
216
+
217
+ def _run_tooluse_eval(
218
+ trainer: SDFTTrainer,
219
+ eval_dataset,
220
+ max_new_tokens: int,
221
+ num_examples: int | None = None,
222
+ metric_prefix: str = "tool_eval",
223
+ ) -> dict[str, float]:
224
+ if num_examples is not None:
225
+ eval_dataset = eval_dataset.select(range(min(num_examples, len(eval_dataset))))
226
+
227
+ prompts = eval_dataset["prompt"]
228
+ prompt_texts = [_apply_prompt_template(trainer.processing_class, prompt) for prompt in prompts]
229
+ tokenized = trainer.processing_class(
230
+ text=prompt_texts,
231
+ return_tensors="pt",
232
+ padding=True,
233
+ padding_side="left",
234
+ truncation=True,
235
+ max_length=trainer.max_prompt_length,
236
+ add_special_tokens=False,
237
+ )
238
+ tokenized = {key: value.to(trainer.accelerator.device) for key, value in tokenized.items()}
239
+
240
+ with (
241
+ unwrap_model_for_generation(
242
+ trainer.model_wrapped,
243
+ trainer.accelerator,
244
+ gather_deepspeed3_params=trainer.args.ds3_gather_for_generation,
245
+ ) as unwrapped_model,
246
+ torch.no_grad(),
247
+ ):
248
+ generated = unwrapped_model.generate(
249
+ **tokenized,
250
+ max_new_tokens=max_new_tokens,
251
+ do_sample=False,
252
+ pad_token_id=trainer.processing_class.pad_token_id,
253
+ eos_token_id=trainer.processing_class.eos_token_id,
254
+ )
255
+
256
+ prompt_length = tokenized["input_ids"].shape[1]
257
+ completions = trainer.processing_class.batch_decode(generated[:, prompt_length:], skip_special_tokens=True)
258
+
259
+ action_correct = 0
260
+ json_valid = 0
261
+ full_match = 0
262
+ parsed_action_present = 0
263
+ records = []
264
+
265
+ for example, completion in zip(eval_dataset, completions, strict=True):
266
+ pred_action, pred_action_input_text = _extract_action_and_input(completion)
267
+ if pred_action is not None:
268
+ parsed_action_present += 1
269
+ pred_json_valid, pred_action_input = _parse_json_object(pred_action_input_text)
270
+ if pred_json_valid:
271
+ json_valid += 1
272
+
273
+ gold_action, gold_action_input = _normalize_gold_answer(example)
274
+ is_action_correct = pred_action == gold_action and gold_action is not None
275
+ if is_action_correct:
276
+ action_correct += 1
277
+ is_full_match = is_action_correct and pred_json_valid and pred_action_input == gold_action_input
278
+ if is_full_match:
279
+ full_match += 1
280
+
281
+ records.append(
282
+ {
283
+ "prompt": _extract_prompt_text(example["prompt"]),
284
+ "completion": completion,
285
+ "pred_action": pred_action,
286
+ "pred_action_input_text": pred_action_input_text,
287
+ "gold_action": gold_action,
288
+ "gold_action_input": gold_action_input,
289
+ "action_correct": is_action_correct,
290
+ "json_valid": pred_json_valid,
291
+ "full_match": is_full_match,
292
+ }
293
+ )
294
+
295
+ total = max(len(eval_dataset), 1)
296
+ metrics = {
297
+ f"{metric_prefix}/action_present_rate": parsed_action_present / total,
298
+ f"{metric_prefix}/valid_json_rate": json_valid / total,
299
+ f"{metric_prefix}/action_accuracy": action_correct / total,
300
+ f"{metric_prefix}/tool_call_accuracy": full_match / total,
301
+ }
302
+
303
+ sample_path = os.path.join(trainer.args.output_dir, f"{metric_prefix}_samples.json")
304
+ os.makedirs(trainer.args.output_dir, exist_ok=True)
305
+ with open(sample_path, "w") as f:
306
+ json.dump(records[: min(20, len(records))], f, indent=2)
307
+
308
+ return metrics
309
+
310
+
311
+ if __name__ == "__main__":
312
+ parser = TrlParser((SDFTScriptArguments, SDFTConfig, ModelConfig))
313
+ script_args, training_args, model_args = parser.parse_args_and_config()
314
+
315
+ if model_args.model_name_or_path is None:
316
+ raise ValueError("`model_name_or_path` is required.")
317
+ if model_args.dtype in ["auto", None]:
318
+ if training_args.bf16:
319
+ dtype = torch.bfloat16
320
+ elif training_args.fp16:
321
+ dtype = torch.float16
322
+ else:
323
+ dtype = "auto"
324
+ else:
325
+ dtype = getattr(torch, model_args.dtype)
326
+ model_kwargs = dict(
327
+ revision=model_args.model_revision,
328
+ attn_implementation=model_args.attn_implementation,
329
+ dtype=dtype,
330
+ )
331
+ quantization_config = get_quantization_config(model_args)
332
+ if quantization_config is not None:
333
+ model_kwargs["quantization_config"] = quantization_config
334
+
335
+ training_args.model_init_kwargs = model_kwargs
336
+
337
+ tokenizer = AutoTokenizer.from_pretrained(
338
+ model_args.model_name_or_path, revision=model_args.model_revision, padding_side="left"
339
+ )
340
+ if tokenizer.pad_token is None:
341
+ tokenizer.pad_token = tokenizer.eos_token
342
+
343
+ if script_args.dataset_path is not None:
344
+ dataset = load_from_disk(script_args.dataset_path)
345
+ else:
346
+ dataset = load_dataset(
347
+ script_args.dataset_name,
348
+ name=script_args.dataset_config,
349
+ streaming=script_args.dataset_streaming,
350
+ )
351
+
352
+ if not isinstance(dataset, DatasetDict):
353
+ raise ValueError("SDFT example expects a dataset with named splits.")
354
+
355
+ train_dataset = _prepare_split(dataset[script_args.dataset_train_split], script_args)
356
+ raw_eval_dataset = dataset[script_args.dataset_test_split] if script_args.dataset_test_split in dataset else None
357
+ eval_dataset = None
358
+ if (
359
+ training_args.eval_strategy != "no"
360
+ and raw_eval_dataset is not None
361
+ and _can_prepare_privileged_context(raw_eval_dataset)
362
+ ):
363
+ eval_dataset = _prepare_split(raw_eval_dataset, script_args)
364
+
365
+ model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
366
+ model.config.use_cache = False if training_args.gradient_checkpointing else True
367
+
368
+ trainer = SDFTTrainer(
369
+ model=model,
370
+ args=training_args,
371
+ train_dataset=train_dataset,
372
+ eval_dataset=eval_dataset,
373
+ processing_class=tokenizer,
374
+ peft_config=get_peft_config(model_args),
375
+ )
376
+
377
+ if eval_dataset is not None and script_args.eval_num_prompts:
378
+ generation_config = GenerationConfig(
379
+ max_new_tokens=training_args.max_completion_length,
380
+ do_sample=True,
381
+ temperature=training_args.temperature,
382
+ )
383
+ trainer.add_callback(
384
+ LogCompletionsCallback(trainer, generation_config, num_prompts=script_args.eval_num_prompts)
385
+ )
386
+
387
+ pretrain_metrics = None
388
+ if raw_eval_dataset is not None and "golden_answer" in raw_eval_dataset.column_names:
389
+ pretrain_metrics = _run_tooluse_eval(
390
+ trainer,
391
+ raw_eval_dataset,
392
+ max_new_tokens=script_args.tool_eval_max_new_tokens,
393
+ num_examples=script_args.tool_eval_num_examples,
394
+ metric_prefix="tool_eval_before",
395
+ )
396
+ trainer.log(pretrain_metrics)
397
+ trainer.log_metrics("eval", pretrain_metrics)
398
+ trainer.save_metrics("eval", pretrain_metrics)
399
+
400
+ trainer.train()
401
+
402
+ trainer.save_model(training_args.output_dir)
403
+ if eval_dataset is not None:
404
+ metrics = trainer.evaluate()
405
+ trainer.log_metrics("eval", metrics)
406
+ trainer.save_metrics("eval", metrics)
407
+ if raw_eval_dataset is not None and "golden_answer" in raw_eval_dataset.column_names:
408
+ post_metrics = _run_tooluse_eval(
409
+ trainer,
410
+ raw_eval_dataset,
411
+ max_new_tokens=script_args.tool_eval_max_new_tokens,
412
+ num_examples=script_args.tool_eval_num_examples,
413
+ metric_prefix="tool_eval_after",
414
+ )
415
+ if pretrain_metrics is not None:
416
+ for key, value in pretrain_metrics.items():
417
+ after_key = key.replace("tool_eval_before/", "tool_eval_after/")
418
+ if after_key in post_metrics:
419
+ delta_name = after_key.replace("tool_eval_after/", "tool_eval_delta/")
420
+ post_metrics[delta_name] = post_metrics[after_key] - value
421
+ trainer.log(post_metrics)
422
+ trainer.log_metrics("eval", post_metrics)
423
+ trainer.save_metrics("eval", post_metrics)
424
+
425
+ if training_args.push_to_hub:
426
+ trainer.push_to_hub(dataset_name=script_args.dataset_name or script_args.dataset_path)
tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sdpo.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "trl",
18
+ # "peft",
19
+ # "math-verify",
20
+ # "latex2sympy2_extended",
21
+ # "trackio",
22
+ # "kernels",
23
+ # ]
24
+ # ///
25
+
26
+ """
27
+ Usage:
28
+
29
+ ```bash
30
+ python examples/scripts/sdpo.py \
31
+ --model_name_or_path Qwen/Qwen2.5-Math-1.5B-Instruct \
32
+ --dataset_name openai/gsm8k \
33
+ --dataset_config main \
34
+ --output_dir outputs/sdpo-qwen35-2b-gsm8k \
35
+ --learning_rate 5e-5 \
36
+ --dtype bfloat16 \
37
+ --bf16 true \
38
+ --max_completion_length 128 \
39
+ --use_peft \
40
+ --lora_target_modules q_proj k_proj v_proj o_proj gate_proj up_proj down_proj \
41
+ --per_device_train_batch_size 1 \
42
+ --gradient_accumulation_steps 2 \
43
+ --num_generations 8 \
44
+ --generation_batch_size 32 \
45
+ --distillation_alpha 1.0 \
46
+ --distillation_mode sampled_token \
47
+ --distillation_weight 0.5 \
48
+ --report_to none \
49
+ --eval_strategy steps \
50
+ --eval_steps 1000 \
51
+ --save_strategy no \
52
+ --eval_num_prompts 0 \
53
+ --accuracy_eval_num_examples 64 \
54
+ --max_train_examples 256 \
55
+ --max_eval_examples 128
56
+ ```
57
+
58
+ This example uses verifiable math rewards and reports answer accuracy before and after training. If your dataset
59
+ already contains textual environment feedback, pass the column name via `--feedback_column`; it will be forwarded as
60
+ `privileged_context` for SDPO reprompting.
61
+ """
62
+
63
+ import re
64
+ from dataclasses import dataclass, field
65
+ from typing import Any
66
+
67
+ import torch
68
+ from datasets import DatasetDict, load_dataset, load_from_disk
69
+ from transformers import AutoTokenizer, GenerationConfig
70
+
71
+ from trl import (
72
+ LogCompletionsCallback,
73
+ ModelConfig,
74
+ ScriptArguments,
75
+ TrlParser,
76
+ get_peft_config,
77
+ get_quantization_config,
78
+ )
79
+ from trl.data_utils import maybe_apply_chat_template
80
+ from trl.experimental.sdpo import SDPOConfig, SDPOTrainer
81
+
82
+
83
+ SYSTEM_PROMPT = (
84
+ "A conversation between user and assistant. The user asks a question, and the assistant solves it. The assistant "
85
+ "first thinks about the reasoning process in the mind and then provides the user with the answer. The reasoning "
86
+ "must be enclosed within <think></think> tags, and the final answer must be on its own line in the format "
87
+ "`#### <answer>`."
88
+ )
89
+
90
+
91
+ @dataclass
92
+ class SDPOScriptArguments(ScriptArguments):
93
+ dataset_path: str | None = field(
94
+ default=None,
95
+ metadata={"help": "Optional local dataset path to load with `load_from_disk`. Overrides `dataset_name`."},
96
+ )
97
+ feedback_column: str | None = field(
98
+ default=None,
99
+ metadata={
100
+ "help": "Optional dataset column containing textual environment feedback to pass as `privileged_context`."
101
+ },
102
+ )
103
+ eval_num_prompts: int | None = field(
104
+ default=8,
105
+ metadata={"help": "Number of prompts to log during evaluation. Set to 0 to disable completion logging."},
106
+ )
107
+ accuracy_eval_num_examples: int | None = field(
108
+ default=128,
109
+ metadata={"help": "Optional number of eval examples to score for answer accuracy. Defaults to 128."},
110
+ )
111
+ accuracy_eval_max_new_tokens: int = field(
112
+ default=128,
113
+ metadata={"help": "Maximum completion length for answer-accuracy evaluation generation."},
114
+ )
115
+ feedback_from_solution: str | None = field(
116
+ default=None,
117
+ metadata={
118
+ "help": "Optional synthesized feedback source when the dataset has no feedback column. Supported: "
119
+ "`final_answer`, `full_solution`."
120
+ },
121
+ )
122
+ max_train_examples: int | None = field(
123
+ default=None,
124
+ metadata={"help": "Optional cap on the number of training examples loaded from the selected train split."},
125
+ )
126
+ max_eval_examples: int | None = field(
127
+ default=None,
128
+ metadata={"help": "Optional cap on the number of evaluation examples loaded from the selected eval split."},
129
+ )
130
+ dataset_shuffle_seed: int = field(
131
+ default=42,
132
+ metadata={"help": "Random seed used before applying `max_train_examples` or `max_eval_examples`."},
133
+ )
134
+
135
+
136
+ @dataclass
137
+ class ExampleSDPOConfig(SDPOConfig):
138
+ scale_rewards: str = field(
139
+ default="group",
140
+ metadata={"help": "Reward normalization mode. Supported: `group`, `batch`, `none`."},
141
+ )
142
+
143
+
144
+ def _make_solution_feedback(final_answer: str, worked_solution: str, feedback_from_solution: str | None) -> str | None:
145
+ if feedback_from_solution is None:
146
+ return None
147
+ if feedback_from_solution == "final_answer":
148
+ return (
149
+ "Your previous answer was incorrect. The correct final answer is:\n\n"
150
+ f"#### {final_answer}\n\n"
151
+ "Revise your reasoning and end with the same final answer format."
152
+ )
153
+ if feedback_from_solution == "full_solution":
154
+ return (
155
+ "Your previous answer was incorrect. Here is a correct worked solution:\n\n"
156
+ f"{worked_solution}\n\n"
157
+ "Use it to solve the original question correctly."
158
+ )
159
+ raise ValueError("feedback_from_solution must be one of: `final_answer`, `full_solution`.")
160
+
161
+
162
+ def _make_conversation(
163
+ example: dict[str, Any], feedback_column: str | None, feedback_from_solution: str | None
164
+ ) -> dict[str, Any]:
165
+ prompt = example.get("prompt")
166
+ if prompt is None and "problem" in example:
167
+ prompt = [
168
+ {"role": "system", "content": SYSTEM_PROMPT},
169
+ {"role": "user", "content": example["problem"]},
170
+ ]
171
+ if prompt is None and "question" in example:
172
+ prompt = [
173
+ {"role": "system", "content": SYSTEM_PROMPT},
174
+ {"role": "user", "content": example["question"]},
175
+ ]
176
+
177
+ if prompt is None:
178
+ raise ValueError("Each example must provide one of: `prompt`, `problem`, or `question`.")
179
+
180
+ output = {"prompt": prompt}
181
+
182
+ solution = None
183
+ if "solution" in example:
184
+ solution = example["solution"]
185
+ elif "answer" in example:
186
+ solution = _normalize_gsm8k_answer(example["answer"])
187
+
188
+ if solution is not None:
189
+ output["solution"] = solution
190
+
191
+ if feedback_column is not None and feedback_column in example:
192
+ output["privileged_context"] = example[feedback_column]
193
+ elif "privileged_context" in example:
194
+ output["privileged_context"] = example["privileged_context"]
195
+ elif solution is not None:
196
+ worked_solution = example.get("solution")
197
+ if worked_solution is None and "answer" in example:
198
+ worked_solution = example["answer"].strip()
199
+ if worked_solution is None:
200
+ worked_solution = f"#### {solution}"
201
+ synthesized_feedback = _make_solution_feedback(solution, worked_solution, feedback_from_solution)
202
+ if synthesized_feedback is not None:
203
+ output["privileged_context"] = synthesized_feedback
204
+
205
+ return output
206
+
207
+
208
+ def _normalize_gsm8k_answer(answer_text: str) -> str:
209
+ if "####" not in answer_text:
210
+ return answer_text.strip()
211
+ return answer_text.split("####", 1)[1].strip().replace(",", "")
212
+
213
+
214
+ def _extract_predicted_answer(completion_text: str) -> str | None:
215
+ match = re.search(r"####\s*([^\n]+)", completion_text)
216
+ if match:
217
+ return match.group(1).strip().replace(",", "")
218
+
219
+ matches = re.findall(r"(-?\$?[0-9][0-9,]*(?:\.[0-9]+)?)", completion_text)
220
+ if not matches:
221
+ return None
222
+ return matches[-1].replace("$", "").replace(",", "").strip()
223
+
224
+
225
+ def _gsm8k_accuracy_reward(completions, solution, **kwargs) -> list[float]:
226
+ rewards = []
227
+ for completion, gold in zip(completions, solution, strict=True):
228
+ content = completion[0]["content"] if isinstance(completion, list) else completion
229
+ pred = _extract_predicted_answer(content)
230
+ rewards.append(1.0 if pred is not None and pred == gold else 0.0)
231
+ return rewards
232
+
233
+
234
+ def _gsm8k_soft_format_reward(completions, **kwargs) -> list[float]:
235
+ pattern = r"<think>.*?</think>\s*####\s*[^\n]+"
236
+ rewards = []
237
+ for completion in completions:
238
+ content = completion[0]["content"] if isinstance(completion, list) else completion
239
+ rewards.append(0.25 if re.match(pattern, content, flags=re.DOTALL) else 0.0)
240
+ return rewards
241
+
242
+
243
+ def _run_accuracy_eval(
244
+ trainer: SDPOTrainer, eval_dataset, max_new_tokens: int, num_examples: int | None, metric_prefix: str = "math_eval"
245
+ ) -> dict[str, float]:
246
+ if num_examples is not None:
247
+ eval_dataset = eval_dataset.select(range(min(num_examples, len(eval_dataset))))
248
+
249
+ prompts = eval_dataset["prompt"]
250
+ prompt_texts = [
251
+ maybe_apply_chat_template({"prompt": prompt}, trainer.processing_class)["prompt"] for prompt in prompts
252
+ ]
253
+ tokenized = trainer.processing_class(
254
+ text=prompt_texts,
255
+ return_tensors="pt",
256
+ padding=True,
257
+ padding_side="left",
258
+ truncation=True,
259
+ max_length=trainer.max_prompt_length,
260
+ add_special_tokens=False,
261
+ )
262
+ tokenized = {key: value.to(trainer.accelerator.device) for key, value in tokenized.items()}
263
+ model = trainer.accelerator.unwrap_model(trainer.model)
264
+ was_training = model.training
265
+ model.eval()
266
+ with torch.no_grad():
267
+ generated = model.generate(
268
+ **tokenized,
269
+ max_new_tokens=max_new_tokens,
270
+ do_sample=False,
271
+ pad_token_id=trainer.processing_class.pad_token_id,
272
+ eos_token_id=trainer.processing_class.eos_token_id,
273
+ )
274
+ if was_training:
275
+ model.train()
276
+
277
+ prompt_length = tokenized["input_ids"].shape[1]
278
+ completions = trainer.processing_class.batch_decode(generated[:, prompt_length:], skip_special_tokens=True)
279
+ completion_messages = [[{"role": "assistant", "content": completion}] for completion in completions]
280
+ rewards = _gsm8k_accuracy_reward(completion_messages, solution=eval_dataset["solution"])
281
+ total = max(len(rewards), 1)
282
+ return {
283
+ f"{metric_prefix}/accuracy": sum(rewards) / total,
284
+ f"{metric_prefix}/num_scored": float(len(rewards)),
285
+ }
286
+
287
+
288
+ if __name__ == "__main__":
289
+ parser = TrlParser((SDPOScriptArguments, ExampleSDPOConfig, ModelConfig))
290
+ script_args, training_args, model_args = parser.parse_args_and_config()
291
+
292
+ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
293
+ training_args.model_init_kwargs = dict(
294
+ revision=model_args.model_revision,
295
+ attn_implementation=model_args.attn_implementation,
296
+ dtype=dtype,
297
+ )
298
+ quantization_config = get_quantization_config(model_args)
299
+ if quantization_config is not None:
300
+ training_args.model_init_kwargs["quantization_config"] = quantization_config
301
+
302
+ if script_args.dataset_path is not None:
303
+ dataset = load_from_disk(script_args.dataset_path)
304
+ else:
305
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
306
+
307
+ if not isinstance(dataset, DatasetDict):
308
+ raise ValueError("SDPO example expects a dataset with named splits.")
309
+
310
+ train_split = dataset[script_args.dataset_train_split]
311
+ if script_args.max_train_examples is not None:
312
+ train_split = train_split.shuffle(seed=script_args.dataset_shuffle_seed).select(
313
+ range(min(script_args.max_train_examples, len(train_split)))
314
+ )
315
+
316
+ train_dataset = train_split.map(
317
+ lambda example: _make_conversation(example, script_args.feedback_column, script_args.feedback_from_solution),
318
+ remove_columns=train_split.column_names,
319
+ )
320
+ eval_dataset = None
321
+ if training_args.eval_strategy != "no":
322
+ eval_split = dataset[script_args.dataset_test_split]
323
+ if script_args.max_eval_examples is not None:
324
+ eval_split = eval_split.shuffle(seed=script_args.dataset_shuffle_seed).select(
325
+ range(min(script_args.max_eval_examples, len(eval_split)))
326
+ )
327
+
328
+ eval_dataset = eval_split.map(
329
+ lambda example: _make_conversation(
330
+ example, script_args.feedback_column, script_args.feedback_from_solution
331
+ ),
332
+ remove_columns=eval_split.column_names,
333
+ )
334
+
335
+ reward_funcs = [_gsm8k_soft_format_reward, _gsm8k_accuracy_reward]
336
+
337
+ tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path)
338
+ if tokenizer.pad_token is None:
339
+ tokenizer.pad_token = tokenizer.eos_token
340
+
341
+ trainer = SDPOTrainer(
342
+ model=model_args.model_name_or_path,
343
+ args=training_args,
344
+ reward_funcs=reward_funcs,
345
+ train_dataset=train_dataset,
346
+ eval_dataset=eval_dataset,
347
+ peft_config=get_peft_config(model_args),
348
+ processing_class=tokenizer,
349
+ )
350
+
351
+ if eval_dataset is not None and script_args.eval_num_prompts:
352
+ generation_config = GenerationConfig(
353
+ max_new_tokens=training_args.max_completion_length,
354
+ do_sample=True,
355
+ temperature=training_args.temperature,
356
+ )
357
+ trainer.add_callback(
358
+ LogCompletionsCallback(trainer, generation_config, num_prompts=script_args.eval_num_prompts)
359
+ )
360
+
361
+ if eval_dataset is not None:
362
+ pre_metrics = _run_accuracy_eval(
363
+ trainer,
364
+ eval_dataset,
365
+ max_new_tokens=script_args.accuracy_eval_max_new_tokens,
366
+ num_examples=script_args.accuracy_eval_num_examples,
367
+ )
368
+ trainer.log_metrics("eval", {f"before_{k}": v for k, v in pre_metrics.items()})
369
+ trainer.save_metrics("eval", {f"before_{k}": v for k, v in pre_metrics.items()})
370
+
371
+ trainer.train()
372
+
373
+ trainer.save_model(training_args.output_dir)
374
+ if eval_dataset is not None:
375
+ post_metrics = _run_accuracy_eval(
376
+ trainer,
377
+ eval_dataset,
378
+ max_new_tokens=script_args.accuracy_eval_max_new_tokens,
379
+ num_examples=script_args.accuracy_eval_num_examples,
380
+ )
381
+ after_metrics = {f"after_{k}": v for k, v in post_metrics.items()}
382
+ delta_metrics = {
383
+ f"delta_{k.split('/', 1)[1]}": after_metrics[f"after_{k}"] - pre_metrics[k] for k in pre_metrics
384
+ }
385
+ trainer.log_metrics("eval", after_metrics | delta_metrics)
386
+ trainer.save_metrics("eval", after_metrics | delta_metrics)
387
+ if training_args.push_to_hub:
388
+ trainer.push_to_hub(dataset_name=script_args.dataset_name or script_args.dataset_path)
tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sft.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ ###############################################################################################
16
+ # This file has been moved to https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py #
17
+ ###############################################################################################
tasks/tasksmith-1fe00f939ab9/tests/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-1fe00f939ab9/tests/source/examples/scripts/sft_gpt_oss.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ attn_implementation=model_args.attn_implementation,
63
+ dtype=model_args.dtype,
64
+ use_cache=False if training_args.gradient_checkpointing else True,
65
+ quantization_config=quantization_config,
66
+ )
67
+
68
+ model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
69
+
70
+ # Load dataset
71
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
72
+
73
+ # Train model
74
+ trainer = SFTTrainer(
75
+ model=model,
76
+ args=training_args,
77
+ train_dataset=dataset[script_args.dataset_train_split],
78
+ eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
79
+ peft_config=get_peft_config(model_args),
80
+ )
81
+
82
+ trainer.train()
83
+ trainer.save_model(training_args.output_dir)
84
+ if training_args.push_to_hub:
85
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
86
+
87
+
88
+ if __name__ == "__main__":
89
+ parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig))
90
+ script_args, training_args, model_args, _ = parser.parse_args_and_config(return_remaining_strings=True)
91
+ main(script_args, training_args, model_args)
tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sft_nemotron_3.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "trl[peft,quantization]",
18
+ # "transformers>=5.7.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.7.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
+
60
+ from trl import ModelConfig, ScriptArguments, SFTConfig, SFTTrainer, TrlParser, get_peft_config
61
+
62
+
63
+ def main(script_args, training_args, model_args):
64
+ training_args.model_init_kwargs = dict(
65
+ revision=model_args.model_revision,
66
+ attn_implementation=model_args.attn_implementation,
67
+ dtype=model_args.dtype,
68
+ )
69
+
70
+ # Load dataset
71
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
72
+
73
+ # Merge thinking into message content using <think> tags and remove extra columns
74
+ def merge_thinking_and_remove_key(example):
75
+ new_messages = []
76
+ for msg in example["messages"]:
77
+ content = msg["content"]
78
+ thinking = msg.get("thinking")
79
+ if thinking and isinstance(thinking, str) and thinking.strip():
80
+ content = f"<think>\n{thinking}\n</think>\n{content}"
81
+ new_messages.append({"role": msg["role"], "content": content})
82
+ example["messages"] = new_messages
83
+ return example
84
+
85
+ dataset = dataset.map(merge_thinking_and_remove_key)
86
+
87
+ # Prepare eval dataset if needed
88
+ eval_dataset = None
89
+ if training_args.eval_strategy != "no" and script_args.dataset_test_split in dataset:
90
+ eval_dataset = dataset[script_args.dataset_test_split]
91
+
92
+ # Train model
93
+ trainer = SFTTrainer(
94
+ model=model_args.model_name_or_path,
95
+ args=training_args,
96
+ train_dataset=dataset[script_args.dataset_train_split],
97
+ eval_dataset=eval_dataset,
98
+ peft_config=get_peft_config(model_args),
99
+ )
100
+
101
+ trainer.train()
102
+ trainer.save_model(training_args.output_dir)
103
+ if training_args.push_to_hub:
104
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
105
+
106
+
107
+ if __name__ == "__main__":
108
+ parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig))
109
+ script_args, training_args, model_args, _ = parser.parse_args_and_config(return_remaining_strings=True)
110
+ main(script_args, training_args, model_args)
tasks/tasksmith-1fe00f939ab9/tests/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-1fe00f939ab9/tests/source/examples/scripts/sft_vlm.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_peft_config,
67
+ get_quantization_config,
68
+ )
69
+
70
+
71
+ if __name__ == "__main__":
72
+ parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig))
73
+ script_args, training_args, model_args = parser.parse_args_and_config()
74
+ training_args.max_length = None
75
+
76
+ ################
77
+ # Model
78
+ ################
79
+ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
80
+ model_kwargs = dict(
81
+ revision=model_args.model_revision,
82
+ attn_implementation=model_args.attn_implementation,
83
+ dtype=dtype,
84
+ )
85
+ quantization_config = get_quantization_config(model_args)
86
+ if quantization_config is not None:
87
+ # Passing None would not be treated the same as omitting the argument, so we include it only when valid.
88
+ model_kwargs["quantization_config"] = quantization_config
89
+
90
+ model = AutoModelForImageTextToText.from_pretrained(model_args.model_name_or_path, **model_kwargs)
91
+
92
+ ################
93
+ # Dataset
94
+ ################
95
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
96
+
97
+ ################
98
+ # Training
99
+ ################
100
+ trainer = SFTTrainer(
101
+ model=model,
102
+ args=training_args,
103
+ train_dataset=dataset[script_args.dataset_train_split],
104
+ eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
105
+ peft_config=get_peft_config(model_args),
106
+ )
107
+
108
+ trainer.train()
109
+
110
+ # Save and push to hub
111
+ trainer.save_model(training_args.output_dir)
112
+ if training_args.push_to_hub:
113
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/sft_vlm_gemma3.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_peft_config,
72
+ get_quantization_config,
73
+ )
74
+
75
+
76
+ # For multi-image example
77
+ def process_vision_info(messages: list[dict]) -> list[Image.Image]:
78
+ image_inputs = []
79
+ for msg in messages:
80
+ content = msg.get("content", [])
81
+ if not isinstance(content, list):
82
+ content = [content]
83
+
84
+ for element in content:
85
+ if isinstance(element, dict) and ("image" in element or element.get("type") == "image"):
86
+ if "image" in element:
87
+ image = element["image"]
88
+ else:
89
+ image = element
90
+ if image is not None:
91
+ image = Image.open(io.BytesIO(image["bytes"]))
92
+ image_inputs.append(image.convert("RGB"))
93
+ return image_inputs
94
+
95
+
96
+ def format_data(samples: dict[str, any]) -> dict[str, list]:
97
+ formatted_samples = {"messages": []}
98
+ for cont in range(len(samples["question"])):
99
+ images = []
100
+ for img_path in samples["input_image_path"][cont]:
101
+ try:
102
+ with open(img_path, "rb") as f:
103
+ img_bytes = f.read()
104
+ image = Image.open(io.BytesIO(img_bytes)).convert("RGB")
105
+ images.append({"type": "image", "image": image})
106
+ except Exception as e:
107
+ print(f"Error processing image {img_path}: {e}")
108
+ continue
109
+
110
+ formatted_samples["messages"].append(
111
+ [
112
+ {"role": "system", "content": [{"type": "text", "text": samples["context"][cont]}]},
113
+ {"role": "user", "content": images + [{"type": "text", "text": samples["question"][cont]}]},
114
+ {"role": "assistant", "content": [{"type": "text", "text": samples["output"][cont]}]},
115
+ ]
116
+ )
117
+ return formatted_samples
118
+
119
+
120
+ # For multi-image example
121
+ def prepare_dataset(dataset: DatasetDict, dataset_name: str) -> DatasetDict:
122
+ all_files = list_repo_files(dataset_name, repo_type="dataset")
123
+ zip_files = [f for f in all_files if f.endswith(".zip")]
124
+
125
+ for zip_filename in zip_files:
126
+ zip_path = hf_hub_download(repo_id=dataset_name, filename=zip_filename, repo_type="dataset")
127
+ extract_folder = zip_filename.replace(".zip", "")
128
+ os.makedirs(extract_folder, exist_ok=True)
129
+
130
+ with zipfile.ZipFile(zip_path, "r") as zip_ref:
131
+ zip_ref.extractall(extract_folder)
132
+
133
+ dataset = dataset.map(format_data, batched=True, batch_size=4, num_proc=16)
134
+ return dataset
135
+
136
+
137
+ def main():
138
+ parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig))
139
+ script_args, training_args, model_args = parser.parse_args_and_config()
140
+ training_args.max_length = None
141
+
142
+ ################
143
+ # Model
144
+ ################
145
+ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
146
+ model_kwargs = dict(
147
+ revision=model_args.model_revision,
148
+ attn_implementation=model_args.attn_implementation,
149
+ dtype=dtype,
150
+ )
151
+ quantization_config = get_quantization_config(model_args)
152
+ if quantization_config is not None:
153
+ # Passing None would not be treated the same as omitting the argument, so we include it only when valid.
154
+ model_kwargs["quantization_config"] = quantization_config
155
+
156
+ model = AutoModelForImageTextToText.from_pretrained(model_args.model_name_or_path, **model_kwargs)
157
+
158
+ ################
159
+ # Dataset
160
+ ################
161
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
162
+ if script_args.dataset_name == "FanqingM/MMIU-Benchmark":
163
+ dataset = prepare_dataset(dataset, script_args.dataset_name)
164
+
165
+ ################
166
+ # Training
167
+ ################
168
+ trainer = SFTTrainer(
169
+ model=model,
170
+ args=training_args,
171
+ train_dataset=dataset[script_args.dataset_train_split],
172
+ eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
173
+ peft_config=get_peft_config(model_args),
174
+ )
175
+
176
+ trainer.train()
177
+
178
+ # Save and push to hub
179
+ trainer.save_model(training_args.output_dir)
180
+ if training_args.push_to_hub:
181
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
182
+
183
+
184
+ if __name__ == "__main__":
185
+ main()
tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/ssd.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # /// script
16
+ # dependencies = [
17
+ # "trl",
18
+ # "peft",
19
+ # "trackio",
20
+ # "kernels",
21
+ # ]
22
+ # ///
23
+
24
+ """
25
+ Simple Self-Distillation (SSD) training for code generation.
26
+
27
+ Implements the method from "Embarrassingly Simple Self-Distillation Improves Code Generation" (Zhang et al., 2026):
28
+ sample completions from the model at a training-time temperature and truncation, then fine-tune on those raw,
29
+ unverified samples with standard cross-entropy loss. No reward model, verifier, teacher, or RL needed.
30
+
31
+ The dataset only requires a ``prompt`` column containing coding problem prompts.
32
+
33
+ Example:
34
+
35
+ ```bash
36
+ python examples/scripts/ssd.py \
37
+ --model_name_or_path Qwen/Qwen3-4B-Instruct-2507 \
38
+ --dataset_name microsoft/rStar-Coder \
39
+ --dataset_config seed_sft \
40
+ --prompt_column question \
41
+ --output_dir outputs/ssd-qwen3-4b \
42
+ --per_device_train_batch_size 1 \
43
+ --gradient_accumulation_steps 32 \
44
+ --learning_rate 5e-6 \
45
+ --lr_scheduler_type cosine \
46
+ --max_prompt_length 1024 \
47
+ --max_completion_length 65536 \
48
+ --temperature 1.6 \
49
+ --top_k 20 \
50
+ --top_p 0.8 \
51
+ --num_train_epochs 1 \
52
+ --bf16 \
53
+ --report_to trackio
54
+ ```
55
+ """
56
+
57
+ from dataclasses import dataclass, field
58
+
59
+ import torch
60
+ from datasets import DatasetDict, load_dataset, load_from_disk
61
+ from transformers import AutoModelForCausalLM, AutoTokenizer
62
+
63
+ from trl import ModelConfig, ScriptArguments, TrlParser, get_peft_config, get_quantization_config
64
+ from trl.experimental.ssd import SSDConfig, SSDTrainer
65
+
66
+
67
+ @dataclass
68
+ class SSDScriptArguments(ScriptArguments):
69
+ dataset_path: str | None = field(
70
+ default=None,
71
+ metadata={"help": "Optional local dataset path to load with `load_from_disk`. Overrides `dataset_name`."},
72
+ )
73
+ prompt_column: str = field(
74
+ default="prompt",
75
+ metadata={"help": "Column containing the problem prompts."},
76
+ )
77
+
78
+
79
+ if __name__ == "__main__":
80
+ parser = TrlParser((SSDScriptArguments, SSDConfig, ModelConfig))
81
+ script_args, training_args, model_args = parser.parse_args_and_config()
82
+
83
+ if model_args.model_name_or_path is None:
84
+ raise ValueError("`model_name_or_path` is required.")
85
+
86
+ if model_args.dtype in ["auto", None]:
87
+ if training_args.bf16:
88
+ dtype = torch.bfloat16
89
+ elif training_args.fp16:
90
+ dtype = torch.float16
91
+ else:
92
+ dtype = "auto"
93
+ else:
94
+ dtype = getattr(torch, model_args.dtype)
95
+ model_kwargs = dict(
96
+ revision=model_args.model_revision,
97
+ attn_implementation=model_args.attn_implementation,
98
+ dtype=dtype,
99
+ )
100
+ quantization_config = get_quantization_config(model_args)
101
+ if quantization_config is not None:
102
+ model_kwargs["quantization_config"] = quantization_config
103
+
104
+ training_args.model_init_kwargs = model_kwargs
105
+
106
+ tokenizer = AutoTokenizer.from_pretrained(
107
+ model_args.model_name_or_path, revision=model_args.model_revision, padding_side="left"
108
+ )
109
+ if tokenizer.pad_token is None:
110
+ tokenizer.pad_token = tokenizer.eos_token
111
+
112
+ # Load dataset
113
+ if script_args.dataset_path is not None:
114
+ dataset = load_from_disk(script_args.dataset_path)
115
+ else:
116
+ dataset = load_dataset(
117
+ script_args.dataset_name,
118
+ name=script_args.dataset_config,
119
+ streaming=script_args.dataset_streaming,
120
+ )
121
+
122
+ # Ensure the dataset has a `prompt` column
123
+ def _prepare_split(ds):
124
+ if script_args.prompt_column != "prompt" and script_args.prompt_column in ds.column_names:
125
+ ds = ds.rename_column(script_args.prompt_column, "prompt")
126
+ return ds.select_columns(["prompt"])
127
+
128
+ if isinstance(dataset, DatasetDict):
129
+ train_dataset = _prepare_split(dataset[script_args.dataset_train_split])
130
+ eval_dataset = None
131
+ if script_args.dataset_test_split in dataset:
132
+ eval_dataset = _prepare_split(dataset[script_args.dataset_test_split])
133
+ else:
134
+ train_dataset = _prepare_split(dataset)
135
+ eval_dataset = None
136
+
137
+ model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
138
+ model.config.use_cache = False if training_args.gradient_checkpointing else True
139
+
140
+ trainer = SSDTrainer(
141
+ model=model,
142
+ args=training_args,
143
+ train_dataset=train_dataset,
144
+ eval_dataset=eval_dataset,
145
+ processing_class=tokenizer,
146
+ peft_config=get_peft_config(model_args),
147
+ )
148
+
149
+ trainer.train()
150
+
151
+ trainer.save_model(training_args.output_dir)
152
+ if eval_dataset is not None:
153
+ metrics = trainer.evaluate()
154
+ trainer.log_metrics("eval", metrics)
155
+ trainer.save_metrics("eval", metrics)
156
+
157
+ if training_args.push_to_hub:
158
+ trainer.push_to_hub(dataset_name=script_args.dataset_name or script_args.dataset_path)
tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/ssd_eval.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # "vllm",
19
+ # "huggingface_hub",
20
+ # "livecodebench @ git+https://github.com/LiveCodeBench/LiveCodeBench.git",
21
+ # ]
22
+ # ///
23
+
24
+ """
25
+ LiveCodeBench v6 evaluation script.
26
+
27
+ Generates completions with vLLM at a configurable decoding setting and scores them with LiveCodeBench's official
28
+ ``codegen_metrics`` (pass@k via sandboxed test execution). The default decoding configuration matches Table 3 of
29
+ *Embarrassingly Simple Self-Distillation Improves Code Generation* (Zhang et al., 2026), making this script suitable
30
+ for evaluating SSD-trained checkpoints alongside their base models.
31
+
32
+ Example — evaluate the base Qwen3-4B-Instruct-2507 on the v6 delta (the new problems released in v6):
33
+
34
+ ```bash
35
+ python examples/scripts/ssd_eval.py \\
36
+ --model_name_or_path Qwen/Qwen3-4B-Instruct-2507 \\
37
+ --temperature 1.1 \\
38
+ --top_k 20 \\
39
+ --top_p 0.8 \\
40
+ --n 1 \\
41
+ --output_file outputs/qwen3_4b_base_lcb_v6.json
42
+ ```
43
+
44
+ Evaluate an SSD-trained checkpoint with the same decoding configuration:
45
+
46
+ ```bash
47
+ python examples/scripts/ssd_eval.py \\
48
+ --model_name_or_path outputs/ssd-qwen3-4b-instruct \\
49
+ --temperature 1.1 \\
50
+ --top_k 20 \\
51
+ --top_p 0.8 \\
52
+ --n 5 \\
53
+ --output_file outputs/qwen3_4b_ssd_lcb_v6.json
54
+ ```
55
+ """
56
+
57
+ # ruff: noqa: T201
58
+
59
+ from __future__ import annotations
60
+
61
+ import json
62
+ import re
63
+ from dataclasses import dataclass, field
64
+ from datetime import datetime
65
+
66
+ from huggingface_hub import hf_hub_download
67
+ from lcb_runner.benchmarks.code_generation import CodeGenerationProblem
68
+ from lcb_runner.evaluation.compute_code_generation_metrics import codegen_metrics
69
+ from transformers import AutoTokenizer
70
+ from vllm import LLM, SamplingParams
71
+
72
+ from trl import TrlParser
73
+
74
+
75
+ # LiveCodeBench stores new problems added in each release version in a separate JSONL file:
76
+ # ``test.jsonl`` = v1, ``test2.jsonl`` = v2, …, ``test6.jsonl`` = v6 (the delta added in release v6).
77
+ # The paper's "LCB v6" refers to exactly this delta.
78
+ LCB_REPO = "livecodebench/code_generation_lite"
79
+ LCB_V6_FILE = "test6.jsonl"
80
+
81
+
82
+ SYSTEM_MESSAGE = (
83
+ "You are an expert Python programmer. You will be given a question (problem specification) and will "
84
+ "generate a correct Python program that matches the specification and passes all tests."
85
+ )
86
+ FORMATTING_WITHOUT_STARTER = (
87
+ "Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on "
88
+ "the sample inputs). Enclose your code within delimiters as follows. Ensure that when the python "
89
+ "program runs, it reads the inputs, runs the algorithm and writes output to STDOUT."
90
+ )
91
+ FORMATTING_WITH_STARTER = (
92
+ "You will use the following starter code to write the solution to the problem and enclose your code "
93
+ "within delimiters."
94
+ )
95
+
96
+ CODE_FENCE_RE = re.compile(r"```(?:python)?\s*\n(.*?)```", re.DOTALL)
97
+
98
+
99
+ @dataclass
100
+ class SSDEvalArguments:
101
+ model_name_or_path: str = field(metadata={"help": "Model path or Hub repo id to evaluate."})
102
+ output_file: str = field(metadata={"help": "Path to write generations + metrics JSON."})
103
+ temperature: float = field(default=1.1, metadata={"help": "Evaluation-time sampling temperature (T_eval)."})
104
+ top_k: int = field(default=20, metadata={"help": "Evaluation-time top-k truncation."})
105
+ top_p: float = field(default=0.8, metadata={"help": "Evaluation-time top-p (nucleus) truncation."})
106
+ n: int = field(default=1, metadata={"help": "Number of samples per problem (pass@1 uses 1, pass@5 uses 5)."})
107
+ max_tokens: int = field(default=32768, metadata={"help": "Maximum tokens to generate per completion."})
108
+ max_model_len: int = field(default=65536, metadata={"help": "vLLM max model length."})
109
+ gpu_memory_utilization: float = field(default=0.9, metadata={"help": "vLLM GPU memory ratio."})
110
+ tensor_parallel_size: int = field(default=1, metadata={"help": "vLLM tensor parallel size."})
111
+ dtype: str = field(default="bfloat16", metadata={"help": "vLLM model dtype."})
112
+ start_date: str | None = field(
113
+ default=None, metadata={"help": "Keep only problems with contest_date >= YYYY-MM-DD."}
114
+ )
115
+ end_date: str | None = field(
116
+ default=None, metadata={"help": "Keep only problems with contest_date <= YYYY-MM-DD."}
117
+ )
118
+ max_problems: int | None = field(
119
+ default=None, metadata={"help": "Evaluate at most N problems (useful for quick smoke tests)."}
120
+ )
121
+ difficulty: str | None = field(
122
+ default=None, metadata={"help": "Filter to a single difficulty: 'easy', 'medium', or 'hard'."}
123
+ )
124
+ timeout: int = field(default=6, metadata={"help": "Per-test execution timeout in seconds."})
125
+ num_process_evaluate: int = field(default=8, metadata={"help": "Parallel processes for sandboxed evaluation."})
126
+ seed: int = field(default=0, metadata={"help": "vLLM sampling seed."})
127
+
128
+
129
+ def _build_prompt(tokenizer, question_content: str, starter_code: str) -> str:
130
+ """Build the LCB prompt and apply the model's chat template."""
131
+ body = f"### Question:\n{question_content}\n\n"
132
+ if starter_code:
133
+ body += f"### Format: {FORMATTING_WITH_STARTER}\n"
134
+ body += f"```python\n{starter_code}\n```\n\n"
135
+ else:
136
+ body += f"### Format: {FORMATTING_WITHOUT_STARTER}\n"
137
+ body += "```python\n# YOUR CODE HERE\n```\n\n"
138
+ body += "### Answer: (use the provided format with backticks)\n\n"
139
+ messages = [
140
+ {"role": "system", "content": SYSTEM_MESSAGE},
141
+ {"role": "user", "content": body},
142
+ ]
143
+ return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
144
+
145
+
146
+ def _extract_code(text: str) -> str:
147
+ """Extract the first Python code fence from a model completion."""
148
+ match = CODE_FENCE_RE.search(text)
149
+ if match:
150
+ return match.group(1).strip()
151
+ # Fallback: if the model returned bare code without a fence, return the whole thing.
152
+ return text.strip()
153
+
154
+
155
+ def _load_lcb_v6_problems(args: SSDEvalArguments):
156
+ """Load LiveCodeBench v6 problems, filter by date/difficulty/count, and return as a list."""
157
+ jsonl_path = hf_hub_download(repo_id=LCB_REPO, filename=LCB_V6_FILE, repo_type="dataset")
158
+ with open(jsonl_path) as f:
159
+ problems = [CodeGenerationProblem(**json.loads(line)) for line in f]
160
+
161
+ if args.start_date is not None:
162
+ start = datetime.fromisoformat(args.start_date)
163
+ problems = [p for p in problems if p.contest_date >= start]
164
+ if args.end_date is not None:
165
+ end = datetime.fromisoformat(args.end_date)
166
+ problems = [p for p in problems if p.contest_date <= end]
167
+ if args.difficulty is not None:
168
+ problems = [p for p in problems if p.difficulty.value == args.difficulty]
169
+ if args.max_problems is not None:
170
+ problems = problems[: args.max_problems]
171
+
172
+ return problems
173
+
174
+
175
+ def main():
176
+ parser = TrlParser(SSDEvalArguments)
177
+ (args,) = parser.parse_args_and_config()
178
+
179
+ problems = _load_lcb_v6_problems(args)
180
+ print(f"Evaluating {len(problems)} problems from LiveCodeBench v6")
181
+
182
+ tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
183
+ prompts = [_build_prompt(tokenizer, p.question_content, p.starter_code) for p in problems]
184
+
185
+ llm = LLM(
186
+ model=args.model_name_or_path,
187
+ dtype=args.dtype,
188
+ tensor_parallel_size=args.tensor_parallel_size,
189
+ max_model_len=args.max_model_len,
190
+ gpu_memory_utilization=args.gpu_memory_utilization,
191
+ )
192
+ sampling_params = SamplingParams(
193
+ n=args.n,
194
+ temperature=args.temperature,
195
+ top_k=args.top_k,
196
+ top_p=args.top_p,
197
+ max_tokens=args.max_tokens,
198
+ seed=args.seed,
199
+ )
200
+ outputs = llm.generate(prompts, sampling_params)
201
+
202
+ generations_list = []
203
+ for out in outputs:
204
+ code_list = [_extract_code(o.text) for o in out.outputs]
205
+ generations_list.append(code_list)
206
+
207
+ samples_list = [p.get_evaluation_sample() for p in problems]
208
+ k_list = [1] if args.n == 1 else [1, args.n]
209
+ metrics, results, _metadata = codegen_metrics(
210
+ samples_list,
211
+ generations_list,
212
+ k_list=k_list,
213
+ num_process_evaluate=args.num_process_evaluate,
214
+ timeout=args.timeout,
215
+ )
216
+
217
+ # Break down pass@1 by difficulty for easier comparison with the paper's tables. `codegen_metrics`
218
+ # returns a nested `detail` dict keyed by problem index.
219
+ per_problem_pass1 = metrics["detail"]["pass@1"]
220
+ per_difficulty = {}
221
+ for difficulty in ("easy", "medium", "hard"):
222
+ idxs = [i for i, p in enumerate(problems) if p.difficulty.value == difficulty]
223
+ if not idxs:
224
+ continue
225
+ per_difficulty[difficulty] = {
226
+ "num_problems": len(idxs),
227
+ "pass@1": sum(per_problem_pass1[i] for i in idxs) / len(idxs),
228
+ }
229
+
230
+ summary = {
231
+ "model": args.model_name_or_path,
232
+ "num_problems": len(problems),
233
+ "temperature": args.temperature,
234
+ "top_k": args.top_k,
235
+ "top_p": args.top_p,
236
+ "n": args.n,
237
+ "metrics": {k: float(v) for k, v in metrics.items() if k != "detail"},
238
+ "per_difficulty": per_difficulty,
239
+ }
240
+
241
+ detail = [
242
+ {
243
+ "question_id": p.question_id,
244
+ "difficulty": p.difficulty.value,
245
+ "code_list": code_list,
246
+ "pass@1": per_problem_pass1[i],
247
+ }
248
+ for i, (p, code_list) in enumerate(zip(problems, generations_list, strict=False))
249
+ ]
250
+
251
+ with open(args.output_file, "w") as f:
252
+ json.dump({"summary": summary, "detail": detail}, f, indent=2)
253
+
254
+ print("\n=== Summary ===")
255
+ print(json.dumps(summary, indent=2))
256
+ print(f"\nFull results written to {args.output_file}")
257
+
258
+
259
+ if __name__ == "__main__":
260
+ main()
tasks/tasksmith-1fe00f939ab9/tests/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-1fe00f939ab9/tests/source/examples/scripts/tpo.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # "trackio",
19
+ # "kernels",
20
+ # ]
21
+ # ///
22
+
23
+ """
24
+ Triple Preference Optimization (TPO) training.
25
+
26
+ TPO requires a *triple-preference* dataset where each example contains a `chosen`, a `rejected` and a `reference`
27
+ (gold) completion for the same prompt. Two dataset paths are supported out of the box:
28
+
29
+ - Use the published
30
+ [`tpo-alignment/triple-preference-ultrafeedback-40K`](https://huggingface.co/datasets/tpo-alignment/triple-preference-ultrafeedback-40K)
31
+ dataset directly. It already has the `prompt` / `reference` / `chosen` / `rejected` schema.
32
+ - Pass `--dataset_name openbmb/UltraFeedback` and the script automatically builds the triple-preference dataset as
33
+ described in the TPO paper (Saeidi et al., 2025): the response with the highest `overall_score` becomes `reference`,
34
+ the second-highest becomes `chosen`, and the lowest becomes `rejected`.
35
+
36
+ In both cases, if the dataset is in standard (plain-string) format it is auto-wrapped into the conversational format so
37
+ that the model's chat template is applied — this matches how Instruct models like `Qwen/Qwen3-0.6B` are trained.
38
+
39
+ Usage:
40
+
41
+ Full training:
42
+
43
+ ```bash
44
+ python examples/scripts/tpo.py \
45
+ --dataset_name tpo-alignment/triple-preference-ultrafeedback-40K \
46
+ --model_name_or_path Qwen/Qwen3-0.6B \
47
+ --per_device_train_batch_size 2 \
48
+ --max_steps 1000 \
49
+ --learning_rate 5e-7 \
50
+ --gradient_accumulation_steps 8 \
51
+ --beta 0.01 \
52
+ --tpo_alpha 1.0 \
53
+ --output_dir Qwen3-0.6B-TPO \
54
+ --no_remove_unused_columns
55
+ ```
56
+
57
+ TPO-L (length-normalized variant with target reward margin):
58
+
59
+ ```bash
60
+ python examples/scripts/tpo.py \
61
+ --dataset_name tpo-alignment/triple-preference-ultrafeedback-40K \
62
+ --model_name_or_path Qwen/Qwen3-0.6B \
63
+ --per_device_train_batch_size 2 \
64
+ --max_steps 1000 \
65
+ --learning_rate 5e-7 \
66
+ --gradient_accumulation_steps 8 \
67
+ --beta 0.01 \
68
+ --tpo_alpha 1.0 \
69
+ --loss_type tpo-l \
70
+ --tpo_l_gamma 0.5 \
71
+ --output_dir Qwen3-0.6B-TPO-L \
72
+ --no_remove_unused_columns
73
+ ```
74
+
75
+ LoRA:
76
+
77
+ ```bash
78
+ python examples/scripts/tpo.py \
79
+ --dataset_name tpo-alignment/triple-preference-ultrafeedback-40K \
80
+ --model_name_or_path Qwen/Qwen3-0.6B \
81
+ --per_device_train_batch_size 2 \
82
+ --max_steps 1000 \
83
+ --learning_rate 5e-6 \
84
+ --gradient_accumulation_steps 8 \
85
+ --output_dir Qwen3-0.6B-TPO-LoRA \
86
+ --no_remove_unused_columns \
87
+ --use_peft \
88
+ --lora_r 32 \
89
+ --lora_alpha 16
90
+ ```
91
+ """
92
+
93
+ import torch
94
+ from datasets import load_dataset
95
+ from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
96
+
97
+ from trl import ModelConfig, ScriptArguments, get_peft_config, get_quantization_config
98
+ from trl.experimental.tpo import TPOConfig, TPOTrainer
99
+
100
+
101
+ def build_triple_preference_from_ultrafeedback(example):
102
+ """
103
+ Build a TPO triple-preference example from a raw UltraFeedback row.
104
+
105
+ Following the TPO paper (Saeidi et al., 2025), completions are sorted by `overall_score` and we pick:
106
+ - the highest-scored response as the gold `reference`,
107
+ - the second-highest as `chosen`,
108
+ - the lowest as `rejected`.
109
+
110
+ Emits the *conversational* format so that [`TPOTrainer`] applies the model's chat template automatically (see
111
+ `trl.data_utils.is_conversational`). Completions with a missing `overall_score` or `response` are filtered out; if
112
+ fewer than 3 valid completions remain, the returned example contains `None` values and should be filtered out
113
+ downstream.
114
+ """
115
+ scored = [c for c in example["completions"] if c.get("overall_score") is not None and c.get("response")]
116
+ if len(scored) < 3:
117
+ return {"prompt": None, "reference": None, "chosen": None, "rejected": None}
118
+ scored.sort(key=lambda c: c["overall_score"], reverse=True)
119
+ return {
120
+ "prompt": [{"role": "user", "content": example["instruction"]}],
121
+ "reference": [{"role": "assistant", "content": scored[0]["response"]}],
122
+ "chosen": [{"role": "assistant", "content": scored[1]["response"]}],
123
+ "rejected": [{"role": "assistant", "content": scored[-1]["response"]}],
124
+ }
125
+
126
+
127
+ def to_conversational(example):
128
+ """
129
+ Wrap a standard-format triple-preference example (plain strings) in the *conversational* format, so that
130
+ [`TPOTrainer`] applies the model's chat template automatically. This is the format expected by Instruct models; for
131
+ non-Instruct base models the standard format can be used directly.
132
+ """
133
+ return {
134
+ "prompt": [{"role": "user", "content": example["prompt"]}],
135
+ "reference": [{"role": "assistant", "content": example["reference"]}],
136
+ "chosen": [{"role": "assistant", "content": example["chosen"]}],
137
+ "rejected": [{"role": "assistant", "content": example["rejected"]}],
138
+ }
139
+
140
+
141
+ if __name__ == "__main__":
142
+ parser = HfArgumentParser((ScriptArguments, TPOConfig, ModelConfig))
143
+ script_args, training_args, model_args = parser.parse_args_into_dataclasses()
144
+
145
+ ################
146
+ # Model & Tokenizer
147
+ ################
148
+ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
149
+ model_kwargs = dict(
150
+ revision=model_args.model_revision,
151
+ attn_implementation=model_args.attn_implementation,
152
+ dtype=dtype,
153
+ )
154
+ quantization_config = get_quantization_config(model_args)
155
+ if quantization_config is not None:
156
+ model_kwargs["quantization_config"] = quantization_config
157
+
158
+ model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
159
+ tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path)
160
+ if tokenizer.pad_token is None:
161
+ tokenizer.pad_token = tokenizer.eos_token
162
+
163
+ ################
164
+ # Dataset
165
+ ################
166
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
167
+
168
+ # Auto-build the triple-preference schema from raw UltraFeedback.
169
+ first_example = next(iter(dataset[script_args.dataset_train_split]))
170
+ if "completions" in first_example and "instruction" in first_example:
171
+ dataset = dataset.map(
172
+ build_triple_preference_from_ultrafeedback,
173
+ remove_columns=list(first_example.keys()),
174
+ )
175
+ dataset = dataset.filter(lambda ex: ex["reference"] is not None)
176
+ first_example = next(iter(dataset[script_args.dataset_train_split]))
177
+
178
+ # Auto-wrap standard-format triple-preference data (plain strings) into conversational messages so the
179
+ # model's chat template gets applied. This matches how Instruct models are trained and is what the TPO
180
+ # paper's data preparation produces.
181
+ if {"prompt", "chosen", "rejected", "reference"}.issubset(first_example) and isinstance(
182
+ first_example["prompt"], str
183
+ ):
184
+ dataset = dataset.map(to_conversational)
185
+
186
+ ################
187
+ # Training
188
+ ################
189
+ trainer = TPOTrainer(
190
+ model,
191
+ args=training_args,
192
+ train_dataset=dataset[script_args.dataset_train_split],
193
+ eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
194
+ processing_class=tokenizer,
195
+ peft_config=get_peft_config(model_args),
196
+ )
197
+
198
+ # train and save the model
199
+ trainer.train()
200
+
201
+ # Run a final evaluation pass and persist the metrics
202
+ if training_args.eval_strategy != "no":
203
+ metrics = trainer.evaluate()
204
+ trainer.log_metrics("eval", metrics)
205
+ trainer.save_metrics("eval", metrics)
206
+
207
+ # Save and push to hub
208
+ trainer.save_model(training_args.output_dir)
209
+ if training_args.push_to_hub:
210
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
tasks/tasksmith-1fe00f939ab9/tests/source/examples/scripts/xpo.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 LogCompletionsCallback, ModelConfig, ScriptArguments, TrlParser, get_quantization_config
46
+ from trl.experimental.xpo import XPOConfig, XPOTrainer
47
+
48
+
49
+ if __name__ == "__main__":
50
+ parser = TrlParser((ScriptArguments, XPOConfig, ModelConfig))
51
+ script_args, training_args, model_args = parser.parse_args_and_config()
52
+ training_args.gradient_checkpointing_kwargs = {"use_reentrant": True}
53
+
54
+ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
55
+ model_kwargs = dict(
56
+ revision=model_args.model_revision,
57
+ attn_implementation=model_args.attn_implementation,
58
+ dtype=dtype,
59
+ use_cache=False if training_args.gradient_checkpointing else True,
60
+ )
61
+ quantization_config = get_quantization_config(model_args)
62
+ if quantization_config is not None:
63
+ # Passing None would not be treated the same as omitting the argument, so we include it only when valid.
64
+ model_kwargs["quantization_config"] = quantization_config
65
+
66
+ model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
67
+ ref_model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
68
+
69
+ if training_args.reward_model_path is not None:
70
+ reward_model = AutoModelForSequenceClassification.from_pretrained(
71
+ training_args.reward_model_path,
72
+ num_labels=1,
73
+ **model_kwargs,
74
+ )
75
+ else:
76
+ reward_model = None
77
+
78
+ tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, padding_side="left")
79
+ if tokenizer.pad_token is None:
80
+ tokenizer.pad_token = tokenizer.eos_token
81
+
82
+ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
83
+
84
+ trainer = XPOTrainer(
85
+ model=model,
86
+ ref_model=ref_model,
87
+ reward_funcs=reward_model,
88
+ args=training_args,
89
+ train_dataset=dataset[script_args.dataset_train_split],
90
+ eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
91
+ processing_class=tokenizer,
92
+ )
93
+
94
+ if training_args.eval_strategy != "no":
95
+ generation_config = GenerationConfig(
96
+ max_new_tokens=training_args.max_new_tokens, do_sample=True, temperature=training_args.temperature
97
+ )
98
+ completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8)
99
+ trainer.add_callback(completions_callback)
100
+
101
+ trainer.train()
102
+
103
+ # Save and push to hub
104
+ trainer.save_model(training_args.output_dir)
105
+ if training_args.push_to_hub:
106
+ trainer.push_to_hub(dataset_name=script_args.dataset_name)
tasks/tasksmith-1fe00f939ab9/tests/source/pyproject.toml ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ kernels = [ # transformers renamed the "hub-kernels" extra to "kernels" in 5.1.0
56
+ "transformers[kernels]", # transformers >= 5.1.0
57
+ "transformers[hub-kernels]", # transformers < 5.1.0
58
+ ]
59
+ liger = [
60
+ "liger-kernel>=0.8.0"
61
+ ]
62
+ peft = [
63
+ "peft>=0.8.0"
64
+ ]
65
+ quality = [
66
+ "pre-commit",
67
+ "hf-doc-builder"
68
+ ]
69
+ quantization = [
70
+ "bitsandbytes"
71
+ ]
72
+ scikit = [
73
+ "scikit-learn"
74
+ ]
75
+ test = [
76
+ "pytest-cov",
77
+ "pytest-datadir>=1.7.0", # lazy datadirs
78
+ "pytest-rerunfailures==15.1",
79
+ "pytest-xdist",
80
+ "pytest"
81
+ ]
82
+ vllm = [
83
+ "vllm>=0.15.0,<=0.23.0",
84
+ "fastapi",
85
+ "pydantic",
86
+ "aiohttp>=3.13.3",
87
+ "requests",
88
+ "uvicorn"
89
+ ]
90
+ vlm = [
91
+ "Pillow",
92
+ "torchvision",
93
+ "num2words==0.5.14"
94
+ ]
95
+ math_verify = [
96
+ "math-verify>=0.5.2",
97
+ ]
98
+ openreward = [
99
+ "openreward>=0.1.109; python_version >= '3.11'", # openreward requires Python 3.11+
100
+ ]
101
+ harbor = [
102
+ "harbor>=0.13.0; python_version >= '3.12'", # harbor requires Python 3.12+ (pulls its sandbox backends)
103
+ ]
104
+ dev = [
105
+ # bco
106
+ "scikit-learn",
107
+ "joblib",
108
+ # deepspeed
109
+ "deepspeed>=0.14.4",
110
+ # kernels: transformers renamed the "hub-kernels" extra to "kernels" in 5.1.0
111
+ "transformers[kernels]", # transformers >= 5.1.0
112
+ "transformers[hub-kernels]", # transformers < 5.1.0
113
+ # liger
114
+ "liger-kernel>=0.8.0",
115
+ # openreward (requires Python 3.11+)
116
+ "openreward>=0.1.109; python_version >= '3.11'",
117
+ # peft
118
+ "peft>=0.8.0",
119
+ # quality
120
+ "pre-commit",
121
+ "hf-doc-builder",
122
+ # quantization
123
+ "bitsandbytes",
124
+ # scikit: included in bco
125
+ # test
126
+ "pytest-cov",
127
+ "pytest-datadir>=1.7.0", # lazy datadirs
128
+ "pytest-rerunfailures==15.1",
129
+ "pytest-xdist",
130
+ "pytest",
131
+ # vllm: not included in dev by default due to CUDA error; see GH-4228
132
+ # vlm
133
+ "Pillow",
134
+ "torchvision",
135
+ "num2words==0.5.14",
136
+ # for response parsing (required for training with tools)
137
+ "jmespath",
138
+ ]
139
+
140
+ [tool.setuptools]
141
+ package-dir = {"trl" = "trl"}
142
+
143
+ [tool.setuptools.dynamic]
144
+ version = { file = "VERSION" }
145
+
146
+ [tool.coverage.run]
147
+ branch = true
148
+
149
+ [tool.ruff]
150
+ target-version = "py310"
151
+ line-length = 119
152
+ src = ["trl"]
153
+
154
+ [tool.ruff.lint]
155
+ ignore = [
156
+ "B028", # warning without explicit stacklevel
157
+ "C408", # dict() calls (stylistic)
158
+ "C901", # function complexity
159
+ "E501",
160
+ ]
161
+ extend-select = ["E", "F", "I", "W", "UP", "B", "T", "C"]
162
+
163
+ [tool.ruff.lint.per-file-ignores]
164
+ # Allow prints in auxiliary scripts
165
+ "examples/**.py" = ["T201"]
166
+ "scripts/**.py" = ["T201"]
167
+ "trl/cli/**.py" = ["T201"]
168
+ "trl/skills/cli.py" = ["T201"]
169
+ # Ignore import violations in all `__init__.py` files.
170
+ "__init__.py" = ["F401"]
171
+
172
+ [tool.ruff.lint.isort]
173
+ lines-after-imports = 2
174
+ known-first-party = ["trl"]
175
+
176
+ [tool.pytest.ini_options]
177
+ markers = [
178
+ "slow: marks tests as slow (deselect with '-m \"not slow\"')",
179
+ "low_priority: marks tests as low priority (deselect with '-m \"not low_priority\"')",
180
+ "invariant: training-invariant checks (run with '-m invariant')",
181
+ ]
182
+ norecursedirs = [
183
+ "tests/experimental",
184
+ "tests/invariant",
185
+ ]
186
+ filterwarnings = [
187
+ # SWIG deprecations from SWIG-generated C/C++ extensions: sentencepiece
188
+ # Upstream issue: https://github.com/google/sentencepiece/issues/1150
189
+ "ignore:builtin type SwigPyPacked has no __module__ attribute:DeprecationWarning",
190
+ "ignore:builtin type SwigPyObject has no __module__ attribute:DeprecationWarning",
191
+ "ignore:builtin type swigvarlink has no __module__ attribute:DeprecationWarning",
192
+
193
+ # PyTorch JIT deprecations (upstream, not actionable in TRL)
194
+ # Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/7835
195
+ # Upstream PR: https://github.com/deepspeedai/DeepSpeed/pull/7840
196
+ # Upstream fix released in deepspeed v0.18.6: https://github.com/deepspeedai/DeepSpeed/releases/tag/v0.18.6
197
+ "ignore:`torch.jit.script_method` is deprecated:DeprecationWarning",
198
+ "ignore:`torch.jit.script` is deprecated:DeprecationWarning",
199
+
200
+ # PyTorch DataLoader pin_memory device argument deprecations
201
+ # Triggered internally by torch.utils.data, not by our code
202
+ # Upstream issue: https://github.com/pytorch/pytorch/issues/174546
203
+ "ignore:The argument 'device' of Tensor.pin_memory:DeprecationWarning",
204
+ "ignore:The argument 'device' of Tensor.is_pinned:DeprecationWarning",
205
+ ]
tasks/tasksmith-1fe00f939ab9/tests/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-1fe00f939ab9/tests/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-1fe00f939ab9/tests/source/scripts/generate_tiny_models/README.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tiny model generation
2
+
3
+ This directory contains one script per tiny model used by the TRL test suite. Each script builds a random-weight, minimally-sized model on top of a real tokenizer/processor and pushes it to the `trl-internal-testing` organization on the Hub.
4
+
5
+ ## Layout
6
+
7
+ ```
8
+ generate_tiny_models/
9
+ ├── _common.py # shared helpers (push_to_hub, smoke_test, print_config_diff, ...)
10
+ ├── for_causal_lm/ # *ForCausalLM + GPT-2 LM head + small/PEFT variants
11
+ ├── for_sequence_classification/ # *ForSequenceClassification (reward models)
12
+ └── for_conditional_generation/ # *ForConditionalGeneration (VLMs + T5 + Bart encoder-decoder)
13
+ ```
14
+
15
+ ## Running
16
+
17
+ From the repo root, invoke a script by its module path:
18
+
19
+ ```bash
20
+ python -m scripts.generate_tiny_models.for_causal_lm.qwen3_for_causal_lm
21
+ ```
22
+
23
+ Each script:
24
+
25
+ 1. Checks that the installed `transformers` version matches the one pinned in the script (fails otherwise).
26
+ 2. Builds the tiny model with random weights.
27
+ 3. Runs `smoke_test` — a minimal forward pass to catch config misspecification and NaNs.
28
+ 4. Runs `check_dtype_pattern` — reads the reference safetensors header via the Hub API and flags any tensor whose dtype diverges from the reference (catches e.g. fp32 norms kept inside a bf16 checkpoint).
29
+ 5. Runs `print_config_diff` — prints every flat-key difference between the reference Hub config and the tiny model's config (for debugging scale-downs).
30
+ 6. Pushes the model, tokenizer/processor, generation config, and model card to the Hub in a single commit.
31
+
32
+ If the repo already exists on the Hub, the push is skipped by default. Pass `--create-pr` to open a PR against the existing repo instead:
33
+
34
+ ```bash
35
+ python -m scripts.generate_tiny_models.for_causal_lm.qwen3_for_causal_lm --create-pr
36
+ ```
37
+
38
+ Direct overwrites of `main` aren't supported — update via `--create-pr` and merge the PR on the Hub.
39
+
40
+ ## Version pinning
41
+
42
+ Each script calls `check_transformers_version(...)`, which enforces:
43
+
44
+ ```
45
+ max(version that introduced the model, TRL's transformers floor)
46
+ ```
47
+
48
+ By default — `check_transformers_version()` with no argument — the expected version is the `transformers>=` floor read from `pyproject.toml` (currently `4.56.2`). Scripts for models introduced after the floor pass an explicit pin, e.g. `check_transformers_version("4.57.0")` for Qwen3-VL or `check_transformers_version("5.6.0")` for Gemma4. The check is an exact match via `packaging.version.Version`; install the matching version before running.
49
+
50
+ **Why exact?** transformers is backward-compatible (a checkpoint saved by X loads on any ≥ X) but not forward-compatible. TRL CI runs against the floor, so tiny models must be saved with the oldest version that supports them — any newer save risks using config fields the floor can't parse. The exact-match check prevents accidental drift.
51
+
52
+ ## Adding a new tiny model
53
+
54
+ 1. Pick the right subfolder based on the model class suffix (`ForCausalLM`, `ForSequenceClassification`, `ForConditionalGeneration`).
55
+ 2. Copy an existing script with the closest shape and adapt it — reference model id, config class, model class, special kwargs.
56
+ 3. If the model requires a release newer than the TRL floor, pass it explicitly: `check_transformers_version("X.Y.Z")`. Otherwise leave the call argument-less to default to the floor.
57
+ 4. Run it. Inspect the `[smoke_test]` and `[config_diff]` output before letting it push.
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/_common.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Shared utilities for the tiny-model generation scripts in this directory.
16
+ # Each sibling script builds a single tiny model and pushes it to the Hub under
17
+ # the `trl-internal-testing` organization.
18
+
19
+ import argparse
20
+ import os
21
+ import re
22
+ import tempfile
23
+ from pathlib import Path
24
+
25
+ import torch
26
+ from huggingface_hub import CommitOperationAdd, HfApi, ModelCard
27
+ from packaging.version import Version
28
+ from torch import nn
29
+ from transformers import AutoConfig, ProcessorMixin
30
+
31
+
32
+ ORGANIZATION = "trl-internal-testing"
33
+
34
+ MODEL_CARD = """
35
+ ---
36
+ library_name: transformers
37
+ tags: [trl]
38
+ ---
39
+
40
+ # Tiny {model_class_name}
41
+
42
+ This is a minimal model built for unit tests in the [TRL](https://github.com/huggingface/trl) library.
43
+ """
44
+
45
+
46
+ api = HfApi()
47
+
48
+
49
+ def _transformers_floor_from_pyproject():
50
+ """Read the `transformers>=X.Y.Z` floor from the repo's pyproject.toml."""
51
+ pyproject = Path(__file__).resolve().parents[2] / "pyproject.toml"
52
+ match = re.search(r'"transformers>=([^"]+)"', pyproject.read_text())
53
+ if match is None:
54
+ raise RuntimeError(f"Could not find a `transformers>=` bound in {pyproject}")
55
+ return match.group(1)
56
+
57
+
58
+ def check_transformers_version(expected_version=None):
59
+ """Raise unless the installed transformers matches `expected_version` exactly.
60
+
61
+ If `expected_version` is None, defaults to the `transformers>=` floor from pyproject.toml.
62
+ """
63
+ import transformers
64
+
65
+ if expected_version is None:
66
+ expected_version = _transformers_floor_from_pyproject()
67
+
68
+ if Version(transformers.__version__) != Version(expected_version):
69
+ raise RuntimeError(
70
+ f"This script requires transformers=={expected_version}, but {transformers.__version__} is installed."
71
+ )
72
+
73
+
74
+ def smoke_test(model, tokenizer_or_processor=None):
75
+ """Run a minimal forward pass to sanity-check the tiny model doesn't crash or produce NaNs."""
76
+ model.eval()
77
+ device = next(model.parameters()).device
78
+
79
+ if isinstance(tokenizer_or_processor, ProcessorMixin):
80
+ # VLM path: build a dummy (image, text) input via the processor.
81
+ from PIL import Image
82
+
83
+ processor = tokenizer_or_processor
84
+ red = Image.new("RGB", (24, 24), color="red")
85
+ blue = Image.new("RGB", (24, 24), color="blue")
86
+ messages = [
87
+ [
88
+ {
89
+ "role": "user",
90
+ "content": [{"type": "image", "image": red}, {"type": "text", "text": "What is this?"}],
91
+ }
92
+ ],
93
+ [{"role": "user", "content": [{"type": "text", "text": "Is it blue?"}, {"type": "image", "image": blue}]}],
94
+ ]
95
+ inputs = processor.apply_chat_template(
96
+ conversation=messages,
97
+ add_generation_prompt=True,
98
+ tokenize=True,
99
+ return_dict=True,
100
+ return_tensors="pt",
101
+ padding=True,
102
+ ).to(device)
103
+ else:
104
+ inputs = {"input_ids": torch.tensor([[1, 2, 3, 4]], device=device)}
105
+
106
+ with torch.no_grad():
107
+ out = model(**inputs)
108
+
109
+ if "logits" in out:
110
+ output_tensor = out["logits"]
111
+ elif "last_hidden_state" in out:
112
+ output_tensor = out["last_hidden_state"]
113
+ else:
114
+ raise RuntimeError(f"[smoke_test] {model.__class__.__name__}: no logits or last_hidden_state on output")
115
+ if torch.isnan(output_tensor).any():
116
+ raise RuntimeError(f"[smoke_test] {model.__class__.__name__}: NaN in forward output")
117
+ print(f"[smoke_test] {model.__class__.__name__}: OK (output shape {tuple(output_tensor.shape)})")
118
+
119
+
120
+ def _flatten(d, prefix=""):
121
+ out = {}
122
+ for k, v in d.items():
123
+ key = f"{prefix}{k}" if prefix else k
124
+ if isinstance(v, dict):
125
+ out.update(_flatten(v, f"{key}."))
126
+ else:
127
+ out[key] = v
128
+ return out
129
+
130
+
131
+ _DIFF_IGNORE = {"_name_or_path", "transformers_version", "architectures", "model_type", "torch_dtype", "dtype"}
132
+
133
+
134
+ _TORCH_TO_SAFETENSORS_DTYPE = {
135
+ torch.float32: "F32",
136
+ torch.float16: "F16",
137
+ torch.bfloat16: "BF16",
138
+ torch.float64: "F64",
139
+ torch.float8_e4m3fn: "F8_E4M3",
140
+ torch.float8_e5m2: "F8_E5M2",
141
+ torch.int8: "I8",
142
+ torch.int16: "I16",
143
+ torch.int32: "I32",
144
+ torch.int64: "I64",
145
+ torch.uint8: "U8",
146
+ torch.bool: "BOOL",
147
+ }
148
+
149
+
150
+ def check_dtype_pattern(reference_id, model):
151
+ """Flag tensors whose dtype diverges from the reference checkpoint.
152
+
153
+ Reads the reference safetensors header via the Hub API (no weight download). Useful to catch cases
154
+ like Qwen3.5 where specific params (e.g. linear_attn.A_log) are kept in fp32 while the rest is bf16.
155
+ """
156
+ metadata = api.get_safetensors_metadata(reference_id)
157
+ ref_dtypes = {name: info.dtype for fm in metadata.files_metadata.values() for name, info in fm.tensors.items()}
158
+
159
+ mismatches = []
160
+ for name, tensor in model.state_dict().items():
161
+ ref_dtype = ref_dtypes.get(name)
162
+ if ref_dtype is None:
163
+ continue # tensor has no counterpart in the reference (e.g. scale-down, PEFT wrapper, tying)
164
+ tiny_dtype = _TORCH_TO_SAFETENSORS_DTYPE.get(tensor.dtype)
165
+ if tiny_dtype != ref_dtype:
166
+ mismatches.append((name, ref_dtype, tiny_dtype))
167
+
168
+ if not mismatches:
169
+ print(f"[dtype_check] {reference_id}: all matched tensors have the reference dtype")
170
+ return
171
+
172
+ print(f"[dtype_check] {reference_id}: {len(mismatches)} tensors differ from reference:")
173
+ for name, ref, tiny in mismatches:
174
+ print(f" {name}: reference={ref}, tiny={tiny}")
175
+
176
+
177
+ def print_config_diff(reference_id, model):
178
+ """Print the flat, recursive diff between the reference Hub config and the tiny-model config."""
179
+ reference_config = AutoConfig.from_pretrained(reference_id)
180
+ ref_flat = _flatten(reference_config.to_dict())
181
+ tiny_flat = _flatten(model.config.to_dict())
182
+
183
+ keys = sorted(set(ref_flat) | set(tiny_flat))
184
+ rows = []
185
+ for k in keys:
186
+ if any(k == ig or k.endswith(f".{ig}") for ig in _DIFF_IGNORE):
187
+ continue
188
+ rv, tv = ref_flat.get(k, "<missing>"), tiny_flat.get(k, "<missing>")
189
+ if rv != tv:
190
+ rows.append((k, rv, tv))
191
+
192
+ print(f"[config_diff] {reference_id} vs tiny ({len(rows)} differences)")
193
+ for k, r, t in rows:
194
+ print(f" {k:48s} {str(r)[:34]:34s} → {str(t)[:34]}")
195
+
196
+
197
+ def _parse_args():
198
+ parser = argparse.ArgumentParser(add_help=False)
199
+ parser.add_argument(
200
+ "--create-pr",
201
+ action="store_true",
202
+ help="If the repo already exists, open a PR instead of skipping.",
203
+ )
204
+ args, _ = parser.parse_known_args()
205
+ return args
206
+
207
+
208
+ def push_to_hub(model, tokenizer, generation_config, prefix=None, suffix=None, create_pr=None):
209
+ if create_pr is None:
210
+ create_pr = _parse_args().create_pr
211
+
212
+ model_class_name = model.__class__.__name__
213
+ content = MODEL_CARD.format(model_class_name=model_class_name)
214
+ model_card = ModelCard(content)
215
+ if prefix is not None:
216
+ model_class_name = f"{prefix}-{model_class_name}"
217
+ repo_id = f"{ORGANIZATION}/{model_class_name}"
218
+ if suffix is not None:
219
+ repo_id += f"-{suffix}"
220
+
221
+ exists = api.repo_exists(repo_id)
222
+ if exists and not create_pr:
223
+ print(f"Model {repo_id} already exists, skipping (pass --create-pr to open a PR)")
224
+ return
225
+
226
+ if not exists:
227
+ api.create_repo(repo_id, exist_ok=True)
228
+
229
+ # Save all artifacts to a temp dir and upload them in a single commit, so --create-pr opens one PR.
230
+ with tempfile.TemporaryDirectory() as tmpdir:
231
+ model.save_pretrained(tmpdir)
232
+ if tokenizer is not None:
233
+ tokenizer.save_pretrained(tmpdir)
234
+ if generation_config is not None:
235
+ generation_config.save_pretrained(tmpdir)
236
+ model_card.save(os.path.join(tmpdir, "README.md"))
237
+
238
+ operations = [
239
+ CommitOperationAdd(
240
+ path_in_repo=os.path.relpath(os.path.join(root, name), tmpdir),
241
+ path_or_fileobj=os.path.join(root, name),
242
+ )
243
+ for root, _, files in os.walk(tmpdir)
244
+ for name in files
245
+ ]
246
+ commit_info = api.create_commit(
247
+ repo_id=repo_id,
248
+ operations=operations,
249
+ commit_message=f"Upload {model.__class__.__name__}",
250
+ create_pr=exists and create_pr,
251
+ )
252
+ if commit_info.pr_url:
253
+ print(f"[push_to_hub] PR opened: {commit_info.pr_url}")
254
+
255
+
256
+ def init_weights_tiny_model(model):
257
+ """
258
+ Initialize tiny test models to avoid NaNs from uninitialized weights.
259
+
260
+ Uses safe defaults:
261
+ - Linear/Conv1d: Xavier uniform (weights), zero (biases)
262
+ - Embedding: Normal(0, 0.02)
263
+ - LayerNorm: Ones (weights), zero (biases)
264
+ """
265
+ for module in model.modules():
266
+ if isinstance(module, nn.Linear):
267
+ if module.bias is not None:
268
+ nn.init.zeros_(module.bias)
269
+ nn.init.xavier_uniform_(module.weight)
270
+
271
+ elif isinstance(module, nn.Embedding):
272
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
273
+
274
+ elif isinstance(module, nn.LayerNorm):
275
+ nn.init.ones_(module.weight)
276
+ if module.bias is not None:
277
+ nn.init.zeros_(module.bias)
278
+
279
+ elif isinstance(module, nn.Conv1d):
280
+ if module.bias is not None:
281
+ nn.init.zeros_(module.bias)
282
+ nn.init.xavier_uniform_(module.weight)
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/_remote_code/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # Source files for the tiny-RemoteForCausalLM Hub repo. Loaded as a sub-package
16
+ # by ../remote_for_causal_lm.py and pushed verbatim to the Hub so consumers can
17
+ # load the model with `trust_remote_code=True`.
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/_remote_code/configuration_remote.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from transformers import LlamaConfig
16
+
17
+
18
+ class RemoteConfig(LlamaConfig):
19
+ model_type = "remote"
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/_remote_code/modeling_remote.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch.nn as nn
16
+ from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel
17
+
18
+ from .configuration_remote import RemoteConfig
19
+
20
+
21
+ class RemoteModel(LlamaModel):
22
+ config_class = RemoteConfig
23
+
24
+
25
+ class RemoteForCausalLM(LlamaForCausalLM):
26
+ config_class = RemoteConfig
27
+
28
+
29
+ class RemoteForSequenceClassification(LlamaForSequenceClassification):
30
+ config_class = RemoteConfig
31
+
32
+ def __init__(self, config):
33
+ # The parent's MRO calls `AutoModel.from_config(config)`, which would re-trigger the
34
+ # trust_remote_code prompt for `RemoteConfig`. Wire `RemoteModel` in directly instead.
35
+ LlamaPreTrainedModel.__init__(self, config)
36
+ self.num_labels = config.num_labels
37
+ self.model = RemoteModel(config)
38
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
39
+ self.post_init()
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/cohere2_for_causal_lm.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ from transformers import AutoTokenizer, Cohere2Config, Cohere2ForCausalLM, GenerationConfig
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "CohereLabs/tiny-aya-earth"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = Cohere2Config(
35
+ vocab_size=262144,
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ logit_scale=1.0,
42
+ rope_theta=50000,
43
+ bos_token_id=2,
44
+ eos_token_id=3,
45
+ cache_implementation="hybrid",
46
+ layer_switch=4,
47
+ order_of_interleaved_layers="local_attn_first",
48
+ position_embedding_type="rope_gptj",
49
+ rotary_pct=1.0,
50
+ use_embedding_sharing=True,
51
+ use_gated_activation=True,
52
+ use_parallel_block=True,
53
+ use_parallel_embedding=False,
54
+ use_qk_norm=False,
55
+ )
56
+ model = Cohere2ForCausalLM(config).to(dtype=torch.bfloat16)
57
+ init_weights_tiny_model(model)
58
+ smoke_test(model, tokenizer)
59
+ check_dtype_pattern(MODEL_ID, model)
60
+ print_config_diff(MODEL_ID, model)
61
+ push_to_hub(model, tokenizer, generation_config, "tiny")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/cohere_for_causal_lm.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ from transformers import AutoTokenizer, CohereConfig, CohereForCausalLM, GenerationConfig
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "CohereLabs/aya-expanse-8b"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = CohereConfig(
35
+ vocab_size=256000,
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ logit_scale=0.125,
42
+ )
43
+ model = CohereForCausalLM(config).to(dtype=torch.float16)
44
+ init_weights_tiny_model(model)
45
+ smoke_test(model, tokenizer)
46
+ check_dtype_pattern(MODEL_ID, model)
47
+ print_config_diff(MODEL_ID, model)
48
+ push_to_hub(model, tokenizer, generation_config, "tiny")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/deepseek_v3_for_causal_lm.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 torch
16
+ from transformers import AutoTokenizer, DeepseekV3Config, DeepseekV3ForCausalLM, GenerationConfig
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "deepseek-ai/DeepSeek-R1"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = DeepseekV3Config(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ )
42
+ model = DeepseekV3ForCausalLM(config).to(dtype=torch.bfloat16)
43
+ init_weights_tiny_model(model)
44
+ smoke_test(model, tokenizer)
45
+ check_dtype_pattern(MODEL_ID, model)
46
+ print_config_diff(MODEL_ID, model)
47
+ push_to_hub(model, tokenizer, generation_config, "tiny")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/deepseek_v3_for_causal_lm_0528.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Note: R1-0528 is kept in addition to R1 because it has a different chat template.
16
+
17
+ import torch
18
+ from transformers import AutoTokenizer, DeepseekV3Config, DeepseekV3ForCausalLM, GenerationConfig
19
+
20
+ from .._common import (
21
+ check_dtype_pattern,
22
+ check_transformers_version,
23
+ init_weights_tiny_model,
24
+ print_config_diff,
25
+ push_to_hub,
26
+ smoke_test,
27
+ )
28
+
29
+
30
+ check_transformers_version()
31
+
32
+ MODEL_ID = "deepseek-ai/DeepSeek-R1-0528"
33
+
34
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
35
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
36
+ config = DeepseekV3Config(
37
+ vocab_size=len(tokenizer.vocab),
38
+ hidden_size=8,
39
+ num_attention_heads=4,
40
+ num_key_value_heads=2,
41
+ num_hidden_layers=2,
42
+ intermediate_size=32,
43
+ )
44
+ model = DeepseekV3ForCausalLM(config).to(dtype=torch.bfloat16)
45
+ init_weights_tiny_model(model)
46
+ smoke_test(model, tokenizer)
47
+ check_dtype_pattern(MODEL_ID, model)
48
+ print_config_diff(MODEL_ID, model)
49
+ push_to_hub(model, tokenizer, generation_config, "tiny", "0528")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/falcon_mamba_for_causal_lm.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 torch
16
+ from transformers import AutoTokenizer, FalconMambaConfig, FalconMambaForCausalLM, GenerationConfig
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "tiiuae/falcon-7b-instruct"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = FalconMambaConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ )
42
+ model = FalconMambaForCausalLM(config).to(dtype=torch.bfloat16)
43
+ init_weights_tiny_model(model)
44
+ smoke_test(model, tokenizer)
45
+ check_dtype_pattern(MODEL_ID, model)
46
+ print_config_diff(MODEL_ID, model)
47
+ push_to_hub(model, tokenizer, generation_config, "tiny")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/gemma2_for_causal_lm.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 torch
16
+ from transformers import AutoTokenizer, Gemma2Config, Gemma2ForCausalLM, GenerationConfig
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "google/gemma-2-2b-it"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = Gemma2Config(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ )
42
+ model = Gemma2ForCausalLM(config).to(dtype=torch.bfloat16)
43
+ init_weights_tiny_model(model)
44
+ smoke_test(model, tokenizer)
45
+ check_dtype_pattern(MODEL_ID, model)
46
+ print_config_diff(MODEL_ID, model)
47
+ push_to_hub(model, tokenizer, generation_config, "tiny")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/gemma_for_causal_lm.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 torch
16
+ from transformers import AutoTokenizer, GemmaConfig, GemmaForCausalLM, GenerationConfig
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "google/gemma-7b-it"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = GemmaConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ )
42
+ model = GemmaForCausalLM(config).to(dtype=torch.bfloat16)
43
+ init_weights_tiny_model(model)
44
+ smoke_test(model, tokenizer)
45
+ check_dtype_pattern(MODEL_ID, model)
46
+ print_config_diff(MODEL_ID, model)
47
+ push_to_hub(model, tokenizer, generation_config, "tiny")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/glm4_moe_for_causal_lm.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ from transformers import AutoTokenizer, GenerationConfig, Glm4MoeConfig, Glm4MoeForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "zai-org/GLM-4.5"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = Glm4MoeConfig(
35
+ vocab_size=151365,
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ moe_intermediate_size=32,
42
+ head_dim=2,
43
+ n_routed_experts=4,
44
+ num_experts_per_tok=2,
45
+ attention_bias=True,
46
+ eos_token_id=[151329, 151336, 151338],
47
+ pad_token_id=151329,
48
+ rope_theta=1000000,
49
+ routed_scaling_factor=2.5,
50
+ use_qk_norm=True,
51
+ num_nextn_predict_layers=1,
52
+ )
53
+ model = Glm4MoeForCausalLM(config).to(dtype=torch.bfloat16)
54
+ init_weights_tiny_model(model)
55
+ smoke_test(model, tokenizer)
56
+ check_dtype_pattern(MODEL_ID, model)
57
+ print_config_diff(MODEL_ID, model)
58
+ push_to_hub(model, tokenizer, generation_config, "tiny")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/gpt2_lm_head_model.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 torch
16
+ from transformers import AutoTokenizer, GenerationConfig, GPT2Config, GPT2LMHeadModel
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "openai-community/gpt2"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = GPT2Config(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ )
42
+ model = GPT2LMHeadModel(config).to(dtype=torch.float32)
43
+ init_weights_tiny_model(model)
44
+ smoke_test(model, tokenizer)
45
+ check_dtype_pattern(MODEL_ID, model)
46
+ print_config_diff(MODEL_ID, model)
47
+ push_to_hub(model, tokenizer, generation_config, "tiny")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/gpt_neox_for_causal_lm.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 torch
16
+ from transformers import AutoTokenizer, GenerationConfig, GPTNeoXConfig, GPTNeoXForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "EleutherAI/pythia-14m"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = GPTNeoXConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ )
42
+ model = GPTNeoXForCausalLM(config).to(dtype=torch.float16)
43
+ init_weights_tiny_model(model)
44
+ smoke_test(model, tokenizer)
45
+ check_dtype_pattern(MODEL_ID, model)
46
+ print_config_diff(MODEL_ID, model)
47
+ push_to_hub(model, tokenizer, generation_config, "tiny")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/gpt_oss_for_causal_lm.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ from transformers import AutoTokenizer, GenerationConfig, GptOssConfig, GptOssForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "openai/gpt-oss-20b"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = GptOssConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ num_local_experts=4,
42
+ num_experts_per_tok=2,
43
+ )
44
+ model = GptOssForCausalLM(config).to(dtype=torch.bfloat16)
45
+ init_weights_tiny_model(model)
46
+ smoke_test(model, tokenizer)
47
+ check_dtype_pattern(MODEL_ID, model)
48
+ print_config_diff(MODEL_ID, model)
49
+ push_to_hub(model, tokenizer, generation_config, "tiny")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/llama_for_causal_lm_3.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 torch
16
+ from transformers import AutoTokenizer, GenerationConfig, LlamaConfig, LlamaForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "meta-llama/Meta-Llama-3-8B-Instruct"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = LlamaConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ )
42
+ model = LlamaForCausalLM(config).to(dtype=torch.bfloat16)
43
+ init_weights_tiny_model(model)
44
+ smoke_test(model, tokenizer)
45
+ check_dtype_pattern(MODEL_ID, model)
46
+ print_config_diff(MODEL_ID, model)
47
+ push_to_hub(model, tokenizer, generation_config, "tiny", "3")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/llama_for_causal_lm_3_1.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 torch
16
+ from transformers import AutoTokenizer, GenerationConfig, LlamaConfig, LlamaForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = LlamaConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ )
42
+ model = LlamaForCausalLM(config).to(dtype=torch.bfloat16)
43
+ init_weights_tiny_model(model)
44
+ smoke_test(model, tokenizer)
45
+ check_dtype_pattern(MODEL_ID, model)
46
+ print_config_diff(MODEL_ID, model)
47
+ push_to_hub(model, tokenizer, generation_config, "tiny", "3.1")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/llama_for_causal_lm_3_2.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 torch
16
+ from transformers import AutoTokenizer, GenerationConfig, LlamaConfig, LlamaForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "meta-llama/Llama-3.2-1B-Instruct"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = LlamaConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ )
42
+ model = LlamaForCausalLM(config).to(dtype=torch.bfloat16)
43
+ init_weights_tiny_model(model)
44
+ smoke_test(model, tokenizer)
45
+ check_dtype_pattern(MODEL_ID, model)
46
+ print_config_diff(MODEL_ID, model)
47
+ push_to_hub(model, tokenizer, generation_config, "tiny", "3.2")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/mistral_for_causal_lm_0_1.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 torch
16
+ from transformers import AutoTokenizer, GenerationConfig, MistralConfig, MistralForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.1"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = MistralConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ )
42
+ model = MistralForCausalLM(config).to(dtype=torch.bfloat16)
43
+ init_weights_tiny_model(model)
44
+ smoke_test(model, tokenizer)
45
+ check_dtype_pattern(MODEL_ID, model)
46
+ print_config_diff(MODEL_ID, model)
47
+ push_to_hub(model, tokenizer, generation_config, "tiny", "0.1")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/mistral_for_causal_lm_0_2.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 torch
16
+ from transformers import AutoTokenizer, GenerationConfig, MistralConfig, MistralForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.2"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = MistralConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ )
42
+ model = MistralForCausalLM(config).to(dtype=torch.bfloat16)
43
+ init_weights_tiny_model(model)
44
+ smoke_test(model, tokenizer)
45
+ check_dtype_pattern(MODEL_ID, model)
46
+ print_config_diff(MODEL_ID, model)
47
+ push_to_hub(model, tokenizer, generation_config, "tiny", "0.2")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/nemotron_3_nano_for_causal_lm.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ from transformers import AutoTokenizer, GenerationConfig, NemotronHConfig, NemotronHForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version("5.3.0")
29
+
30
+ MODEL_ID = "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = NemotronHConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=16,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ intermediate_size=32,
40
+ layers_block_type=["mamba", "attention", "moe"], # one of each block type
41
+ mamba_num_heads=8,
42
+ mamba_head_dim=4,
43
+ mamba_n_groups=1,
44
+ ssm_state_size=16,
45
+ mamba_d_conv=4,
46
+ mamba_expand=2,
47
+ n_routed_experts=4,
48
+ num_experts_per_tok=2,
49
+ moe_intermediate_size=32,
50
+ moe_shared_expert_intermediate_size=32,
51
+ use_mamba_kernels=False, # CPU-friendly for testing
52
+ )
53
+ model = NemotronHForCausalLM(config).to(dtype=torch.bfloat16)
54
+ init_weights_tiny_model(model)
55
+
56
+ # Restore float32 for the Mamba mixer weights that the upstream model keeps in fp32.
57
+ for i, block_type in enumerate(config.layers_block_type):
58
+ if block_type == "mamba":
59
+ mixer = model.model.layers[i].mixer
60
+ mixer.A_log.data = mixer.A_log.data.float()
61
+ mixer.D.data = mixer.D.data.float()
62
+
63
+ smoke_test(model, tokenizer)
64
+ check_dtype_pattern(MODEL_ID, model)
65
+ print_config_diff(MODEL_ID, model)
66
+ push_to_hub(model, tokenizer, generation_config, "tiny", "nano")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/nemotron_3_super_for_causal_lm.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ from transformers import AutoTokenizer, GenerationConfig, NemotronHConfig, NemotronHForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version("5.3.0")
29
+
30
+ MODEL_ID = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = NemotronHConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=16,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ intermediate_size=32,
40
+ layers_block_type=["mamba", "attention", "moe"], # one of each block type
41
+ mamba_num_heads=8,
42
+ mamba_head_dim=4,
43
+ mamba_n_groups=1,
44
+ ssm_state_size=16,
45
+ mamba_d_conv=4,
46
+ mamba_expand=2,
47
+ n_routed_experts=4,
48
+ num_experts_per_tok=2,
49
+ moe_intermediate_size=32,
50
+ moe_shared_expert_intermediate_size=32,
51
+ use_mamba_kernels=False, # CPU-friendly for testing
52
+ )
53
+ # Unlike the Nano checkpoint, the Super checkpoint keeps the Mamba mixer weights in bfloat16, so no fp32 restore here.
54
+ model = NemotronHForCausalLM(config).to(dtype=torch.bfloat16)
55
+ init_weights_tiny_model(model)
56
+ smoke_test(model, tokenizer)
57
+ check_dtype_pattern(MODEL_ID, model)
58
+ print_config_diff(MODEL_ID, model)
59
+ push_to_hub(model, tokenizer, generation_config, "tiny", "super")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/nemotron_3_ultra_for_causal_lm.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ from transformers import AutoTokenizer, GenerationConfig, NemotronHConfig, NemotronHForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version("5.3.0")
29
+
30
+ MODEL_ID = "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = NemotronHConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=16,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ intermediate_size=32,
40
+ layers_block_type=["mamba", "attention", "moe"], # one of each block type
41
+ mamba_num_heads=8,
42
+ mamba_head_dim=4,
43
+ mamba_n_groups=1,
44
+ ssm_state_size=16,
45
+ mamba_d_conv=4,
46
+ mamba_expand=2,
47
+ n_routed_experts=4,
48
+ num_experts_per_tok=2,
49
+ moe_intermediate_size=32,
50
+ moe_shared_expert_intermediate_size=32,
51
+ use_mamba_kernels=False, # CPU-friendly for testing
52
+ )
53
+ # Unlike the Nano checkpoint, the Ultra checkpoint keeps the Mamba mixer weights in bfloat16, so no fp32 restore here.
54
+ model = NemotronHForCausalLM(config).to(dtype=torch.bfloat16)
55
+ init_weights_tiny_model(model)
56
+ smoke_test(model, tokenizer)
57
+ check_dtype_pattern(MODEL_ID, model)
58
+ print_config_diff(MODEL_ID, model)
59
+ push_to_hub(model, tokenizer, generation_config, "tiny", "ultra")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/olmo3_for_causal_lm.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ from transformers import AutoTokenizer, GenerationConfig, Olmo3Config, Olmo3ForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ # 4.57.0 (the release that introduced Olmo 3) was yanked for a packaging issue, so pin the first non-yanked patch.
29
+ check_transformers_version("4.57.1")
30
+
31
+ MODEL_ID = "allenai/Olmo-3-7B-Think"
32
+
33
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
34
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
35
+ config = Olmo3Config(
36
+ vocab_size=len(tokenizer.vocab),
37
+ hidden_size=8,
38
+ num_attention_heads=4,
39
+ num_key_value_heads=2,
40
+ num_hidden_layers=2,
41
+ intermediate_size=32,
42
+ # Non-size fields kept aligned with the reference so the tiny config only differs in what we scale down.
43
+ max_position_embeddings=65536,
44
+ rms_norm_eps=1e-06,
45
+ rope_theta=500000,
46
+ rope_scaling={
47
+ "attention_factor": 1.2079441541679836,
48
+ "beta_fast": 32.0,
49
+ "beta_slow": 1.0,
50
+ "factor": 8.0,
51
+ "original_max_position_embeddings": 8192,
52
+ "rope_type": "yarn",
53
+ },
54
+ bos_token_id=None,
55
+ eos_token_id=100257,
56
+ pad_token_id=100277,
57
+ use_cache=False,
58
+ )
59
+ model = Olmo3ForCausalLM(config).to(dtype=torch.bfloat16)
60
+ init_weights_tiny_model(model)
61
+ smoke_test(model, tokenizer)
62
+ check_dtype_pattern(MODEL_ID, model)
63
+ print_config_diff(MODEL_ID, model)
64
+ push_to_hub(model, tokenizer, generation_config, "tiny")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/opt_for_causal_lm.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 torch
16
+ from transformers import AutoTokenizer, GenerationConfig, OPTConfig, OPTForCausalLM
17
+
18
+ from .._common import (
19
+ check_dtype_pattern,
20
+ check_transformers_version,
21
+ init_weights_tiny_model,
22
+ print_config_diff,
23
+ push_to_hub,
24
+ smoke_test,
25
+ )
26
+
27
+
28
+ check_transformers_version()
29
+
30
+ MODEL_ID = "facebook/opt-1.3b"
31
+
32
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
33
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID)
34
+ config = OPTConfig(
35
+ vocab_size=len(tokenizer.vocab),
36
+ hidden_size=8,
37
+ num_attention_heads=4,
38
+ num_key_value_heads=2,
39
+ num_hidden_layers=2,
40
+ intermediate_size=32,
41
+ )
42
+ model = OPTForCausalLM(config).to(dtype=torch.float16)
43
+ init_weights_tiny_model(model)
44
+ smoke_test(model, tokenizer)
45
+ check_dtype_pattern(MODEL_ID, model)
46
+ print_config_diff(MODEL_ID, model)
47
+ push_to_hub(model, tokenizer, generation_config, "tiny")
tasks/tasksmith-1fe00f939ab9/tests/source/scripts/generate_tiny_models/for_causal_lm/peft_qwen3_for_causal_lm.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 peft import LoraConfig, get_peft_model
16
+ from transformers import Qwen3ForCausalLM
17
+
18
+ from .._common import check_transformers_version, push_to_hub, smoke_test
19
+
20
+
21
+ check_transformers_version()
22
+
23
+ BASE = "trl-internal-testing/tiny-Qwen3ForCausalLM"
24
+
25
+ model = Qwen3ForCausalLM.from_pretrained(BASE, dtype="auto")
26
+ model = get_peft_model(model, LoraConfig())
27
+ smoke_test(model, None)
28
+ push_to_hub(model, None, None, "tiny")