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

Stage Harbor release files 33501-34000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/glm4moe_training.jinja +109 -0
  2. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/gptoss.jinja +331 -0
  3. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/gptoss_training.jinja +338 -0
  4. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/llama3.jinja +5 -0
  5. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/llama3_1.jinja +109 -0
  6. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/llama3_2.jinja +93 -0
  7. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/llama3_training.jinja +19 -0
  8. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/llava_next.jinja +6 -0
  9. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/llava_next_training.jinja +11 -0
  10. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/nemotron_3_nano.jinja +204 -0
  11. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/nemotron_3_nano_training.jinja +220 -0
  12. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/nemotron_3_super.jinja +209 -0
  13. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/nemotron_3_super_training.jinja +226 -0
  14. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/nemotron_3_ultra.jinja +195 -0
  15. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/nemotron_3_ultra_training.jinja +212 -0
  16. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/phi3.jinja +8 -0
  17. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/phi3_5.jinja +8 -0
  18. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/phi3_5_training.jinja +26 -0
  19. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/phi3_training.jinja +26 -0
  20. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen2_5.jinja +54 -0
  21. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen2_5_training.jinja +65 -0
  22. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen2_5_vl.jinja +7 -0
  23. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen2_5_vl_training.jinja +63 -0
  24. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3.jinja +89 -0
  25. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_5_nothink.jinja +154 -0
  26. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_5_nothink_training.jinja +162 -0
  27. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_5_think.jinja +154 -0
  28. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_5_think_training.jinja +162 -0
  29. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_6.jinja +154 -0
  30. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_6_training.jinja +162 -0
  31. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_instruct_2507.jinja +61 -0
  32. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_instruct_2507_training.jinja +71 -0
  33. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_training.jinja +93 -0
  34. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_vl.jinja +120 -0
  35. tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_vl_training.jinja +127 -0
  36. tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/__init__.py +18 -0
  37. tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/accelerate_config.py +47 -0
  38. tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/accelerate_launcher.py +47 -0
  39. tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/commands/__init__.py +37 -0
  40. tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/commands/base.py +62 -0
  41. tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/commands/env.py +33 -0
  42. tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/commands/skills.py +42 -0
  43. tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/commands/training.py +72 -0
  44. tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/commands/vllm_serve.py +36 -0
  45. tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/main.py +51 -0
  46. tasks/tasksmith-5b4f21a2a450/environment/source/trl/data_utils.py +977 -0
  47. tasks/tasksmith-5b4f21a2a450/environment/source/trl/distributed.py +91 -0
  48. tasks/tasksmith-5b4f21a2a450/environment/source/trl/experimental/__init__.py +36 -0
  49. tasks/tasksmith-5b4f21a2a450/environment/source/trl/experimental/a2po/__init__.py +16 -0
  50. tasks/tasksmith-5b4f21a2a450/environment/source/trl/experimental/a2po/a2po_config.py +146 -0
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/glm4moe_training.jinja ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gMASK]<sop>
2
+ {%- if tools -%}
3
+ <|system|>
4
+ # Tools
5
+
6
+ You may call one or more functions to assist with the user query.
7
+
8
+ You are provided with function signatures within <tools></tools> XML tags:
9
+ <tools>
10
+ {% for tool in tools %}
11
+ {{ tool | tojson(ensure_ascii=False) }}
12
+ {% endfor %}
13
+ </tools>
14
+
15
+ For each function call, output the function name and arguments within the following XML format:
16
+ <tool_call>{function-name}
17
+ <arg_key>{arg-key-1}</arg_key>
18
+ <arg_value>{arg-value-1}</arg_value>
19
+ <arg_key>{arg-key-2}</arg_key>
20
+ <arg_value>{arg-value-2}</arg_value>
21
+ ...
22
+ </tool_call>{%- endif -%}
23
+ {%- macro visible_text(content) -%}
24
+ {%- if content is string -%}
25
+ {{- content }}
26
+ {%- elif content is iterable and content is not mapping -%}
27
+ {%- for item in content -%}
28
+ {%- if item is mapping and item.type == 'text' -%}
29
+ {{- item.text }}
30
+ {%- elif item is string -%}
31
+ {{- item }}
32
+ {%- endif -%}
33
+ {%- endfor -%}
34
+ {%- else -%}
35
+ {{- content }}
36
+ {%- endif -%}
37
+ {%- endmacro -%}
38
+ {%- set ns = namespace(last_user_index=-1) %}
39
+ {%- for m in messages %}
40
+ {%- if m.role == 'user' %}
41
+ {% set ns.last_user_index = loop.index0 -%}
42
+ {%- endif %}
43
+ {%- endfor %}
44
+ {% for m in messages %}
45
+ {%- if m.role == 'user' -%}
46
+ {%- if loop.first or messages[loop.index0 - 1].role != 'assistant' -%}<|user|>{%- endif -%}
47
+ {{ '\n' + visible_text(m.content) }}
48
+ {{- '/nothink' if (enable_thinking is defined and not enable_thinking and not visible_text(m.content).endswith("/nothink")) else '' -}}
49
+ {%- elif m.role == 'assistant' -%}
50
+ <|assistant|>
51
+ {%- set reasoning_content = '' %}
52
+ {%- set content = visible_text(m.content) %}
53
+ {%- if m.reasoning_content is string %}
54
+ {%- set reasoning_content = m.reasoning_content %}
55
+ {%- else %}
56
+ {%- if '</think>' in content %}
57
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
58
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
59
+ {%- endif %}
60
+ {%- endif %}
61
+ {% generation %}
62
+ {%- if loop.index0 > ns.last_user_index and reasoning_content -%}
63
+ {{ '\n<think>' + reasoning_content.strip() + '</think>'}}
64
+ {%- else -%}
65
+ {{ '\n<think></think>' }}
66
+ {%- endif -%}
67
+ {%- if content.strip() -%}
68
+ {{ '\n' + content.strip() }}
69
+ {%- endif -%}
70
+ {% if m.tool_calls %}
71
+ {% for tc in m.tool_calls %}
72
+ {%- if tc.function %}
73
+ {%- set tc = tc.function %}
74
+ {%- endif %}
75
+ {{ '\n<tool_call>' + tc.name }}
76
+ {% set _args = tc.arguments %}
77
+ {% for k, v in _args.items() %}
78
+ <arg_key>{{ k }}</arg_key>
79
+ <arg_value>{{ v | tojson(ensure_ascii=False) if v is not string else v }}</arg_value>
80
+ {% endfor %}
81
+ </tool_call>{% endfor %}<|observation|>
82
+ {%- elif loop.last -%}
83
+ {{- '<|user|>' }}
84
+ {%- elif messages[loop.index0 + 1].role == 'system' -%}
85
+ {{- '<|system|>' }}
86
+ {%- else -%}
87
+ {{- '<|user|>' }}
88
+ {%- endif %}
89
+ {% endgeneration %}
90
+ {%- elif m.role == 'tool' -%}
91
+ {%- if m.content is string -%}
92
+ {{- '\n<tool_response>\n' }}
93
+ {{- m.content }}
94
+ {{- '\n</tool_response>' }}
95
+ {%- else -%}
96
+ {{- '<|observation|>' if loop.first or messages[loop.index0 - 1].role != 'assistant' }}{% for tr in m.content %}
97
+
98
+ <tool_response>
99
+ {{ tr.output if tr.output is defined else tr }}
100
+ </tool_response>{% endfor -%}
101
+ {% endif -%}
102
+ {%- elif m.role == 'system' -%}
103
+ {%- if loop.first or messages[loop.index0 - 1].role != 'assistant' -%}<|system|>{%- endif -%}
104
+ {{ '\n' + visible_text(m.content) }}
105
+ {%- endif -%}
106
+ {%- endfor -%}
107
+ {%- if add_generation_prompt -%}
108
+ <|assistant|>{{- '\n<think></think>' if (enable_thinking is defined and not enable_thinking) else '' -}}
109
+ {%- endif -%}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/gptoss.jinja ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#-
2
+ In addition to the normal inputs of `messages` and `tools`, this template also accepts the
3
+ following kwargs:
4
+ - "builtin_tools": A list, can contain "browser" and/or "python".
5
+ - "model_identity": A string that optionally describes the model identity.
6
+ - "reasoning_effort": A string that describes the reasoning effort, defaults to "medium".
7
+ #}
8
+
9
+ {#- Tool Definition Rendering ============================================== #}
10
+ {%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%}
11
+ {%- if param_spec.type == "array" -%}
12
+ {%- if param_spec['items'] -%}
13
+ {%- if param_spec['items']['type'] == "string" -%}
14
+ {{- "string[]" }}
15
+ {%- elif param_spec['items']['type'] == "number" -%}
16
+ {{- "number[]" }}
17
+ {%- elif param_spec['items']['type'] == "integer" -%}
18
+ {{- "number[]" }}
19
+ {%- elif param_spec['items']['type'] == "boolean" -%}
20
+ {{- "boolean[]" }}
21
+ {%- else -%}
22
+ {%- set inner_type = render_typescript_type(param_spec['items'], required_params) -%}
23
+ {%- if inner_type == "object | object" or inner_type|length > 50 -%}
24
+ {{- "any[]" }}
25
+ {%- else -%}
26
+ {{- inner_type + "[]" }}
27
+ {%- endif -%}
28
+ {%- endif -%}
29
+ {%- if param_spec.nullable -%}
30
+ {{- " | null" }}
31
+ {%- endif -%}
32
+ {%- else -%}
33
+ {{- "any[]" }}
34
+ {%- if param_spec.nullable -%}
35
+ {{- " | null" }}
36
+ {%- endif -%}
37
+ {%- endif -%}
38
+ {%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is defined -%}
39
+ {#- Handle array of types like ["object", "object"] from Union[dict, list] #}
40
+ {%- if param_spec.type | length > 1 -%}
41
+ {{- param_spec.type | join(" | ") }}
42
+ {%- else -%}
43
+ {{- param_spec.type[0] }}
44
+ {%- endif -%}
45
+ {%- elif param_spec.oneOf -%}
46
+ {#- Handle oneOf schemas - check for complex unions and fallback to any #}
47
+ {%- set has_object_variants = false -%}
48
+ {%- for variant in param_spec.oneOf -%}
49
+ {%- if variant.type == "object" -%}
50
+ {%- set has_object_variants = true -%}
51
+ {%- endif -%}
52
+ {%- endfor -%}
53
+ {%- if has_object_variants and param_spec.oneOf|length > 1 -%}
54
+ {{- "any" }}
55
+ {%- else -%}
56
+ {%- for variant in param_spec.oneOf -%}
57
+ {{- render_typescript_type(variant, required_params) -}}
58
+ {%- if variant.description %}
59
+ {{- "// " + variant.description }}
60
+ {%- endif -%}
61
+ {%- if variant.default is defined %}
62
+ {{ "// default: " + variant.default|tojson }}
63
+ {%- endif -%}
64
+ {%- if not loop.last %}
65
+ {{- " | " }}
66
+ {% endif -%}
67
+ {%- endfor -%}
68
+ {%- endif -%}
69
+ {%- elif param_spec.type == "string" -%}
70
+ {%- if param_spec.enum -%}
71
+ {{- '"' + param_spec.enum|join('" | "') + '"' -}}
72
+ {%- else -%}
73
+ {{- "string" }}
74
+ {%- if param_spec.nullable %}
75
+ {{- " | null" }}
76
+ {%- endif -%}
77
+ {%- endif -%}
78
+ {%- elif param_spec.type == "number" -%}
79
+ {{- "number" }}
80
+ {%- elif param_spec.type == "integer" -%}
81
+ {{- "number" }}
82
+ {%- elif param_spec.type == "boolean" -%}
83
+ {{- "boolean" }}
84
+
85
+ {%- elif param_spec.type == "object" -%}
86
+ {%- if param_spec.properties -%}
87
+ {{- "{\n" }}
88
+ {%- for prop_name, prop_spec in param_spec.properties.items() -%}
89
+ {{- prop_name -}}
90
+ {%- if prop_name not in (param_spec.required or []) -%}
91
+ {{- "?" }}
92
+ {%- endif -%}
93
+ {{- ": " }}
94
+ {{ render_typescript_type(prop_spec, param_spec.required or []) }}
95
+ {%- if not loop.last -%}
96
+ {{-", " }}
97
+ {%- endif -%}
98
+ {%- endfor -%}
99
+ {{- "}" }}
100
+ {%- else -%}
101
+ {{- "object" }}
102
+ {%- endif -%}
103
+ {%- else -%}
104
+ {{- "any" }}
105
+ {%- endif -%}
106
+ {%- endmacro -%}
107
+
108
+ {%- macro render_tool_namespace(namespace_name, tools) -%}
109
+ {{- "## " + namespace_name + "\n\n" }}
110
+ {{- "namespace " + namespace_name + " {\n\n" }}
111
+ {%- for tool in tools %}
112
+ {%- set tool = tool.function %}
113
+ {{- "// " + tool.description + "\n" }}
114
+ {{- "type "+ tool.name + " = " }}
115
+ {%- if tool.parameters and tool.parameters.properties %}
116
+ {{- "(_: {\n" }}
117
+ {%- for param_name, param_spec in tool.parameters.properties.items() %}
118
+ {%- if param_spec.description %}
119
+ {{- "// " + param_spec.description + "\n" }}
120
+ {%- endif %}
121
+ {{- param_name }}
122
+ {%- if param_name not in (tool.parameters.required or []) -%}
123
+ {{- "?" }}
124
+ {%- endif -%}
125
+ {{- ": " }}
126
+ {{- render_typescript_type(param_spec, tool.parameters.required or []) }}
127
+ {%- if param_spec.default is defined -%}
128
+ {%- if param_spec.enum %}
129
+ {{- ", // default: " + param_spec.default }}
130
+ {%- elif param_spec.oneOf %}
131
+ {{- "// default: " + param_spec.default }}
132
+ {%- else %}
133
+ {{- ", // default: " + param_spec.default|tojson }}
134
+ {%- endif -%}
135
+ {%- endif -%}
136
+ {%- if not loop.last %}
137
+ {{- ",\n" }}
138
+ {%- else %}
139
+ {{- ",\n" }}
140
+ {%- endif -%}
141
+ {%- endfor %}
142
+ {{- "}) => any;\n\n" }}
143
+ {%- else -%}
144
+ {{- "() => any;\n\n" }}
145
+ {%- endif -%}
146
+ {%- endfor %}
147
+ {{- "} // namespace " + namespace_name }}
148
+ {%- endmacro -%}
149
+
150
+ {%- macro render_builtin_tools(browser_tool, python_tool) -%}
151
+ {%- if browser_tool %}
152
+ {{- "## browser\n\n" }}
153
+ {{- "// Tool for browsing.\n" }}
154
+ {{- "// The `cursor` appears in brackets before each browsing display: `[{cursor}]`.\n" }}
155
+ {{- "// Cite information from the tool using the following format:\n" }}
156
+ {{- "// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`.\n" }}
157
+ {{- "// Do not quote more than 10 words directly from the tool output.\n" }}
158
+ {{- "// sources=web (default: web)\n" }}
159
+ {{- "namespace browser {\n\n" }}
160
+ {{- "// Searches for information related to `query` and displays `topn` results.\n" }}
161
+ {{- "type search = (_: {\n" }}
162
+ {{- "query: string,\n" }}
163
+ {{- "topn?: number, // default: 10\n" }}
164
+ {{- "source?: string,\n" }}
165
+ {{- "}) => any;\n\n" }}
166
+ {{- "// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines.\n" }}
167
+ {{- "// Valid link ids are displayed with the formatting: `【{id}†.*】`.\n" }}
168
+ {{- "// If `cursor` is not provided, the most recent page is implied.\n" }}
169
+ {{- "// If `id` is a string, it is treated as a fully qualified URL associated with `source`.\n" }}
170
+ {{- "// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available.\n" }}
171
+ {{- "// Use this function without `id` to scroll to a new location of an opened page.\n" }}
172
+ {{- "type open = (_: {\n" }}
173
+ {{- "id?: number | string, // default: -1\n" }}
174
+ {{- "cursor?: number, // default: -1\n" }}
175
+ {{- "loc?: number, // default: -1\n" }}
176
+ {{- "num_lines?: number, // default: -1\n" }}
177
+ {{- "view_source?: boolean, // default: false\n" }}
178
+ {{- "source?: string,\n" }}
179
+ {{- "}) => any;\n\n" }}
180
+ {{- "// Finds exact matches of `pattern` in the current page, or the page given by `cursor`.\n" }}
181
+ {{- "type find = (_: {\n" }}
182
+ {{- "pattern: string,\n" }}
183
+ {{- "cursor?: number, // default: -1\n" }}
184
+ {{- "}) => any;\n\n" }}
185
+ {{- "} // namespace browser\n\n" }}
186
+ {%- endif -%}
187
+
188
+ {%- if python_tool %}
189
+ {{- "## python\n\n" }}
190
+ {{- "Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files).\n\n" }}
191
+ {{- "When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster.\n\n" }}
192
+ {%- endif -%}
193
+ {%- endmacro -%}
194
+
195
+ {#- System Message Construction ============================================ #}
196
+ {%- macro build_system_message() -%}
197
+ {%- if model_identity is not defined %}
198
+ {%- set model_identity = "You are ChatGPT, a large language model trained by OpenAI." %}
199
+ {%- endif %}
200
+ {{- model_identity + "\n" }}
201
+ {{- "Knowledge cutoff: 2024-06\n" }}
202
+ {{- "Current date: " + strftime_now("%Y-%m-%d") + "\n\n" }}
203
+ {%- if reasoning_effort is not defined %}
204
+ {%- set reasoning_effort = "medium" %}
205
+ {%- endif %}
206
+ {{- "Reasoning: " + reasoning_effort + "\n\n" }}
207
+ {%- if builtin_tools %}
208
+ {{- "# Tools\n\n" }}
209
+ {%- set available_builtin_tools = namespace(browser=false, python=false) %}
210
+ {%- for tool in builtin_tools %}
211
+ {%- if tool == "browser" %}
212
+ {%- set available_builtin_tools.browser = true %}
213
+ {%- elif tool == "python" %}
214
+ {%- set available_builtin_tools.python = true %}
215
+ {%- endif %}
216
+ {%- endfor %}
217
+ {{- render_builtin_tools(available_builtin_tools.browser, available_builtin_tools.python) }}
218
+ {%- endif -%}
219
+ {{- "# Valid channels: analysis, commentary, final. Channel must be included for every message." }}
220
+ {%- if tools -%}
221
+ {{- "\nCalls to these tools must go to the commentary channel: 'functions'." }}
222
+ {%- endif -%}
223
+ {%- endmacro -%}
224
+
225
+ {#- Main Template Logic ================================================= #}
226
+ {#- Set defaults #}
227
+
228
+ {#- Render system message #}
229
+ {{- "<|start|>system<|message|>" }}
230
+ {{- build_system_message() }}
231
+ {{- "<|end|>" }}
232
+
233
+ {#- Extract developer message #}
234
+ {%- if messages[0].role == "developer" or messages[0].role == "system" %}
235
+ {%- set developer_message = messages[0].content %}
236
+ {%- set loop_messages = messages[1:] %}
237
+ {%- else %}
238
+ {%- set developer_message = "" %}
239
+ {%- set loop_messages = messages %}
240
+ {%- endif %}
241
+
242
+ {#- Render developer message #}
243
+ {%- if developer_message or tools %}
244
+ {{- "<|start|>developer<|message|>" }}
245
+ {%- if developer_message %}
246
+ {{- "# Instructions\n\n" }}
247
+ {{- developer_message }}
248
+ {{- "\n\n" }}
249
+ {%- endif %}
250
+ {%- if tools -%}
251
+ {{- "# Tools\n\n" }}
252
+ {{- render_tool_namespace("functions", tools) }}
253
+ {%- endif -%}
254
+ {{- "<|end|>" }}
255
+ {%- endif %}
256
+
257
+ {#- Render messages #}
258
+ {%- set last_tool_call = namespace(name=none) %}
259
+ {%- for message in loop_messages -%}
260
+ {#- At this point only assistant/user/tool messages should remain #}
261
+ {%- if message.role == 'assistant' -%}
262
+ {#- Checks to ensure the messages are being passed in the format we expect #}
263
+ {%- if "content" in message %}
264
+ {%- if "<|channel|>analysis<|message|>" in message.content or "<|channel|>final<|message|>" in message.content %}
265
+ {{- raise_exception("You have passed a message containing <|channel|> tags in the content field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }}
266
+ {%- endif %}
267
+ {%- endif %}
268
+ {%- if "thinking" in message %}
269
+ {%- if "<|channel|>analysis<|message|>" in message.thinking or "<|channel|>final<|message|>" in message.thinking %}
270
+ {{- raise_exception("You have passed a message containing <|channel|> tags in the thinking field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }}
271
+ {%- endif %}
272
+ {%- endif %}
273
+ {%- if "tool_calls" in message %}
274
+ {#- We need very careful handling here - we want to drop the tool call analysis message if the model #}
275
+ {#- has output a later <|final|> message, but otherwise we want to retain it. This is the only case #}
276
+ {#- when we render CoT/analysis messages in inference. #}
277
+ {%- set future_final_message = namespace(found=false) %}
278
+ {%- for future_message in loop_messages[loop.index:] %}
279
+ {%- if future_message.role == 'assistant' and "tool_calls" not in future_message %}
280
+ {%- set future_final_message.found = true %}
281
+ {%- endif %}
282
+ {%- endfor %}
283
+ {#- We assume max 1 tool call per message, and so we infer the tool call name #}
284
+ {#- in "tool" messages from the most recent assistant tool call name #}
285
+ {%- set tool_call = message.tool_calls[0] %}
286
+ {%- if tool_call.function %}
287
+ {%- set tool_call = tool_call.function %}
288
+ {%- endif %}
289
+ {%- if message.content and message.thinking %}
290
+ {{- raise_exception("Cannot pass both content and thinking in an assistant message with tool calls! Put the analysis message in one or the other, but not both.") }}
291
+ {%- elif message.content and not future_final_message.found %}
292
+ {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.content + "<|end|>" }}
293
+ {%- elif message.thinking and not future_final_message.found %}
294
+ {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }}
295
+ {%- endif %}
296
+ {{- "<|start|>assistant to=" }}
297
+ {{- "functions." + tool_call.name + "<|channel|>commentary " }}
298
+ {{- (tool_call.content_type if tool_call.content_type is defined else "json") + "<|message|>" }}
299
+ {{- tool_call.arguments|tojson }}
300
+ {{- "<|call|>" }}
301
+ {%- set last_tool_call.name = tool_call.name %}
302
+ {%- elif loop.last and not add_generation_prompt %}
303
+ {#- Only render the CoT if the final turn is an assistant turn and add_generation_prompt is false #}
304
+ {#- This is a situation that should only occur in training, never in inference. #}
305
+ {%- if "thinking" in message %}
306
+ {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }}
307
+ {%- endif %}
308
+ {#- <|return|> indicates the end of generation, but <|end|> does not #}
309
+ {#- <|return|> should never be an input to the model, but we include it as the final token #}
310
+ {#- when training, so the model learns to emit it. #}
311
+ {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|return|>" }}
312
+ {%- else %}
313
+ {#- CoT is dropped during all previous turns, so we never render it for inference #}
314
+ {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|end|>" }}
315
+ {%- set last_tool_call.name = none %}
316
+ {%- endif %}
317
+ {%- elif message.role == 'tool' -%}
318
+ {%- if last_tool_call.name is none %}
319
+ {{- raise_exception("Message has tool role, but there was no previous assistant message with a tool call!") }}
320
+ {%- endif %}
321
+ {{- "<|start|>functions." + last_tool_call.name }}
322
+ {{- " to=assistant<|channel|>commentary<|message|>" + message.content|tojson + "<|end|>" }}
323
+ {%- elif message.role == 'user' -%}
324
+ {{- "<|start|>user<|message|>" + message.content + "<|end|>" }}
325
+ {%- endif -%}
326
+ {%- endfor -%}
327
+
328
+ {#- Generation prompt #}
329
+ {%- if add_generation_prompt -%}
330
+ <|start|>assistant
331
+ {%- endif -%}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/gptoss_training.jinja ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#-
2
+ Training variant of the GPT-OSS chat template (see gptoss.jinja for the original).
3
+ Modifications vs the original:
4
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
5
+ assistant-only loss masking in SFT training.
6
+
7
+ In addition to the normal inputs of `messages` and `tools`, this template also accepts the
8
+ following kwargs:
9
+ - "builtin_tools": A list, can contain "browser" and/or "python".
10
+ - "model_identity": A string that optionally describes the model identity.
11
+ - "reasoning_effort": A string that describes the reasoning effort, defaults to "medium".
12
+ #}
13
+
14
+ {#- Tool Definition Rendering ============================================== #}
15
+ {%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%}
16
+ {%- if param_spec.type == "array" -%}
17
+ {%- if param_spec['items'] -%}
18
+ {%- if param_spec['items']['type'] == "string" -%}
19
+ {{- "string[]" }}
20
+ {%- elif param_spec['items']['type'] == "number" -%}
21
+ {{- "number[]" }}
22
+ {%- elif param_spec['items']['type'] == "integer" -%}
23
+ {{- "number[]" }}
24
+ {%- elif param_spec['items']['type'] == "boolean" -%}
25
+ {{- "boolean[]" }}
26
+ {%- else -%}
27
+ {%- set inner_type = render_typescript_type(param_spec['items'], required_params) -%}
28
+ {%- if inner_type == "object | object" or inner_type|length > 50 -%}
29
+ {{- "any[]" }}
30
+ {%- else -%}
31
+ {{- inner_type + "[]" }}
32
+ {%- endif -%}
33
+ {%- endif -%}
34
+ {%- if param_spec.nullable -%}
35
+ {{- " | null" }}
36
+ {%- endif -%}
37
+ {%- else -%}
38
+ {{- "any[]" }}
39
+ {%- if param_spec.nullable -%}
40
+ {{- " | null" }}
41
+ {%- endif -%}
42
+ {%- endif -%}
43
+ {%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is defined -%}
44
+ {#- Handle array of types like ["object", "object"] from Union[dict, list] #}
45
+ {%- if param_spec.type | length > 1 -%}
46
+ {{- param_spec.type | join(" | ") }}
47
+ {%- else -%}
48
+ {{- param_spec.type[0] }}
49
+ {%- endif -%}
50
+ {%- elif param_spec.oneOf -%}
51
+ {#- Handle oneOf schemas - check for complex unions and fallback to any #}
52
+ {%- set has_object_variants = false -%}
53
+ {%- for variant in param_spec.oneOf -%}
54
+ {%- if variant.type == "object" -%}
55
+ {%- set has_object_variants = true -%}
56
+ {%- endif -%}
57
+ {%- endfor -%}
58
+ {%- if has_object_variants and param_spec.oneOf|length > 1 -%}
59
+ {{- "any" }}
60
+ {%- else -%}
61
+ {%- for variant in param_spec.oneOf -%}
62
+ {{- render_typescript_type(variant, required_params) -}}
63
+ {%- if variant.description %}
64
+ {{- "// " + variant.description }}
65
+ {%- endif -%}
66
+ {%- if variant.default is defined %}
67
+ {{ "// default: " + variant.default|tojson }}
68
+ {%- endif -%}
69
+ {%- if not loop.last %}
70
+ {{- " | " }}
71
+ {% endif -%}
72
+ {%- endfor -%}
73
+ {%- endif -%}
74
+ {%- elif param_spec.type == "string" -%}
75
+ {%- if param_spec.enum -%}
76
+ {{- '"' + param_spec.enum|join('" | "') + '"' -}}
77
+ {%- else -%}
78
+ {{- "string" }}
79
+ {%- if param_spec.nullable %}
80
+ {{- " | null" }}
81
+ {%- endif -%}
82
+ {%- endif -%}
83
+ {%- elif param_spec.type == "number" -%}
84
+ {{- "number" }}
85
+ {%- elif param_spec.type == "integer" -%}
86
+ {{- "number" }}
87
+ {%- elif param_spec.type == "boolean" -%}
88
+ {{- "boolean" }}
89
+
90
+ {%- elif param_spec.type == "object" -%}
91
+ {%- if param_spec.properties -%}
92
+ {{- "{\n" }}
93
+ {%- for prop_name, prop_spec in param_spec.properties.items() -%}
94
+ {{- prop_name -}}
95
+ {%- if prop_name not in (param_spec.required or []) -%}
96
+ {{- "?" }}
97
+ {%- endif -%}
98
+ {{- ": " }}
99
+ {{ render_typescript_type(prop_spec, param_spec.required or []) }}
100
+ {%- if not loop.last -%}
101
+ {{-", " }}
102
+ {%- endif -%}
103
+ {%- endfor -%}
104
+ {{- "}" }}
105
+ {%- else -%}
106
+ {{- "object" }}
107
+ {%- endif -%}
108
+ {%- else -%}
109
+ {{- "any" }}
110
+ {%- endif -%}
111
+ {%- endmacro -%}
112
+
113
+ {%- macro render_tool_namespace(namespace_name, tools) -%}
114
+ {{- "## " + namespace_name + "\n\n" }}
115
+ {{- "namespace " + namespace_name + " {\n\n" }}
116
+ {%- for tool in tools %}
117
+ {%- set tool = tool.function %}
118
+ {{- "// " + tool.description + "\n" }}
119
+ {{- "type "+ tool.name + " = " }}
120
+ {%- if tool.parameters and tool.parameters.properties %}
121
+ {{- "(_: {\n" }}
122
+ {%- for param_name, param_spec in tool.parameters.properties.items() %}
123
+ {%- if param_spec.description %}
124
+ {{- "// " + param_spec.description + "\n" }}
125
+ {%- endif %}
126
+ {{- param_name }}
127
+ {%- if param_name not in (tool.parameters.required or []) -%}
128
+ {{- "?" }}
129
+ {%- endif -%}
130
+ {{- ": " }}
131
+ {{- render_typescript_type(param_spec, tool.parameters.required or []) }}
132
+ {%- if param_spec.default is defined -%}
133
+ {%- if param_spec.enum %}
134
+ {{- ", // default: " + param_spec.default }}
135
+ {%- elif param_spec.oneOf %}
136
+ {{- "// default: " + param_spec.default }}
137
+ {%- else %}
138
+ {{- ", // default: " + param_spec.default|tojson }}
139
+ {%- endif -%}
140
+ {%- endif -%}
141
+ {%- if not loop.last %}
142
+ {{- ",\n" }}
143
+ {%- else %}
144
+ {{- ",\n" }}
145
+ {%- endif -%}
146
+ {%- endfor %}
147
+ {{- "}) => any;\n\n" }}
148
+ {%- else -%}
149
+ {{- "() => any;\n\n" }}
150
+ {%- endif -%}
151
+ {%- endfor %}
152
+ {{- "} // namespace " + namespace_name }}
153
+ {%- endmacro -%}
154
+
155
+ {%- macro render_builtin_tools(browser_tool, python_tool) -%}
156
+ {%- if browser_tool %}
157
+ {{- "## browser\n\n" }}
158
+ {{- "// Tool for browsing.\n" }}
159
+ {{- "// The `cursor` appears in brackets before each browsing display: `[{cursor}]`.\n" }}
160
+ {{- "// Cite information from the tool using the following format:\n" }}
161
+ {{- "// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`.\n" }}
162
+ {{- "// Do not quote more than 10 words directly from the tool output.\n" }}
163
+ {{- "// sources=web (default: web)\n" }}
164
+ {{- "namespace browser {\n\n" }}
165
+ {{- "// Searches for information related to `query` and displays `topn` results.\n" }}
166
+ {{- "type search = (_: {\n" }}
167
+ {{- "query: string,\n" }}
168
+ {{- "topn?: number, // default: 10\n" }}
169
+ {{- "source?: string,\n" }}
170
+ {{- "}) => any;\n\n" }}
171
+ {{- "// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines.\n" }}
172
+ {{- "// Valid link ids are displayed with the formatting: `【{id}†.*】`.\n" }}
173
+ {{- "// If `cursor` is not provided, the most recent page is implied.\n" }}
174
+ {{- "// If `id` is a string, it is treated as a fully qualified URL associated with `source`.\n" }}
175
+ {{- "// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available.\n" }}
176
+ {{- "// Use this function without `id` to scroll to a new location of an opened page.\n" }}
177
+ {{- "type open = (_: {\n" }}
178
+ {{- "id?: number | string, // default: -1\n" }}
179
+ {{- "cursor?: number, // default: -1\n" }}
180
+ {{- "loc?: number, // default: -1\n" }}
181
+ {{- "num_lines?: number, // default: -1\n" }}
182
+ {{- "view_source?: boolean, // default: false\n" }}
183
+ {{- "source?: string,\n" }}
184
+ {{- "}) => any;\n\n" }}
185
+ {{- "// Finds exact matches of `pattern` in the current page, or the page given by `cursor`.\n" }}
186
+ {{- "type find = (_: {\n" }}
187
+ {{- "pattern: string,\n" }}
188
+ {{- "cursor?: number, // default: -1\n" }}
189
+ {{- "}) => any;\n\n" }}
190
+ {{- "} // namespace browser\n\n" }}
191
+ {%- endif -%}
192
+
193
+ {%- if python_tool %}
194
+ {{- "## python\n\n" }}
195
+ {{- "Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files).\n\n" }}
196
+ {{- "When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster.\n\n" }}
197
+ {%- endif -%}
198
+ {%- endmacro -%}
199
+
200
+ {#- System Message Construction ============================================ #}
201
+ {%- macro build_system_message() -%}
202
+ {%- if model_identity is not defined %}
203
+ {%- set model_identity = "You are ChatGPT, a large language model trained by OpenAI." %}
204
+ {%- endif %}
205
+ {{- model_identity + "\n" }}
206
+ {{- "Knowledge cutoff: 2024-06\n" }}
207
+ {{- "Current date: " + strftime_now("%Y-%m-%d") + "\n\n" }}
208
+ {%- if reasoning_effort is not defined %}
209
+ {%- set reasoning_effort = "medium" %}
210
+ {%- endif %}
211
+ {{- "Reasoning: " + reasoning_effort + "\n\n" }}
212
+ {%- if builtin_tools %}
213
+ {{- "# Tools\n\n" }}
214
+ {%- set available_builtin_tools = namespace(browser=false, python=false) %}
215
+ {%- for tool in builtin_tools %}
216
+ {%- if tool == "browser" %}
217
+ {%- set available_builtin_tools.browser = true %}
218
+ {%- elif tool == "python" %}
219
+ {%- set available_builtin_tools.python = true %}
220
+ {%- endif %}
221
+ {%- endfor %}
222
+ {{- render_builtin_tools(available_builtin_tools.browser, available_builtin_tools.python) }}
223
+ {%- endif -%}
224
+ {{- "# Valid channels: analysis, commentary, final. Channel must be included for every message." }}
225
+ {%- if tools -%}
226
+ {{- "\nCalls to these tools must go to the commentary channel: 'functions'." }}
227
+ {%- endif -%}
228
+ {%- endmacro -%}
229
+
230
+ {#- Main Template Logic ================================================= #}
231
+ {#- Set defaults #}
232
+
233
+ {#- Render system message #}
234
+ {{- "<|start|>system<|message|>" }}
235
+ {{- build_system_message() }}
236
+ {{- "<|end|>" }}
237
+
238
+ {#- Extract developer message #}
239
+ {%- if messages[0].role == "developer" or messages[0].role == "system" %}
240
+ {%- set developer_message = messages[0].content %}
241
+ {%- set loop_messages = messages[1:] %}
242
+ {%- else %}
243
+ {%- set developer_message = "" %}
244
+ {%- set loop_messages = messages %}
245
+ {%- endif %}
246
+
247
+ {#- Render developer message #}
248
+ {%- if developer_message or tools %}
249
+ {{- "<|start|>developer<|message|>" }}
250
+ {%- if developer_message %}
251
+ {{- "# Instructions\n\n" }}
252
+ {{- developer_message }}
253
+ {{- "\n\n" }}
254
+ {%- endif %}
255
+ {%- if tools -%}
256
+ {{- "# Tools\n\n" }}
257
+ {{- render_tool_namespace("functions", tools) }}
258
+ {%- endif -%}
259
+ {{- "<|end|>" }}
260
+ {%- endif %}
261
+
262
+ {#- Render messages #}
263
+ {%- set last_tool_call = namespace(name=none) %}
264
+ {%- for message in loop_messages -%}
265
+ {#- At this point only assistant/user/tool messages should remain #}
266
+ {%- if message.role == 'assistant' -%}
267
+ {#- Checks to ensure the messages are being passed in the format we expect #}
268
+ {%- if "content" in message %}
269
+ {%- if "<|channel|>analysis<|message|>" in message.content or "<|channel|>final<|message|>" in message.content %}
270
+ {{- raise_exception("You have passed a message containing <|channel|> tags in the content field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }}
271
+ {%- endif %}
272
+ {%- endif %}
273
+ {%- if "thinking" in message %}
274
+ {%- if "<|channel|>analysis<|message|>" in message.thinking or "<|channel|>final<|message|>" in message.thinking %}
275
+ {{- raise_exception("You have passed a message containing <|channel|> tags in the thinking field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }}
276
+ {%- endif %}
277
+ {%- endif %}
278
+ {%- generation %}
279
+ {%- if "tool_calls" in message %}
280
+ {#- We need very careful handling here - we want to drop the tool call analysis message if the model #}
281
+ {#- has output a later <|final|> message, but otherwise we want to retain it. This is the only case #}
282
+ {#- when we render CoT/analysis messages in inference. #}
283
+ {%- set future_final_message = namespace(found=false) %}
284
+ {%- for future_message in loop_messages[loop.index:] %}
285
+ {%- if future_message.role == 'assistant' and "tool_calls" not in future_message %}
286
+ {%- set future_final_message.found = true %}
287
+ {%- endif %}
288
+ {%- endfor %}
289
+ {#- We assume max 1 tool call per message, and so we infer the tool call name #}
290
+ {#- in "tool" messages from the most recent assistant tool call name #}
291
+ {%- set tool_call = message.tool_calls[0] %}
292
+ {%- if tool_call.function %}
293
+ {%- set tool_call = tool_call.function %}
294
+ {%- endif %}
295
+ {%- if message.content and message.thinking %}
296
+ {{- raise_exception("Cannot pass both content and thinking in an assistant message with tool calls! Put the analysis message in one or the other, but not both.") }}
297
+ {%- elif message.content and not future_final_message.found %}
298
+ {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.content + "<|end|>" }}
299
+ {%- elif message.thinking and not future_final_message.found %}
300
+ {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }}
301
+ {%- endif %}
302
+ {{- "<|start|>assistant to=" }}
303
+ {{- "functions." + tool_call.name + "<|channel|>commentary " }}
304
+ {{- (tool_call.content_type if tool_call.content_type is defined else "json") + "<|message|>" }}
305
+ {{- tool_call.arguments|tojson }}
306
+ {{- "<|call|>" }}
307
+ {%- set last_tool_call.name = tool_call.name %}
308
+ {%- elif loop.last and not add_generation_prompt %}
309
+ {#- Only render the CoT if the final turn is an assistant turn and add_generation_prompt is false #}
310
+ {#- This is a situation that should only occur in training, never in inference. #}
311
+ {%- if "thinking" in message %}
312
+ {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }}
313
+ {%- endif %}
314
+ {#- <|return|> indicates the end of generation, but <|end|> does not #}
315
+ {#- <|return|> should never be an input to the model, but we include it as the final token #}
316
+ {#- when training, so the model learns to emit it. #}
317
+ {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|return|>" }}
318
+ {%- else %}
319
+ {#- CoT is dropped during all previous turns, so we never render it for inference #}
320
+ {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|end|>" }}
321
+ {%- set last_tool_call.name = none %}
322
+ {%- endif %}
323
+ {%- endgeneration %}
324
+ {%- elif message.role == 'tool' -%}
325
+ {%- if last_tool_call.name is none %}
326
+ {{- raise_exception("Message has tool role, but there was no previous assistant message with a tool call!") }}
327
+ {%- endif %}
328
+ {{- "<|start|>functions." + last_tool_call.name }}
329
+ {{- " to=assistant<|channel|>commentary<|message|>" + message.content|tojson + "<|end|>" }}
330
+ {%- elif message.role == 'user' -%}
331
+ {{- "<|start|>user<|message|>" + message.content + "<|end|>" }}
332
+ {%- endif -%}
333
+ {%- endfor -%}
334
+
335
+ {#- Generation prompt #}
336
+ {%- if add_generation_prompt -%}
337
+ <|start|>assistant
338
+ {%- endif -%}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/llama3.jinja ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|>
2
+
3
+ '+ message['content'] | trim + '<|eot_id|>' %}{% if loop.index0 == 0 %}{% set content = bos_token + content %}{% endif %}{{ content }}{% endfor %}{% if add_generation_prompt %}{{ '<|start_header_id|>assistant<|end_header_id|>
4
+
5
+ ' }}{% endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/llama3_1.jinja ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{- bos_token }}
2
+ {%- if custom_tools is defined %}
3
+ {%- set tools = custom_tools %}
4
+ {%- endif %}
5
+ {%- if not tools_in_user_message is defined %}
6
+ {%- set tools_in_user_message = true %}
7
+ {%- endif %}
8
+ {%- if not date_string is defined %}
9
+ {%- set date_string = "26 Jul 2024" %}
10
+ {%- endif %}
11
+ {%- if not tools is defined %}
12
+ {%- set tools = none %}
13
+ {%- endif %}
14
+
15
+ {#- This block extracts the system message, so we can slot it into the right place. #}
16
+ {%- if messages[0]['role'] == 'system' %}
17
+ {%- set system_message = messages[0]['content']|trim %}
18
+ {%- set messages = messages[1:] %}
19
+ {%- else %}
20
+ {%- set system_message = "" %}
21
+ {%- endif %}
22
+
23
+ {#- System message + builtin tools #}
24
+ {{- "<|start_header_id|>system<|end_header_id|>\n\n" }}
25
+ {%- if builtin_tools is defined or tools is not none %}
26
+ {{- "Environment: ipython\n" }}
27
+ {%- endif %}
28
+ {%- if builtin_tools is defined %}
29
+ {{- "Tools: " + builtin_tools | reject('equalto', 'code_interpreter') | join(", ") + "\n\n"}}
30
+ {%- endif %}
31
+ {{- "Cutting Knowledge Date: December 2023\n" }}
32
+ {{- "Today Date: " + date_string + "\n\n" }}
33
+ {%- if tools is not none and not tools_in_user_message %}
34
+ {{- "You have access to the following functions. To call a function, please respond with JSON for a function call." }}
35
+ {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }}
36
+ {{- "Do not use variables.\n\n" }}
37
+ {%- for t in tools %}
38
+ {{- t | tojson(indent=4) }}
39
+ {{- "\n\n" }}
40
+ {%- endfor %}
41
+ {%- endif %}
42
+ {{- system_message }}
43
+ {{- "<|eot_id|>" }}
44
+
45
+ {#- Custom tools are passed in a user message with some extra guidance #}
46
+ {%- if tools_in_user_message and not tools is none %}
47
+ {#- Extract the first user message so we can plug it in here #}
48
+ {%- if messages | length != 0 %}
49
+ {%- set first_user_message = messages[0]['content']|trim %}
50
+ {%- set messages = messages[1:] %}
51
+ {%- else %}
52
+ {{- raise_exception("Cannot put tools in the first user message when there's no first user message!") }}
53
+ {%- endif %}
54
+ {{- '<|start_header_id|>user<|end_header_id|>\n\n' -}}
55
+ {{- "Given the following functions, please respond with a JSON for a function call " }}
56
+ {{- "with its proper arguments that best answers the given prompt.\n\n" }}
57
+ {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }}
58
+ {{- "Do not use variables.\n\n" }}
59
+ {%- for t in tools %}
60
+ {{- t | tojson(indent=4) }}
61
+ {{- "\n\n" }}
62
+ {%- endfor %}
63
+ {{- first_user_message + "<|eot_id|>"}}
64
+ {%- endif %}
65
+
66
+ {%- for message in messages %}
67
+ {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %}
68
+ {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n'+ message['content'] | trim + '<|eot_id|>' }}
69
+ {%- elif 'tool_calls' in message %}
70
+ {%- if not message.tool_calls|length == 1 %}
71
+ {{- raise_exception("This model only supports single tool-calls at once!") }}
72
+ {%- endif %}
73
+ {%- set tool_call = message.tool_calls[0].function %}
74
+ {%- if builtin_tools is defined and tool_call.name in builtin_tools %}
75
+ {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' -}}
76
+ {{- "<|python_tag|>" + tool_call.name + ".call(" }}
77
+ {%- for arg_name, arg_val in tool_call.arguments | items %}
78
+ {{- arg_name + '="' + arg_val + '"' }}
79
+ {%- if not loop.last %}
80
+ {{- ", " }}
81
+ {%- endif %}
82
+ {%- endfor %}
83
+ {{- ")" }}
84
+ {%- else %}
85
+ {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' -}}
86
+ {{- '{"name": "' + tool_call.name + '", ' }}
87
+ {{- '"parameters": ' }}
88
+ {{- tool_call.arguments | tojson }}
89
+ {{- "}" }}
90
+ {%- endif %}
91
+ {%- if builtin_tools is defined %}
92
+ {#- This means we're in ipython mode #}
93
+ {{- "<|eom_id|>" }}
94
+ {%- else %}
95
+ {{- "<|eot_id|>" }}
96
+ {%- endif %}
97
+ {%- elif message.role == "tool" or message.role == "ipython" %}
98
+ {{- "<|start_header_id|>ipython<|end_header_id|>\n\n" }}
99
+ {%- if message.content is mapping or message.content is iterable %}
100
+ {{- message.content | tojson }}
101
+ {%- else %}
102
+ {{- message.content }}
103
+ {%- endif %}
104
+ {{- "<|eot_id|>" }}
105
+ {%- endif %}
106
+ {%- endfor %}
107
+ {%- if add_generation_prompt %}
108
+ {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }}
109
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/llama3_2.jinja ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{- bos_token }}
2
+ {%- if custom_tools is defined %}
3
+ {%- set tools = custom_tools %}
4
+ {%- endif %}
5
+ {%- if not tools_in_user_message is defined %}
6
+ {%- set tools_in_user_message = true %}
7
+ {%- endif %}
8
+ {%- if not date_string is defined %}
9
+ {%- if strftime_now is defined %}
10
+ {%- set date_string = strftime_now("%d %b %Y") %}
11
+ {%- else %}
12
+ {%- set date_string = "26 Jul 2024" %}
13
+ {%- endif %}
14
+ {%- endif %}
15
+ {%- if not tools is defined %}
16
+ {%- set tools = none %}
17
+ {%- endif %}
18
+
19
+ {#- This block extracts the system message, so we can slot it into the right place. #}
20
+ {%- if messages[0]['role'] == 'system' %}
21
+ {%- set system_message = messages[0]['content']|trim %}
22
+ {%- set messages = messages[1:] %}
23
+ {%- else %}
24
+ {%- set system_message = "" %}
25
+ {%- endif %}
26
+
27
+ {#- System message #}
28
+ {{- "<|start_header_id|>system<|end_header_id|>\n\n" }}
29
+ {%- if tools is not none %}
30
+ {{- "Environment: ipython\n" }}
31
+ {%- endif %}
32
+ {{- "Cutting Knowledge Date: December 2023\n" }}
33
+ {{- "Today Date: " + date_string + "\n\n" }}
34
+ {%- if tools is not none and not tools_in_user_message %}
35
+ {{- "You have access to the following functions. To call a function, please respond with JSON for a function call." }}
36
+ {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }}
37
+ {{- "Do not use variables.\n\n" }}
38
+ {%- for t in tools %}
39
+ {{- t | tojson(indent=4) }}
40
+ {{- "\n\n" }}
41
+ {%- endfor %}
42
+ {%- endif %}
43
+ {{- system_message }}
44
+ {{- "<|eot_id|>" }}
45
+
46
+ {#- Custom tools are passed in a user message with some extra guidance #}
47
+ {%- if tools_in_user_message and not tools is none %}
48
+ {#- Extract the first user message so we can plug it in here #}
49
+ {%- if messages | length != 0 %}
50
+ {%- set first_user_message = messages[0]['content']|trim %}
51
+ {%- set messages = messages[1:] %}
52
+ {%- else %}
53
+ {{- raise_exception("Cannot put tools in the first user message when there's no first user message!") }}
54
+ {%- endif %}
55
+ {{- '<|start_header_id|>user<|end_header_id|>\n\n' -}}
56
+ {{- "Given the following functions, please respond with a JSON for a function call " }}
57
+ {{- "with its proper arguments that best answers the given prompt.\n\n" }}
58
+ {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }}
59
+ {{- "Do not use variables.\n\n" }}
60
+ {%- for t in tools %}
61
+ {{- t | tojson(indent=4) }}
62
+ {{- "\n\n" }}
63
+ {%- endfor %}
64
+ {{- first_user_message + "<|eot_id|>"}}
65
+ {%- endif %}
66
+
67
+ {%- for message in messages %}
68
+ {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %}
69
+ {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n'+ message['content'] | trim + '<|eot_id|>' }}
70
+ {%- elif 'tool_calls' in message %}
71
+ {%- if not message.tool_calls|length == 1 %}
72
+ {{- raise_exception("This model only supports single tool-calls at once!") }}
73
+ {%- endif %}
74
+ {%- set tool_call = message.tool_calls[0].function %}
75
+ {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' -}}
76
+ {{- '{"name": "' + tool_call.name + '", ' }}
77
+ {{- '"parameters": ' }}
78
+ {{- tool_call.arguments | tojson }}
79
+ {{- "}" }}
80
+ {{- "<|eot_id|>" }}
81
+ {%- elif message.role == "tool" or message.role == "ipython" %}
82
+ {{- "<|start_header_id|>ipython<|end_header_id|>\n\n" }}
83
+ {%- if message.content is mapping or message.content is iterable %}
84
+ {{- message.content | tojson }}
85
+ {%- else %}
86
+ {{- message.content }}
87
+ {%- endif %}
88
+ {{- "<|eot_id|>" }}
89
+ {%- endif %}
90
+ {%- endfor %}
91
+ {%- if add_generation_prompt %}
92
+ {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }}
93
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/llama3_training.jinja ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Llama 3 chat template (see llama3.jinja for the original).
2
+ Modifications vs the original:
3
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
4
+ assistant-only loss masking in SFT training.
5
+ -#}
6
+ {%- for message in messages %}
7
+ {%- if loop.index0 == 0 %}{{- bos_token }}{%- endif %}
8
+ {%- if message['role'] == 'assistant' %}
9
+ {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }}
10
+ {%- generation %}
11
+ {{- message['content'] | trim + '<|eot_id|>' }}
12
+ {%- endgeneration %}
13
+ {%- else %}
14
+ {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n' + message['content'] | trim + '<|eot_id|>' }}
15
+ {%- endif %}
16
+ {%- endfor %}
17
+ {%- if add_generation_prompt %}
18
+ {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }}
19
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/llava_next.jinja ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {% for message in messages %}{% if message['role'] == 'system' %}{{ '<<SYS>>
2
+ ' + message['content'][0]['text'] + '
3
+ <</SYS>>
4
+
5
+ ' }}{% elif message['role'] == 'user' %}{{ '[INST] ' }}{# Render all images first #}{% for content in message['content'] | selectattr('type', 'equalto', 'image') %}{{ '<image>
6
+ ' }}{% endfor %}{# Render all text next #}{% for content in message['content'] | selectattr('type', 'equalto', 'text') %}{{ content['text'] }}{% endfor %}{{' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ ' ' + message['content'][0]['text'] + '</s> '}}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/llava_next_training.jinja ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Llava-Next chat template (see llava_next.jinja for the original).
2
+ Modifications vs the original:
3
+ - Added {% generation %} / {% endgeneration %} around the assistant message output to support
4
+ assistant-only loss masking in SFT training.
5
+ -#}
6
+ {% for message in messages %}{% if message['role'] == 'system' %}{{ '<<SYS>>
7
+ ' + message['content'][0]['text'] + '
8
+ <</SYS>>
9
+
10
+ ' }}{% elif message['role'] == 'user' %}{{ '[INST] ' }}{# Render all images first #}{% for content in message['content'] | selectattr('type', 'equalto', 'image') %}{{ '<image>
11
+ ' }}{% endfor %}{# Render all text next #}{% for content in message['content'] | selectattr('type', 'equalto', 'text') %}{{ content['text'] }}{% endfor %}{{' [/INST]' }}{% elif message['role'] == 'assistant' %}{% generation %}{{ ' ' + message['content'][0]['text'] + '</s> '}}{% endgeneration %}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/nemotron_3_nano.jinja ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% macro render_extra_keys(json_dict, handled_keys) %}
2
+ {%- if json_dict is mapping %}
3
+ {%- for json_key in json_dict if json_key not in handled_keys %}
4
+ {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
5
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
6
+ {%- else %}
7
+ {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
8
+ {%- endif %}
9
+ {%- endfor %}
10
+ {%- endif %}
11
+ {% endmacro %}
12
+ {%- set enable_thinking = enable_thinking if enable_thinking is defined else True %}
13
+ {%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %}
14
+
15
+ {%- set ns = namespace(last_user_idx = -1) %}
16
+ {%- set loop_messages = messages %}
17
+ {%- for m in loop_messages %}
18
+ {%- if m["role"] == "user" %}
19
+ {%- set ns.last_user_idx = loop.index0 %}
20
+ {%- endif %}
21
+ {%- endfor %}
22
+
23
+ {%- if messages[0]["role"] == "system" %}
24
+ {%- set system_message = messages[0]["content"] %}
25
+ {%- set loop_messages = messages[1:] %}
26
+ {%- else %}
27
+ {%- set system_message = "" %}
28
+ {%- set loop_messages = messages %}
29
+ {%- endif %}
30
+ {%- if not tools is defined %}
31
+ {%- set tools = [] %}
32
+ {%- endif %}
33
+ {# Recompute last_user_idx relative to loop_messages after handling system #}
34
+ {%- set ns = namespace(last_user_idx = -1) %}
35
+ {%- for m in loop_messages %}
36
+ {%- if m["role"] == "user" %}
37
+ {%- set ns.last_user_idx = loop.index0 %}
38
+ {%- endif %}
39
+ {%- endfor %}
40
+ {%- if system_message is defined %}
41
+ {{- "<|im_start|>system\n" + system_message }}
42
+ {%- else %}
43
+ {%- if tools is iterable and tools | length > 0 %}
44
+ {{- "<|im_start|>system\n" }}
45
+ {%- endif %}
46
+ {%- endif %}
47
+ {%- if tools is iterable and tools | length > 0 %}
48
+ {%- if system_message is defined and system_message | length > 0 %}
49
+ {{- "\n\n" }}
50
+ {%- endif %}
51
+ {{- "# Tools\n\nYou have access to the following functions:\n\n" }}
52
+ {{- "<tools>" }}
53
+ {%- for tool in tools %}
54
+ {%- if tool.function is defined %}
55
+ {%- set tool = tool.function %}
56
+ {%- endif %}
57
+ {{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
58
+ {%- if tool.description is defined %}
59
+ {{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
60
+ {%- endif %}
61
+ {{- '\n<parameters>' }}
62
+ {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
63
+ {%- for param_name, param_fields in tool.parameters.properties|items %}
64
+ {{- '\n<parameter>' }}
65
+ {{- '\n<name>' ~ param_name ~ '</name>' }}
66
+ {%- if param_fields.type is defined %}
67
+ {{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
68
+ {%- endif %}
69
+ {%- if param_fields.description is defined %}
70
+ {{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
71
+ {%- endif %}
72
+ {%- if param_fields.enum is defined %}
73
+ {{- '\n<enum>' ~ (param_fields.enum | tojson | safe) ~ '</enum>' }}
74
+ {%- endif %}
75
+ {%- set handled_keys = ['name', 'type', 'description', 'enum'] %}
76
+ {{- render_extra_keys(param_fields, handled_keys) }}
77
+ {{- '\n</parameter>' }}
78
+ {%- endfor %}
79
+ {%- endif %}
80
+ {% set handled_keys = ['type', 'properties', 'required'] %}
81
+ {{- render_extra_keys(tool.parameters, handled_keys) }}
82
+ {%- if tool.parameters is defined and tool.parameters.required is defined %}
83
+ {{- '\n<required>' ~ (tool.parameters.required | tojson | safe) ~ '</required>' }}
84
+ {%- endif %}
85
+ {{- '\n</parameters>' }}
86
+ {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
87
+ {{- render_extra_keys(tool, handled_keys) }}
88
+ {{- '\n</function>' }}
89
+ {%- endfor %}
90
+ {{- "\n</tools>" }}
91
+
92
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
93
+ {%- endif %}
94
+
95
+
96
+ {%- if system_message is defined %}
97
+ {{- '<|im_end|>\n' }}
98
+ {%- else %}
99
+ {%- if tools is iterable and tools | length > 0 %}
100
+ {{- '<|im_end|>\n' }}
101
+ {%- endif %}
102
+ {%- endif %}
103
+
104
+ {%- for message in loop_messages %}
105
+ {%- if message.role == "assistant" %}
106
+ {# Add reasoning content in to content field for unified processing below. #}
107
+ {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %}
108
+ {%- set content = "<think>\n" ~ message.reasoning_content ~ "\n</think>\n" ~ (message.content | default('', true)) %}
109
+ {%- else %}
110
+ {%- set content = message.content | default('', true) %}
111
+ {%- if content is string -%}
112
+ {# Allow downstream logic to to take care of broken thought, only handle coherent reasoning here. #}
113
+ {%- if '<think>' not in content and '</think>' not in content -%}
114
+ {%- set content = "<think></think>" ~ content -%}
115
+ {%- endif -%}
116
+ {%- else -%}
117
+ {%- set content = content -%}
118
+ {%- endif -%}
119
+ {%- endif %}
120
+ {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
121
+ {# Assistant message has tool calls. #}
122
+ {{- '<|im_start|>assistant\n' }}
123
+ {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
124
+ {%- if content is string and content | trim | length > 0 %}
125
+ {%- if include_content %}
126
+ {{- (content | trim) ~ '\n' -}}
127
+ {%- else %}
128
+ {%- set c = (content | string) %}
129
+ {%- if '</think>' in c %}
130
+ {# Keep only content after the last closing think. Also generation prompt causes this. #}
131
+ {%- set c = c.split('</think>')[-1] %}
132
+ {%- elif '<think>' in c %}
133
+ {# If <think> was opened but never closed, drop the trailing think segment #}
134
+ {%- set c = c.split('<think>')[0] %}
135
+ {%- endif %}
136
+ {%- set c = "<think></think>" ~ c | trim %}
137
+ {%- if c | length > 0 %}
138
+ {{- c ~ '\n' -}}
139
+ {%- endif %}
140
+ {%- endif %}
141
+ {%- else %}
142
+ {{- "<think></think>" -}}
143
+ {%- endif %}
144
+ {%- for tool_call in message.tool_calls %}
145
+ {%- if tool_call.function is defined %}
146
+ {%- set tool_call = tool_call.function %}
147
+ {%- endif %}
148
+ {{- '<tool_call>\n<function=' ~ tool_call.name ~ '>\n' -}}
149
+ {%- if tool_call.arguments is defined %}
150
+ {%- for args_name, args_value in tool_call.arguments|items %}
151
+ {{- '<parameter=' ~ args_name ~ '>\n' -}}
152
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
153
+ {{- args_value ~ '\n</parameter>\n' -}}
154
+ {%- endfor %}
155
+ {%- endif %}
156
+ {{- '</function>\n</tool_call>\n' -}}
157
+ {%- endfor %}
158
+ {{- '<|im_end|>\n' }}
159
+ {%- else %}
160
+ {# Assistant message doesn't have tool calls. #}
161
+ {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
162
+ {{- '<|im_start|>assistant\n' ~ (content | default('', true) | string | trim) ~ '<|im_end|>\n' }}
163
+ {%- else %}
164
+ {%- set c = (content | default('', true) | string) %}
165
+ {%- if '<think>' in c and '</think>' in c %}
166
+ {%- set c = "<think></think>" ~ c.split('</think>')[-1] %}
167
+ {%- endif %}
168
+ {%- set c = c | trim %}
169
+ {%- if c | length > 0 %}
170
+ {{- '<|im_start|>assistant\n' ~ c ~ '<|im_end|>\n' }}
171
+ {%- else %}
172
+ {{- '<|im_start|>assistant\n<|im_end|>\n' }}
173
+ {%- endif %}
174
+ {%- endif %}
175
+ {%- endif %}
176
+ {%- elif message.role == "user" or message.role == "system" %}
177
+ {{- '<|im_start|>' + message.role + '\n' }}
178
+ {%- set content = message.content | string %}
179
+ {{- content }}
180
+ {{- '<|im_end|>\n' }}
181
+ {%- elif message.role == "tool" %}
182
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
183
+ {{- '<|im_start|>user\n' }}
184
+ {%- endif %}
185
+ {{- '<tool_response>\n' }}
186
+ {{- message.content }}
187
+ {{- '\n</tool_response>\n' }}
188
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
189
+ {{- '<|im_end|>\n' }}
190
+ {%- elif loop.last %}
191
+ {{- '<|im_end|>\n' }}
192
+ {%- endif %}
193
+ {%- else %}
194
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
195
+ {%- endif %}
196
+ {%- endfor %}
197
+
198
+ {%- if add_generation_prompt %}
199
+ {%- if enable_thinking %}
200
+ {{- '<|im_start|>assistant\n<think>\n' }}
201
+ {%- else %}
202
+ {{- '<|im_start|>assistant\n<think></think>' }}
203
+ {%- endif %}
204
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/nemotron_3_nano_training.jinja ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Nemotron Nano chat template (see nemotron_3_nano.jinja for the original).
2
+ Modifications vs the original:
3
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
4
+ assistant-only loss masking in SFT training.
5
+ -#}
6
+ {% macro render_extra_keys(json_dict, handled_keys) %}
7
+ {%- if json_dict is mapping %}
8
+ {%- for json_key in json_dict if json_key not in handled_keys %}
9
+ {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
10
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
11
+ {%- else %}
12
+ {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
13
+ {%- endif %}
14
+ {%- endfor %}
15
+ {%- endif %}
16
+ {% endmacro %}
17
+ {%- set enable_thinking = enable_thinking if enable_thinking is defined else True %}
18
+ {%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %}
19
+
20
+ {%- set ns = namespace(last_user_idx = -1) %}
21
+ {%- set loop_messages = messages %}
22
+ {%- for m in loop_messages %}
23
+ {%- if m["role"] == "user" %}
24
+ {%- set ns.last_user_idx = loop.index0 %}
25
+ {%- endif %}
26
+ {%- endfor %}
27
+
28
+ {%- if messages[0]["role"] == "system" %}
29
+ {%- set system_message = messages[0]["content"] %}
30
+ {%- set loop_messages = messages[1:] %}
31
+ {%- else %}
32
+ {%- set system_message = "" %}
33
+ {%- set loop_messages = messages %}
34
+ {%- endif %}
35
+ {%- if not tools is defined %}
36
+ {%- set tools = [] %}
37
+ {%- endif %}
38
+ {# Recompute last_user_idx relative to loop_messages after handling system #}
39
+ {%- set ns = namespace(last_user_idx = -1) %}
40
+ {%- for m in loop_messages %}
41
+ {%- if m["role"] == "user" %}
42
+ {%- set ns.last_user_idx = loop.index0 %}
43
+ {%- endif %}
44
+ {%- endfor %}
45
+ {%- if system_message is defined %}
46
+ {{- "<|im_start|>system\n" + system_message }}
47
+ {%- else %}
48
+ {%- if tools is iterable and tools | length > 0 %}
49
+ {{- "<|im_start|>system\n" }}
50
+ {%- endif %}
51
+ {%- endif %}
52
+ {%- if tools is iterable and tools | length > 0 %}
53
+ {%- if system_message is defined and system_message | length > 0 %}
54
+ {{- "\n\n" }}
55
+ {%- endif %}
56
+ {{- "# Tools\n\nYou have access to the following functions:\n\n" }}
57
+ {{- "<tools>" }}
58
+ {%- for tool in tools %}
59
+ {%- if tool.function is defined %}
60
+ {%- set tool = tool.function %}
61
+ {%- endif %}
62
+ {{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
63
+ {%- if tool.description is defined %}
64
+ {{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
65
+ {%- endif %}
66
+ {{- '\n<parameters>' }}
67
+ {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
68
+ {%- for param_name, param_fields in tool.parameters.properties|items %}
69
+ {{- '\n<parameter>' }}
70
+ {{- '\n<name>' ~ param_name ~ '</name>' }}
71
+ {%- if param_fields.type is defined %}
72
+ {{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
73
+ {%- endif %}
74
+ {%- if param_fields.description is defined %}
75
+ {{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
76
+ {%- endif %}
77
+ {%- if param_fields.enum is defined %}
78
+ {{- '\n<enum>' ~ (param_fields.enum | tojson | safe) ~ '</enum>' }}
79
+ {%- endif %}
80
+ {%- set handled_keys = ['name', 'type', 'description', 'enum'] %}
81
+ {{- render_extra_keys(param_fields, handled_keys) }}
82
+ {{- '\n</parameter>' }}
83
+ {%- endfor %}
84
+ {%- endif %}
85
+ {% set handled_keys = ['type', 'properties', 'required'] %}
86
+ {{- render_extra_keys(tool.parameters, handled_keys) }}
87
+ {%- if tool.parameters is defined and tool.parameters.required is defined %}
88
+ {{- '\n<required>' ~ (tool.parameters.required | tojson | safe) ~ '</required>' }}
89
+ {%- endif %}
90
+ {{- '\n</parameters>' }}
91
+ {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
92
+ {{- render_extra_keys(tool, handled_keys) }}
93
+ {{- '\n</function>' }}
94
+ {%- endfor %}
95
+ {{- "\n</tools>" }}
96
+
97
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
98
+ {%- endif %}
99
+
100
+
101
+ {%- if system_message is defined %}
102
+ {{- '<|im_end|>\n' }}
103
+ {%- else %}
104
+ {%- if tools is iterable and tools | length > 0 %}
105
+ {{- '<|im_end|>\n' }}
106
+ {%- endif %}
107
+ {%- endif %}
108
+
109
+ {%- for message in loop_messages %}
110
+ {%- if message.role == "assistant" %}
111
+ {# Add reasoning content in to content field for unified processing below. #}
112
+ {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %}
113
+ {%- set content = "<think>\n" ~ message.reasoning_content ~ "\n</think>\n" ~ (message.content | default('', true)) %}
114
+ {%- else %}
115
+ {%- set content = message.content | default('', true) %}
116
+ {%- if content is string -%}
117
+ {# Allow downstream logic to to take care of broken thought, only handle coherent reasoning here. #}
118
+ {%- if '<think>' not in content and '</think>' not in content -%}
119
+ {%- set content = "<think></think>" ~ content -%}
120
+ {%- endif -%}
121
+ {%- else -%}
122
+ {%- set content = content -%}
123
+ {%- endif -%}
124
+ {%- endif %}
125
+ {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
126
+ {# Assistant message has tool calls. #}
127
+ {{- '<|im_start|>assistant\n' }}
128
+ {%- generation %}
129
+ {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
130
+ {%- if content is string and content | trim | length > 0 %}
131
+ {%- if include_content %}
132
+ {{- (content | trim) ~ '\n' -}}
133
+ {%- else %}
134
+ {%- set c = (content | string) %}
135
+ {%- if '</think>' in c %}
136
+ {# Keep only content after the last closing think. Also generation prompt causes this. #}
137
+ {%- set c = c.split('</think>')[-1] %}
138
+ {%- elif '<think>' in c %}
139
+ {# If <think> was opened but never closed, drop the trailing think segment #}
140
+ {%- set c = c.split('<think>')[0] %}
141
+ {%- endif %}
142
+ {%- set c = "<think></think>" ~ c | trim %}
143
+ {%- if c | length > 0 %}
144
+ {{- c ~ '\n' -}}
145
+ {%- endif %}
146
+ {%- endif %}
147
+ {%- else %}
148
+ {{- "<think></think>" -}}
149
+ {%- endif %}
150
+ {%- for tool_call in message.tool_calls %}
151
+ {%- if tool_call.function is defined %}
152
+ {%- set tool_call = tool_call.function %}
153
+ {%- endif %}
154
+ {{- '<tool_call>\n<function=' ~ tool_call.name ~ '>\n' -}}
155
+ {%- if tool_call.arguments is defined %}
156
+ {%- for args_name, args_value in tool_call.arguments|items %}
157
+ {{- '<parameter=' ~ args_name ~ '>\n' -}}
158
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
159
+ {{- args_value ~ '\n</parameter>\n' -}}
160
+ {%- endfor %}
161
+ {%- endif %}
162
+ {{- '</function>\n</tool_call>\n' -}}
163
+ {%- endfor %}
164
+ {{- '<|im_end|>\n' }}
165
+ {%- endgeneration %}
166
+ {%- else %}
167
+ {# Assistant message doesn't have tool calls. #}
168
+ {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
169
+ {{- '<|im_start|>assistant\n' }}
170
+ {%- generation %}
171
+ {{- (content | default('', true) | string | trim) ~ '<|im_end|>\n' }}
172
+ {%- endgeneration %}
173
+ {%- else %}
174
+ {%- set c = (content | default('', true) | string) %}
175
+ {%- if '<think>' in c and '</think>' in c %}
176
+ {%- set c = "<think></think>" ~ c.split('</think>')[-1] %}
177
+ {%- endif %}
178
+ {%- set c = c | trim %}
179
+ {%- if c | length > 0 %}
180
+ {{- '<|im_start|>assistant\n' }}
181
+ {%- generation %}
182
+ {{- c ~ '<|im_end|>\n' }}
183
+ {%- endgeneration %}
184
+ {%- else %}
185
+ {{- '<|im_start|>assistant\n' }}
186
+ {%- generation %}
187
+ {{- '<|im_end|>\n' }}
188
+ {%- endgeneration %}
189
+ {%- endif %}
190
+ {%- endif %}
191
+ {%- endif %}
192
+ {%- elif message.role == "user" or message.role == "system" %}
193
+ {{- '<|im_start|>' + message.role + '\n' }}
194
+ {%- set content = message.content | string %}
195
+ {{- content }}
196
+ {{- '<|im_end|>\n' }}
197
+ {%- elif message.role == "tool" %}
198
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
199
+ {{- '<|im_start|>user\n' }}
200
+ {%- endif %}
201
+ {{- '<tool_response>\n' }}
202
+ {{- message.content }}
203
+ {{- '\n</tool_response>\n' }}
204
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
205
+ {{- '<|im_end|>\n' }}
206
+ {%- elif loop.last %}
207
+ {{- '<|im_end|>\n' }}
208
+ {%- endif %}
209
+ {%- else %}
210
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
211
+ {%- endif %}
212
+ {%- endfor %}
213
+
214
+ {%- if add_generation_prompt %}
215
+ {%- if enable_thinking %}
216
+ {{- '<|im_start|>assistant\n<think>\n' }}
217
+ {%- else %}
218
+ {{- '<|im_start|>assistant\n<think></think>' }}
219
+ {%- endif %}
220
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/nemotron_3_super.jinja ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% macro render_extra_keys(json_dict, handled_keys) %}
2
+ {%- if json_dict is mapping %}
3
+ {%- for json_key in json_dict if json_key not in handled_keys %}
4
+ {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
5
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
6
+ {%- else %}
7
+ {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
8
+ {%- endif %}
9
+ {%- endfor %}
10
+ {%- endif %}
11
+ {% endmacro %}
12
+ {%- set enable_thinking = enable_thinking if enable_thinking is defined else True %}
13
+ {%- set low_effort = low_effort if low_effort is defined else False %}
14
+ {%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %}
15
+
16
+ {%- set ns = namespace(last_user_idx = -1) %}
17
+ {%- set loop_messages = messages %}
18
+ {%- for m in loop_messages %}
19
+ {%- if m["role"] == "user" %}
20
+ {%- set ns.last_user_idx = loop.index0 %}
21
+ {%- endif %}
22
+ {%- endfor %}
23
+
24
+ {%- if messages[0]["role"] == "system" %}
25
+ {%- set system_message = messages[0]["content"] %}
26
+ {%- set loop_messages = messages[1:] %}
27
+ {%- else %}
28
+ {%- set system_message = "" %}
29
+ {%- set loop_messages = messages %}
30
+ {%- endif %}
31
+ {%- if not tools is defined %}
32
+ {%- set tools = [] %}
33
+ {%- endif %}
34
+ {# Recompute last_user_idx relative to loop_messages after handling system #}
35
+ {%- set ns = namespace(last_user_idx = -1) %}
36
+ {%- for m in loop_messages %}
37
+ {%- if m["role"] == "user" %}
38
+ {%- set ns.last_user_idx = loop.index0 %}
39
+ {%- endif %}
40
+ {%- endfor %}
41
+ {%- if system_message is defined %}
42
+ {{- "<|im_start|>system\n" + system_message }}
43
+ {%- else %}
44
+ {%- if tools is iterable and tools | length > 0 %}
45
+ {{- "<|im_start|>system\n" }}
46
+ {%- endif %}
47
+ {%- endif %}
48
+ {%- if tools is iterable and tools | length > 0 %}
49
+ {%- if system_message is defined and system_message | length > 0 %}
50
+ {{- "\n\n" }}
51
+ {%- endif %}
52
+ {{- "# Tools\n\nYou have access to the following functions:\n\n" }}
53
+ {{- "<tools>" }}
54
+ {%- for tool in tools %}
55
+ {%- if tool.function is defined %}
56
+ {%- set tool = tool.function %}
57
+ {%- endif %}
58
+ {{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
59
+ {%- if tool.description is defined %}
60
+ {{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
61
+ {%- endif %}
62
+ {{- '\n<parameters>' }}
63
+ {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
64
+ {%- for param_name, param_fields in tool.parameters.properties|items %}
65
+ {{- '\n<parameter>' }}
66
+ {{- '\n<name>' ~ param_name ~ '</name>' }}
67
+ {%- if param_fields.type is defined %}
68
+ {{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
69
+ {%- endif %}
70
+ {%- if param_fields.description is defined %}
71
+ {{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
72
+ {%- endif %}
73
+ {%- if param_fields.enum is defined %}
74
+ {{- '\n<enum>' ~ (param_fields.enum | tojson | safe) ~ '</enum>' }}
75
+ {%- endif %}
76
+ {%- set handled_keys = ['name', 'type', 'description', 'enum'] %}
77
+ {{- render_extra_keys(param_fields, handled_keys) }}
78
+ {{- '\n</parameter>' }}
79
+ {%- endfor %}
80
+ {%- endif %}
81
+ {% set handled_keys = ['type', 'properties', 'required'] %}
82
+ {{- render_extra_keys(tool.parameters, handled_keys) }}
83
+ {%- if tool.parameters is defined and tool.parameters.required is defined %}
84
+ {{- '\n<required>' ~ (tool.parameters.required | tojson | safe) ~ '</required>' }}
85
+ {%- endif %}
86
+ {{- '\n</parameters>' }}
87
+ {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
88
+ {{- render_extra_keys(tool, handled_keys) }}
89
+ {{- '\n</function>' }}
90
+ {%- endfor %}
91
+ {{- "\n</tools>" }}
92
+
93
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
94
+ {%- endif %}
95
+
96
+
97
+ {%- if system_message is defined %}
98
+ {{- '<|im_end|>\n' }}
99
+ {%- else %}
100
+ {%- if tools is iterable and tools | length > 0 %}
101
+ {{- '<|im_end|>\n' }}
102
+ {%- endif %}
103
+ {%- endif %}
104
+
105
+ {%- for message in loop_messages %}
106
+ {%- if message.role == "assistant" %}
107
+ {# Add reasoning content in to content field for unified processing below. #}
108
+ {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %}
109
+ {%- set content = "<think>\n" ~ message.reasoning_content ~ "\n</think>\n" ~ (message.content | default('', true)) %}
110
+ {%- else %}
111
+ {%- set content = message.content | default('', true) %}
112
+ {%- if content is string -%}
113
+ {# Allow downstream logic to to take care of broken thought, only handle coherent reasoning here. #}
114
+ {%- if '<think>' not in content and '</think>' not in content -%}
115
+ {%- set content = "<think></think>" ~ content -%}
116
+ {%- endif -%}
117
+ {%- else -%}
118
+ {%- set content = content -%}
119
+ {%- endif -%}
120
+ {%- endif %}
121
+ {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
122
+ {# Assistant message has tool calls. #}
123
+ {{- '<|im_start|>assistant\n' }}
124
+ {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
125
+ {%- if content is string and content | trim | length > 0 %}
126
+ {%- if include_content %}
127
+ {{- (content | trim) ~ '\n' -}}
128
+ {%- else %}
129
+ {%- set c = (content | string) %}
130
+ {%- if '</think>' in c %}
131
+ {# Keep only content after the last closing think. Also generation prompt causes this. #}
132
+ {%- set c = c.split('</think>')[-1] %}
133
+ {%- elif '<think>' in c %}
134
+ {# If <think> was opened but never closed, drop the trailing think segment #}
135
+ {%- set c = c.split('<think>')[0] %}
136
+ {%- endif %}
137
+ {%- set c = "<think></think>" ~ c | trim %}
138
+ {%- if c | length > 0 %}
139
+ {{- c ~ '\n' -}}
140
+ {%- endif %}
141
+ {%- endif %}
142
+ {%- else %}
143
+ {{- "<think></think>" -}}
144
+ {%- endif %}
145
+ {%- for tool_call in message.tool_calls %}
146
+ {%- if tool_call.function is defined %}
147
+ {%- set tool_call = tool_call.function %}
148
+ {%- endif %}
149
+ {{- '<tool_call>\n<function=' ~ tool_call.name ~ '>\n' -}}
150
+ {%- if tool_call.arguments is defined %}
151
+ {%- for args_name, args_value in tool_call.arguments|items %}
152
+ {{- '<parameter=' ~ args_name ~ '>\n' -}}
153
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
154
+ {{- args_value ~ '\n</parameter>\n' -}}
155
+ {%- endfor %}
156
+ {%- endif %}
157
+ {{- '</function>\n</tool_call>\n' -}}
158
+ {%- endfor %}
159
+ {{- '<|im_end|>\n' }}
160
+ {%- else %}
161
+ {# Assistant message doesn't have tool calls. #}
162
+ {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
163
+ {{- '<|im_start|>assistant\n' ~ (content | default('', true) | string | trim) ~ '<|im_end|>\n' }}
164
+ {%- else %}
165
+ {%- set c = (content | default('', true) | string) %}
166
+ {%- if '<think>' in c and '</think>' in c %}
167
+ {%- set c = "<think></think>" ~ c.split('</think>')[-1] %}
168
+ {%- endif %}
169
+ {%- set c = c | trim %}
170
+ {%- if c | length > 0 %}
171
+ {{- '<|im_start|>assistant\n' ~ c ~ '<|im_end|>\n' }}
172
+ {%- else %}
173
+ {{- '<|im_start|>assistant\n<|im_end|>\n' }}
174
+ {%- endif %}
175
+ {%- endif %}
176
+ {%- endif %}
177
+ {%- elif message.role == "user" or message.role == "system" %}
178
+ {{- '<|im_start|>' + message.role + '\n' }}
179
+ {%- set content = message.content | string %}
180
+ {%- if message.role == "user" and loop.index0 == ns.last_user_idx and low_effort %}
181
+ {{- content + '\n\n{reasoning effort: low}' }}
182
+ {%- else %}
183
+ {{- content }}
184
+ {%- endif %}
185
+ {{- '<|im_end|>\n' }}
186
+ {%- elif message.role == "tool" %}
187
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
188
+ {{- '<|im_start|>user\n' }}
189
+ {%- endif %}
190
+ {{- '<tool_response>\n' }}
191
+ {{- message.content }}
192
+ {{- '\n</tool_response>\n' }}
193
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
194
+ {{- '<|im_end|>\n' }}
195
+ {%- elif loop.last %}
196
+ {{- '<|im_end|>\n' }}
197
+ {%- endif %}
198
+ {%- else %}
199
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
200
+ {%- endif %}
201
+ {%- endfor %}
202
+
203
+ {%- if add_generation_prompt %}
204
+ {%- if enable_thinking %}
205
+ {{- '<|im_start|>assistant\n<think>\n' }}
206
+ {%- else %}
207
+ {{- '<|im_start|>assistant\n<think></think>' }}
208
+ {%- endif %}
209
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/nemotron_3_super_training.jinja ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Nemotron Super chat template (see nemotron_3_super.jinja for the original).
2
+ The original is already prefix-preserving, so the only modification is adding
3
+ {% generation %} / {% endgeneration %} around assistant message output to support
4
+ assistant-only loss masking in SFT training. All other rendering (including the
5
+ `truncate_history_thinking` and `low_effort` logic) is identical to the original.
6
+ -#}
7
+ {% macro render_extra_keys(json_dict, handled_keys) %}
8
+ {%- if json_dict is mapping %}
9
+ {%- for json_key in json_dict if json_key not in handled_keys %}
10
+ {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
11
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
12
+ {%- else %}
13
+ {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
14
+ {%- endif %}
15
+ {%- endfor %}
16
+ {%- endif %}
17
+ {% endmacro %}
18
+ {%- set enable_thinking = enable_thinking if enable_thinking is defined else True %}
19
+ {%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %}
20
+ {%- set low_effort = low_effort if low_effort is defined else False %}
21
+
22
+ {%- set ns = namespace(last_user_idx = -1) %}
23
+ {%- set loop_messages = messages %}
24
+ {%- for m in loop_messages %}
25
+ {%- if m["role"] == "user" %}
26
+ {%- set ns.last_user_idx = loop.index0 %}
27
+ {%- endif %}
28
+ {%- endfor %}
29
+
30
+ {%- if messages[0]["role"] == "system" %}
31
+ {%- set system_message = messages[0]["content"] %}
32
+ {%- set loop_messages = messages[1:] %}
33
+ {%- else %}
34
+ {%- set system_message = "" %}
35
+ {%- set loop_messages = messages %}
36
+ {%- endif %}
37
+ {%- if not tools is defined %}
38
+ {%- set tools = [] %}
39
+ {%- endif %}
40
+ {# Recompute last_user_idx relative to loop_messages after handling system #}
41
+ {%- set ns = namespace(last_user_idx = -1) %}
42
+ {%- for m in loop_messages %}
43
+ {%- if m["role"] == "user" %}
44
+ {%- set ns.last_user_idx = loop.index0 %}
45
+ {%- endif %}
46
+ {%- endfor %}
47
+ {%- if system_message is defined %}
48
+ {{- "<|im_start|>system\n" + system_message }}
49
+ {%- else %}
50
+ {%- if tools is iterable and tools | length > 0 %}
51
+ {{- "<|im_start|>system\n" }}
52
+ {%- endif %}
53
+ {%- endif %}
54
+ {%- if tools is iterable and tools | length > 0 %}
55
+ {%- if system_message is defined and system_message | length > 0 %}
56
+ {{- "\n\n" }}
57
+ {%- endif %}
58
+ {{- "# Tools\n\nYou have access to the following functions:\n\n" }}
59
+ {{- "<tools>" }}
60
+ {%- for tool in tools %}
61
+ {%- if tool.function is defined %}
62
+ {%- set tool = tool.function %}
63
+ {%- endif %}
64
+ {{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
65
+ {%- if tool.description is defined %}
66
+ {{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
67
+ {%- endif %}
68
+ {{- '\n<parameters>' }}
69
+ {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
70
+ {%- for param_name, param_fields in tool.parameters.properties|items %}
71
+ {{- '\n<parameter>' }}
72
+ {{- '\n<name>' ~ param_name ~ '</name>' }}
73
+ {%- if param_fields.type is defined %}
74
+ {{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
75
+ {%- endif %}
76
+ {%- if param_fields.description is defined %}
77
+ {{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
78
+ {%- endif %}
79
+ {%- if param_fields.enum is defined %}
80
+ {{- '\n<enum>' ~ (param_fields.enum | tojson | safe) ~ '</enum>' }}
81
+ {%- endif %}
82
+ {%- set handled_keys = ['name', 'type', 'description', 'enum'] %}
83
+ {{- render_extra_keys(param_fields, handled_keys) }}
84
+ {{- '\n</parameter>' }}
85
+ {%- endfor %}
86
+ {%- endif %}
87
+ {% set handled_keys = ['type', 'properties', 'required'] %}
88
+ {{- render_extra_keys(tool.parameters, handled_keys) }}
89
+ {%- if tool.parameters is defined and tool.parameters.required is defined %}
90
+ {{- '\n<required>' ~ (tool.parameters.required | tojson | safe) ~ '</required>' }}
91
+ {%- endif %}
92
+ {{- '\n</parameters>' }}
93
+ {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
94
+ {{- render_extra_keys(tool, handled_keys) }}
95
+ {{- '\n</function>' }}
96
+ {%- endfor %}
97
+ {{- "\n</tools>" }}
98
+
99
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
100
+ {%- endif %}
101
+
102
+
103
+ {%- if system_message is defined %}
104
+ {{- '<|im_end|>\n' }}
105
+ {%- else %}
106
+ {%- if tools is iterable and tools | length > 0 %}
107
+ {{- '<|im_end|>\n' }}
108
+ {%- endif %}
109
+ {%- endif %}
110
+
111
+ {%- for message in loop_messages %}
112
+ {%- if message.role == "assistant" %}
113
+ {# Add reasoning content in to content field for unified processing below. #}
114
+ {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %}
115
+ {%- set content = "<think>\n" ~ message.reasoning_content ~ "\n</think>\n" ~ (message.content | default('', true)) %}
116
+ {%- else %}
117
+ {%- set content = message.content | default('', true) %}
118
+ {%- if content is string -%}
119
+ {# Allow downstream logic to to take care of broken thought, only handle coherent reasoning here. #}
120
+ {%- if '<think>' not in content and '</think>' not in content -%}
121
+ {%- set content = "<think></think>" ~ content -%}
122
+ {%- endif -%}
123
+ {%- else -%}
124
+ {%- set content = content -%}
125
+ {%- endif -%}
126
+ {%- endif %}
127
+ {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
128
+ {# Assistant message has tool calls. #}
129
+ {{- '<|im_start|>assistant\n' }}
130
+ {%- generation %}
131
+ {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
132
+ {%- if content is string and content | trim | length > 0 %}
133
+ {%- if include_content %}
134
+ {{- (content | trim) ~ '\n' -}}
135
+ {%- else %}
136
+ {%- set c = (content | string) %}
137
+ {%- if '</think>' in c %}
138
+ {# Keep only content after the last closing think. Also generation prompt causes this. #}
139
+ {%- set c = c.split('</think>')[-1] %}
140
+ {%- elif '<think>' in c %}
141
+ {# If <think> was opened but never closed, drop the trailing think segment #}
142
+ {%- set c = c.split('<think>')[0] %}
143
+ {%- endif %}
144
+ {%- set c = "<think></think>" ~ c | trim %}
145
+ {%- if c | length > 0 %}
146
+ {{- c ~ '\n' -}}
147
+ {%- endif %}
148
+ {%- endif %}
149
+ {%- else %}
150
+ {{- "<think></think>" -}}
151
+ {%- endif %}
152
+ {%- for tool_call in message.tool_calls %}
153
+ {%- if tool_call.function is defined %}
154
+ {%- set tool_call = tool_call.function %}
155
+ {%- endif %}
156
+ {{- '<tool_call>\n<function=' ~ tool_call.name ~ '>\n' -}}
157
+ {%- if tool_call.arguments is defined %}
158
+ {%- for args_name, args_value in tool_call.arguments|items %}
159
+ {{- '<parameter=' ~ args_name ~ '>\n' -}}
160
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
161
+ {{- args_value ~ '\n</parameter>\n' -}}
162
+ {%- endfor %}
163
+ {%- endif %}
164
+ {{- '</function>\n</tool_call>\n' -}}
165
+ {%- endfor %}
166
+ {{- '<|im_end|>\n' }}
167
+ {%- endgeneration %}
168
+ {%- else %}
169
+ {# Assistant message doesn't have tool calls. #}
170
+ {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
171
+ {{- '<|im_start|>assistant\n' }}
172
+ {%- generation %}
173
+ {{- (content | default('', true) | string | trim) ~ '<|im_end|>\n' }}
174
+ {%- endgeneration %}
175
+ {%- else %}
176
+ {%- set c = (content | default('', true) | string) %}
177
+ {%- if '<think>' in c and '</think>' in c %}
178
+ {%- set c = "<think></think>" ~ c.split('</think>')[-1] %}
179
+ {%- endif %}
180
+ {%- set c = c | trim %}
181
+ {%- if c | length > 0 %}
182
+ {{- '<|im_start|>assistant\n' }}
183
+ {%- generation %}
184
+ {{- c ~ '<|im_end|>\n' }}
185
+ {%- endgeneration %}
186
+ {%- else %}
187
+ {{- '<|im_start|>assistant\n' }}
188
+ {%- generation %}
189
+ {{- '<|im_end|>\n' }}
190
+ {%- endgeneration %}
191
+ {%- endif %}
192
+ {%- endif %}
193
+ {%- endif %}
194
+ {%- elif message.role == "user" or message.role == "system" %}
195
+ {{- '<|im_start|>' + message.role + '\n' }}
196
+ {%- set content = message.content | string %}
197
+ {%- if message.role == "user" and loop.index0 == ns.last_user_idx and low_effort %}
198
+ {{- content + '\n\n{reasoning effort: low}' }}
199
+ {%- else %}
200
+ {{- content }}
201
+ {%- endif %}
202
+ {{- '<|im_end|>\n' }}
203
+ {%- elif message.role == "tool" %}
204
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
205
+ {{- '<|im_start|>user\n' }}
206
+ {%- endif %}
207
+ {{- '<tool_response>\n' }}
208
+ {{- message.content }}
209
+ {{- '\n</tool_response>\n' }}
210
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
211
+ {{- '<|im_end|>\n' }}
212
+ {%- elif loop.last %}
213
+ {{- '<|im_end|>\n' }}
214
+ {%- endif %}
215
+ {%- else %}
216
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
217
+ {%- endif %}
218
+ {%- endfor %}
219
+
220
+ {%- if add_generation_prompt %}
221
+ {%- if enable_thinking %}
222
+ {{- '<|im_start|>assistant\n<think>\n' }}
223
+ {%- else %}
224
+ {{- '<|im_start|>assistant\n<think></think>' }}
225
+ {%- endif %}
226
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/nemotron_3_ultra.jinja ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% macro render_extra_keys(json_dict, handled_keys) %}
2
+ {%- if json_dict is mapping %}
3
+ {%- for json_key in json_dict if json_key not in handled_keys %}
4
+ {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
5
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
6
+ {%- else %}
7
+ {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
8
+ {%- endif %}
9
+ {%- endfor %}
10
+ {%- endif %}
11
+ {% endmacro %}
12
+ {%- set enable_thinking = enable_thinking if enable_thinking is defined else True %}
13
+ {%- set medium_effort = medium_effort if medium_effort is defined else False %}
14
+ {%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %}
15
+ {%- set ns = namespace(last_user_idx = -1) %}
16
+ {%- set loop_messages = messages %}
17
+ {%- for m in loop_messages %}
18
+ {%- if m["role"] == "user" %}
19
+ {%- set ns.last_user_idx = loop.index0 %}
20
+ {%- endif %}
21
+ {%- endfor %}
22
+ {%- if messages[0]["role"] == "system" %}
23
+ {%- set system_message = messages[0]["content"] %}
24
+ {%- set loop_messages = messages[1:] %}
25
+ {%- else %}
26
+ {%- set system_message = "" %}
27
+ {%- set loop_messages = messages %}
28
+ {%- endif %}
29
+ {%- if not tools is defined %}
30
+ {%- set tools = [] %}
31
+ {%- endif %}
32
+ {%- set ns = namespace(last_user_idx = -1) %}
33
+ {%- for m in loop_messages %}
34
+ {%- if m["role"] == "user" %}
35
+ {%- set ns.last_user_idx = loop.index0 %}
36
+ {%- endif %}
37
+ {%- endfor %}
38
+ {%- if system_message is defined %}
39
+ {{- "<|im_start|>system\n" + system_message }}
40
+ {%- else %}
41
+ {%- if tools is iterable and tools | length > 0 %}
42
+ {{- "<|im_start|>system\n" }}
43
+ {%- endif %}
44
+ {%- endif %}
45
+ {%- if tools is iterable and tools | length > 0 %}
46
+ {%- if system_message is defined and system_message | length > 0 %}
47
+ {{- "\n\n" }}
48
+ {%- endif %}
49
+ {{- "# Tools\n\nYou have access to the following functions:\n\n" }}
50
+ {{- "<tools>" }}
51
+ {%- for tool in tools %}
52
+ {%- if tool.function is defined %}
53
+ {%- set tool = tool.function %}
54
+ {%- endif %}
55
+ {{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
56
+ {%- if tool.description is defined %}
57
+ {{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
58
+ {%- endif %}
59
+ {{- '\n<parameters>' }}
60
+ {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
61
+ {%- for param_name, param_fields in tool.parameters.properties|items %}
62
+ {{- '\n<parameter>' }}
63
+ {{- '\n<name>' ~ param_name ~ '</name>' }}
64
+ {%- if param_fields.type is defined %}
65
+ {{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
66
+ {%- endif %}
67
+ {%- if param_fields.description is defined %}
68
+ {{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
69
+ {%- endif %}
70
+ {%- if param_fields.enum is defined %}
71
+ {{- '\n<enum>' ~ (param_fields.enum | tojson | safe) ~ '</enum>' }}
72
+ {%- endif %}
73
+ {%- set handled_keys = ['name', 'type', 'description', 'enum'] %}
74
+ {{- render_extra_keys(param_fields, handled_keys) }}
75
+ {{- '\n</parameter>' }}
76
+ {%- endfor %}
77
+ {%- endif %}
78
+ {% set handled_keys = ['type', 'properties', 'required'] %}
79
+ {{- render_extra_keys(tool.parameters, handled_keys) }}
80
+ {%- if tool.parameters is defined and tool.parameters.required is defined %}
81
+ {{- '\n<required>' ~ (tool.parameters.required | tojson | safe) ~ '</required>' }}
82
+ {%- endif %}
83
+ {{- '\n</parameters>' }}
84
+ {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
85
+ {{- render_extra_keys(tool, handled_keys) }}
86
+ {{- '\n</function>' }}
87
+ {%- endfor %}
88
+ {{- "\n</tools>" }}
89
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
90
+ {%- endif %}
91
+ {%- if system_message is defined %}
92
+ {{- '<|im_end|>\n' }}
93
+ {%- else %}
94
+ {%- if tools is iterable and tools | length > 0 %}
95
+ {{- '<|im_end|>\n' }}
96
+ {%- endif %}
97
+ {%- endif %}
98
+ {%- for message in loop_messages %}
99
+ {%- if message.role == "assistant" %}
100
+ {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %}
101
+ {%- set content = "<think>\n" ~ message.reasoning_content ~ "</think>" ~ (message.content | default('', true)) %}
102
+ {%- else %}
103
+ {%- set content = message.content | default('', true) %}
104
+ {%- if content is string -%}
105
+ {%- if '<think>' not in content and '</think>' not in content -%}
106
+ {%- set content = "<think></think>" ~ content -%}
107
+ {%- endif -%}
108
+ {%- else -%}
109
+ {%- set content = content -%}
110
+ {%- endif -%}
111
+ {%- endif %}
112
+ {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
113
+ {{- '<|im_start|>assistant\n' }}
114
+ {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
115
+ {%- if content is string and content | trim | length > 0 %}
116
+ {%- if include_content %}
117
+ {{- (content | trim) ~ '\n' -}}
118
+ {%- else %}
119
+ {%- set c = (content | string) %}
120
+ {%- if '</think>' in c %}
121
+ {%- set c = c.split('</think>')[-1] %}
122
+ {%- elif '<think>' in c %}
123
+ {%- set c = c.split('<think>')[0] %}
124
+ {%- endif %}
125
+ {%- set c = "<think></think>" ~ c %}
126
+ {%- if c | length > 0 %}
127
+ {{- c ~ '\n' -}}
128
+ {%- endif %}
129
+ {%- endif %}
130
+ {%- else %}
131
+ {{- "<think></think>" -}}
132
+ {%- endif %}
133
+ {%- for tool_call in message.tool_calls %}
134
+ {%- if tool_call.function is defined %}
135
+ {%- set tool_call = tool_call.function %}
136
+ {%- endif %}
137
+ {{- '<tool_call>\n<function=' ~ tool_call.name ~ '>\n' -}}
138
+ {%- if tool_call.arguments is defined %}
139
+ {%- for args_name, args_value in tool_call.arguments|items %}
140
+ {{- '<parameter=' ~ args_name ~ '>\n' -}}
141
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
142
+ {{- args_value ~ '\n</parameter>\n' -}}
143
+ {%- endfor %}
144
+ {%- endif %}
145
+ {{- '</function>\n</tool_call>\n' -}}
146
+ {%- endfor %}
147
+ {{- '<|im_end|>\n' }}
148
+ {%- else %}
149
+ {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
150
+ {{- '<|im_start|>assistant\n' ~ (content | default('', true) | string | trim) ~ '<|im_end|>\n' }}
151
+ {%- else %}
152
+ {%- set c = (content | default('', true) | string) %}
153
+ {%- if '<think>' in c and '</think>' in c %}
154
+ {%- set c = "<think></think>" ~ c.split('</think>')[-1] %}
155
+ {%- endif %}
156
+ {%- set c = c | trim %}
157
+ {%- if c | length > 0 %}
158
+ {{- '<|im_start|>assistant\n' ~ c ~ '<|im_end|>\n' }}
159
+ {%- else %}
160
+ {{- '<|im_start|>assistant\n<|im_end|>\n' }}
161
+ {%- endif %}
162
+ {%- endif %}
163
+ {%- endif %}
164
+ {%- elif message.role == "user" or message.role == "system" %}
165
+ {{- '<|im_start|>' + message.role + '\n' }}
166
+ {%- set content = message.content | string %}
167
+ {%- if message.role == "user" and loop.index0 == ns.last_user_idx and medium_effort %}
168
+ {{- content + '\n\n{reasoning effort: efficient}' }}
169
+ {%- else %}
170
+ {{- content }}
171
+ {%- endif %}
172
+ {{- '<|im_end|>\n' }}
173
+ {%- elif message.role == "tool" %}
174
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
175
+ {{- '<|im_start|>user\n' }}
176
+ {%- endif %}
177
+ {{- '<tool_response>\n' }}
178
+ {{- message.content }}
179
+ {{- '\n</tool_response>\n' }}
180
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
181
+ {{- '<|im_end|>\n' }}
182
+ {%- elif loop.last %}
183
+ {{- '<|im_end|>\n' }}
184
+ {%- endif %}
185
+ {%- else %}
186
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
187
+ {%- endif %}
188
+ {%- endfor %}
189
+ {%- if add_generation_prompt %}
190
+ {%- if enable_thinking %}
191
+ {{- '<|im_start|>assistant\n<think>\n' }}
192
+ {%- else %}
193
+ {{- '<|im_start|>assistant\n<think></think>' }}
194
+ {%- endif %}
195
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/nemotron_3_ultra_training.jinja ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Nemotron Ultra chat template (see nemotron_3_ultra.jinja for the original).
2
+ The original is already prefix-preserving, so the only modification is adding
3
+ {% generation %} / {% endgeneration %} around assistant message output to support
4
+ assistant-only loss masking in SFT training. All other rendering (including the
5
+ `truncate_history_thinking` and `medium_effort` logic) is identical to the original.
6
+ -#}
7
+ {% macro render_extra_keys(json_dict, handled_keys) %}
8
+ {%- if json_dict is mapping %}
9
+ {%- for json_key in json_dict if json_key not in handled_keys %}
10
+ {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
11
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
12
+ {%- else %}
13
+ {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
14
+ {%- endif %}
15
+ {%- endfor %}
16
+ {%- endif %}
17
+ {% endmacro %}
18
+ {%- set enable_thinking = enable_thinking if enable_thinking is defined else True %}
19
+ {%- set medium_effort = medium_effort if medium_effort is defined else False %}
20
+ {%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %}
21
+ {%- set ns = namespace(last_user_idx = -1) %}
22
+ {%- set loop_messages = messages %}
23
+ {%- for m in loop_messages %}
24
+ {%- if m["role"] == "user" %}
25
+ {%- set ns.last_user_idx = loop.index0 %}
26
+ {%- endif %}
27
+ {%- endfor %}
28
+ {%- if messages[0]["role"] == "system" %}
29
+ {%- set system_message = messages[0]["content"] %}
30
+ {%- set loop_messages = messages[1:] %}
31
+ {%- else %}
32
+ {%- set system_message = "" %}
33
+ {%- set loop_messages = messages %}
34
+ {%- endif %}
35
+ {%- if not tools is defined %}
36
+ {%- set tools = [] %}
37
+ {%- endif %}
38
+ {%- set ns = namespace(last_user_idx = -1) %}
39
+ {%- for m in loop_messages %}
40
+ {%- if m["role"] == "user" %}
41
+ {%- set ns.last_user_idx = loop.index0 %}
42
+ {%- endif %}
43
+ {%- endfor %}
44
+ {%- if system_message is defined %}
45
+ {{- "<|im_start|>system\n" + system_message }}
46
+ {%- else %}
47
+ {%- if tools is iterable and tools | length > 0 %}
48
+ {{- "<|im_start|>system\n" }}
49
+ {%- endif %}
50
+ {%- endif %}
51
+ {%- if tools is iterable and tools | length > 0 %}
52
+ {%- if system_message is defined and system_message | length > 0 %}
53
+ {{- "\n\n" }}
54
+ {%- endif %}
55
+ {{- "# Tools\n\nYou have access to the following functions:\n\n" }}
56
+ {{- "<tools>" }}
57
+ {%- for tool in tools %}
58
+ {%- if tool.function is defined %}
59
+ {%- set tool = tool.function %}
60
+ {%- endif %}
61
+ {{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
62
+ {%- if tool.description is defined %}
63
+ {{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
64
+ {%- endif %}
65
+ {{- '\n<parameters>' }}
66
+ {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
67
+ {%- for param_name, param_fields in tool.parameters.properties|items %}
68
+ {{- '\n<parameter>' }}
69
+ {{- '\n<name>' ~ param_name ~ '</name>' }}
70
+ {%- if param_fields.type is defined %}
71
+ {{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
72
+ {%- endif %}
73
+ {%- if param_fields.description is defined %}
74
+ {{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
75
+ {%- endif %}
76
+ {%- if param_fields.enum is defined %}
77
+ {{- '\n<enum>' ~ (param_fields.enum | tojson | safe) ~ '</enum>' }}
78
+ {%- endif %}
79
+ {%- set handled_keys = ['name', 'type', 'description', 'enum'] %}
80
+ {{- render_extra_keys(param_fields, handled_keys) }}
81
+ {{- '\n</parameter>' }}
82
+ {%- endfor %}
83
+ {%- endif %}
84
+ {% set handled_keys = ['type', 'properties', 'required'] %}
85
+ {{- render_extra_keys(tool.parameters, handled_keys) }}
86
+ {%- if tool.parameters is defined and tool.parameters.required is defined %}
87
+ {{- '\n<required>' ~ (tool.parameters.required | tojson | safe) ~ '</required>' }}
88
+ {%- endif %}
89
+ {{- '\n</parameters>' }}
90
+ {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
91
+ {{- render_extra_keys(tool, handled_keys) }}
92
+ {{- '\n</function>' }}
93
+ {%- endfor %}
94
+ {{- "\n</tools>" }}
95
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
96
+ {%- endif %}
97
+ {%- if system_message is defined %}
98
+ {{- '<|im_end|>\n' }}
99
+ {%- else %}
100
+ {%- if tools is iterable and tools | length > 0 %}
101
+ {{- '<|im_end|>\n' }}
102
+ {%- endif %}
103
+ {%- endif %}
104
+ {%- for message in loop_messages %}
105
+ {%- if message.role == "assistant" %}
106
+ {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %}
107
+ {%- set content = "<think>\n" ~ message.reasoning_content ~ "</think>" ~ (message.content | default('', true)) %}
108
+ {%- else %}
109
+ {%- set content = message.content | default('', true) %}
110
+ {%- if content is string -%}
111
+ {%- if '<think>' not in content and '</think>' not in content -%}
112
+ {%- set content = "<think></think>" ~ content -%}
113
+ {%- endif -%}
114
+ {%- else -%}
115
+ {%- set content = content -%}
116
+ {%- endif -%}
117
+ {%- endif %}
118
+ {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
119
+ {{- '<|im_start|>assistant\n' }}
120
+ {%- generation %}
121
+ {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
122
+ {%- if content is string and content | trim | length > 0 %}
123
+ {%- if include_content %}
124
+ {{- (content | trim) ~ '\n' -}}
125
+ {%- else %}
126
+ {%- set c = (content | string) %}
127
+ {%- if '</think>' in c %}
128
+ {%- set c = c.split('</think>')[-1] %}
129
+ {%- elif '<think>' in c %}
130
+ {%- set c = c.split('<think>')[0] %}
131
+ {%- endif %}
132
+ {%- set c = "<think></think>" ~ c %}
133
+ {%- if c | length > 0 %}
134
+ {{- c ~ '\n' -}}
135
+ {%- endif %}
136
+ {%- endif %}
137
+ {%- else %}
138
+ {{- "<think></think>" -}}
139
+ {%- endif %}
140
+ {%- for tool_call in message.tool_calls %}
141
+ {%- if tool_call.function is defined %}
142
+ {%- set tool_call = tool_call.function %}
143
+ {%- endif %}
144
+ {{- '<tool_call>\n<function=' ~ tool_call.name ~ '>\n' -}}
145
+ {%- if tool_call.arguments is defined %}
146
+ {%- for args_name, args_value in tool_call.arguments|items %}
147
+ {{- '<parameter=' ~ args_name ~ '>\n' -}}
148
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
149
+ {{- args_value ~ '\n</parameter>\n' -}}
150
+ {%- endfor %}
151
+ {%- endif %}
152
+ {{- '</function>\n</tool_call>\n' -}}
153
+ {%- endfor %}
154
+ {{- '<|im_end|>\n' }}
155
+ {%- endgeneration %}
156
+ {%- else %}
157
+ {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
158
+ {{- '<|im_start|>assistant\n' }}
159
+ {%- generation %}
160
+ {{- (content | default('', true) | string | trim) ~ '<|im_end|>\n' }}
161
+ {%- endgeneration %}
162
+ {%- else %}
163
+ {%- set c = (content | default('', true) | string) %}
164
+ {%- if '<think>' in c and '</think>' in c %}
165
+ {%- set c = "<think></think>" ~ c.split('</think>')[-1] %}
166
+ {%- endif %}
167
+ {%- set c = c | trim %}
168
+ {%- if c | length > 0 %}
169
+ {{- '<|im_start|>assistant\n' }}
170
+ {%- generation %}
171
+ {{- c ~ '<|im_end|>\n' }}
172
+ {%- endgeneration %}
173
+ {%- else %}
174
+ {{- '<|im_start|>assistant\n' }}
175
+ {%- generation %}
176
+ {{- '<|im_end|>\n' }}
177
+ {%- endgeneration %}
178
+ {%- endif %}
179
+ {%- endif %}
180
+ {%- endif %}
181
+ {%- elif message.role == "user" or message.role == "system" %}
182
+ {{- '<|im_start|>' + message.role + '\n' }}
183
+ {%- set content = message.content | string %}
184
+ {%- if message.role == "user" and loop.index0 == ns.last_user_idx and medium_effort %}
185
+ {{- content + '\n\n{reasoning effort: efficient}' }}
186
+ {%- else %}
187
+ {{- content }}
188
+ {%- endif %}
189
+ {{- '<|im_end|>\n' }}
190
+ {%- elif message.role == "tool" %}
191
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
192
+ {{- '<|im_start|>user\n' }}
193
+ {%- endif %}
194
+ {{- '<tool_response>\n' }}
195
+ {{- message.content }}
196
+ {{- '\n</tool_response>\n' }}
197
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
198
+ {{- '<|im_end|>\n' }}
199
+ {%- elif loop.last %}
200
+ {{- '<|im_end|>\n' }}
201
+ {%- endif %}
202
+ {%- else %}
203
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
204
+ {%- endif %}
205
+ {%- endfor %}
206
+ {%- if add_generation_prompt %}
207
+ {%- if enable_thinking %}
208
+ {{- '<|im_start|>assistant\n<think>\n' }}
209
+ {%- else %}
210
+ {{- '<|im_start|>assistant\n<think></think>' }}
211
+ {%- endif %}
212
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/phi3.jinja ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {% for message in messages %}{% if message['role'] == 'system' %}{{'<|system|>
2
+ ' + message['content'] + '<|end|>
3
+ '}}{% elif message['role'] == 'user' %}{{'<|user|>
4
+ ' + message['content'] + '<|end|>
5
+ '}}{% elif message['role'] == 'assistant' %}{{'<|assistant|>
6
+ ' + message['content'] + '<|end|>
7
+ '}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|>
8
+ ' }}{% else %}{{ eos_token }}{% endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/phi3_5.jinja ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {% for message in messages %}{% if message['role'] == 'system' and message['content'] %}{{'<|system|>
2
+ ' + message['content'] + '<|end|>
3
+ '}}{% elif message['role'] == 'user' %}{{'<|user|>
4
+ ' + message['content'] + '<|end|>
5
+ '}}{% elif message['role'] == 'assistant' %}{{'<|assistant|>
6
+ ' + message['content'] + '<|end|>
7
+ '}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|>
8
+ ' }}{% else %}{{ eos_token }}{% endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/phi3_5_training.jinja ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Phi-3.5 chat template (see phi3_5.jinja for the original).
2
+ Modifications vs the original:
3
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
4
+ assistant-only loss masking in SFT training.
5
+ -#}
6
+ {%- for message in messages %}
7
+ {%- if message['role'] == 'system' and message['content'] %}
8
+ {{- '<|system|>\n' + message['content'] + '<|end|>\n' }}
9
+ {%- elif message['role'] == 'user' %}
10
+ {{- '<|user|>\n' + message['content'] + '<|end|>\n'}}
11
+ {%- elif message['role'] == 'assistant' %}
12
+ {{- '<|assistant|>\n' }}
13
+ {%- generation %}
14
+ {{- message['content'] + '<|end|>\n' }}
15
+ {%- endgeneration %}
16
+ {%- endif %}
17
+ {%- endfor %}
18
+ {%- if add_generation_prompt %}
19
+ {{- '<|assistant|>\n'}}
20
+ {%- elif messages[-1]['role'] == 'assistant' %}
21
+ {%- generation %}
22
+ {{- eos_token }}
23
+ {%- endgeneration %}
24
+ {%- else %}
25
+ {{- eos_token }}
26
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/phi3_training.jinja ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Phi-3 chat template (see phi3.jinja for the original).
2
+ Modifications vs the original:
3
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
4
+ assistant-only loss masking in SFT training.
5
+ -#}
6
+ {%- for message in messages %}
7
+ {%- if message['role'] == 'system' %}
8
+ {{- '<|system|>\n' + message['content'] + '<|end|>\n' }}
9
+ {%- elif message['role'] == 'user' %}
10
+ {{- '<|user|>\n' + message['content'] + '<|end|>\n' }}
11
+ {%- elif message['role'] == 'assistant' %}
12
+ {{- '<|assistant|>\n' }}
13
+ {%- generation %}
14
+ {{- message['content'] + '<|end|>\n' }}
15
+ {%- endgeneration %}
16
+ {%- endif %}
17
+ {%- endfor %}
18
+ {%- if add_generation_prompt %}
19
+ {{- '<|assistant|>\n' }}
20
+ {%- elif messages[-1]['role'] == 'assistant' %}
21
+ {%- generation %}
22
+ {{- eos_token }}
23
+ {%- endgeneration %}
24
+ {%- else %}
25
+ {{- eos_token }}
26
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen2_5.jinja ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0]['role'] == 'system' %}
4
+ {{- messages[0]['content'] }}
5
+ {%- else %}
6
+ {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}
7
+ {%- endif %}
8
+ {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
9
+ {%- for tool in tools %}
10
+ {{- "\n" }}
11
+ {{- tool | tojson }}
12
+ {%- endfor %}
13
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
14
+ {%- else %}
15
+ {%- if messages[0]['role'] == 'system' %}
16
+ {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}
17
+ {%- else %}
18
+ {{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }}
19
+ {%- endif %}
20
+ {%- endif %}
21
+ {%- for message in messages %}
22
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %}
23
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
24
+ {%- elif message.role == "assistant" %}
25
+ {{- '<|im_start|>' + message.role }}
26
+ {%- if message.content %}
27
+ {{- '\n' + message.content }}
28
+ {%- endif %}
29
+ {%- for tool_call in message.tool_calls %}
30
+ {%- if tool_call.function is defined %}
31
+ {%- set tool_call = tool_call.function %}
32
+ {%- endif %}
33
+ {{- '\n<tool_call>\n{"name": "' }}
34
+ {{- tool_call.name }}
35
+ {{- '", "arguments": ' }}
36
+ {{- tool_call.arguments | tojson }}
37
+ {{- '}\n</tool_call>' }}
38
+ {%- endfor %}
39
+ {{- '<|im_end|>\n' }}
40
+ {%- elif message.role == "tool" %}
41
+ {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
42
+ {{- '<|im_start|>user' }}
43
+ {%- endif %}
44
+ {{- '\n<tool_response>\n' }}
45
+ {{- message.content }}
46
+ {{- '\n</tool_response>' }}
47
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
48
+ {{- '<|im_end|>\n' }}
49
+ {%- endif %}
50
+ {%- endif %}
51
+ {%- endfor %}
52
+ {%- if add_generation_prompt %}
53
+ {{- '<|im_start|>assistant\n' }}
54
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen2_5_training.jinja ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Qwen2.5 chat template (see qwen2_5.jinja for the original).
2
+ Modifications vs the original:
3
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
4
+ assistant-only loss masking in SFT training.
5
+ -#}
6
+ {%- if tools %}
7
+ {{- '<|im_start|>system\n' }}
8
+ {%- if messages[0]['role'] == 'system' %}
9
+ {{- messages[0]['content'] }}
10
+ {%- else %}
11
+ {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}
12
+ {%- endif %}
13
+ {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
14
+ {%- for tool in tools %}
15
+ {{- "\n" }}
16
+ {{- tool | tojson }}
17
+ {%- endfor %}
18
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
19
+ {%- else %}
20
+ {%- if messages[0]['role'] == 'system' %}
21
+ {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}
22
+ {%- else %}
23
+ {{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }}
24
+ {%- endif %}
25
+ {%- endif %}
26
+ {%- for message in messages %}
27
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
28
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
29
+ {%- elif message.role == "assistant" %}
30
+ {{- '<|im_start|>assistant' }}
31
+ {%- generation %}
32
+ {%- if not message.tool_calls %}
33
+ {{- '\n' + message.content + '<|im_end|>\n' }}
34
+ {%- else %}
35
+ {%- if message.content %}
36
+ {{- '\n' + message.content }}
37
+ {%- endif %}
38
+ {%- for tool_call in message.tool_calls %}
39
+ {%- if tool_call.function is defined %}
40
+ {%- set tool_call = tool_call.function %}
41
+ {%- endif %}
42
+ {{- '\n<tool_call>\n{"name": "' }}
43
+ {{- tool_call.name }}
44
+ {{- '", "arguments": ' }}
45
+ {{- tool_call.arguments | tojson }}
46
+ {{- '}\n</tool_call>' }}
47
+ {%- endfor %}
48
+ {{- '<|im_end|>\n' }}
49
+ {%- endif %}
50
+ {%- endgeneration %}
51
+ {%- elif message.role == "tool" %}
52
+ {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
53
+ {{- '<|im_start|>user' }}
54
+ {%- endif %}
55
+ {{- '\n<tool_response>\n' }}
56
+ {{- message.content }}
57
+ {{- '\n</tool_response>' }}
58
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
59
+ {{- '<|im_end|>\n' }}
60
+ {%- endif %}
61
+ {%- endif %}
62
+ {%- endfor %}
63
+ {%- if add_generation_prompt %}
64
+ {{- '<|im_start|>assistant\n' }}
65
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen2_5_vl.jinja ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system
2
+ You are a helpful assistant.<|im_end|>
3
+ {% endif %}<|im_start|>{{ message['role'] }}
4
+ {% if message['content'] is string %}{{ message['content'] }}<|im_end|>
5
+ {% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>
6
+ {% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant
7
+ {% endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen2_5_vl_training.jinja ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Qwen 2.5 VL chat template (see qwen2_5_vl.jinja for the original).
2
+ Also used for Qwen 2 VL, which ships a byte-identical chat template.
3
+ Modifications vs the original:
4
+ - Split the assistant message into its own branch so the {% generation %} / {% endgeneration %}
5
+ markers wrap the assistant content (everything after the '<|im_start|>assistant\n' prompt
6
+ cue, up to and including the trailing '<|im_end|>\n'). This enables assistant-only loss
7
+ masking in SFT training.
8
+ -#}
9
+ {%- set image_count = namespace(value=0) %}
10
+ {%- set video_count = namespace(value=0) %}
11
+ {%- for message in messages %}
12
+ {%- if loop.first and message['role'] != 'system' %}
13
+ {{- '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}
14
+ {%- endif %}
15
+ {%- if message['role'] == 'assistant' %}
16
+ {{- '<|im_start|>assistant\n' }}
17
+ {%- generation -%}
18
+ {%- if message['content'] is string %}
19
+ {{- message['content'] }}
20
+ {{- '<|im_end|>\n' }}
21
+ {%- else %}
22
+ {%- for content in message['content'] %}
23
+ {%- if content['type'] == 'image' or 'image' in content or 'image_url' in content %}
24
+ {%- set image_count.value = image_count.value + 1 %}
25
+ {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}
26
+ <|vision_start|><|image_pad|><|vision_end|>
27
+ {%- elif content['type'] == 'video' or 'video' in content %}
28
+ {%- set video_count.value = video_count.value + 1 %}
29
+ {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}
30
+ <|vision_start|><|video_pad|><|vision_end|>
31
+ {%- elif 'text' in content %}
32
+ {{- content['text'] }}
33
+ {%- endif %}
34
+ {%- endfor %}
35
+ {{- '<|im_end|>\n' }}
36
+ {%- endif %}
37
+ {%- endgeneration -%}
38
+ {%- else %}
39
+ {{- '<|im_start|>' + message['role'] + '\n' }}
40
+ {%- if message['content'] is string %}
41
+ {{- message['content'] }}
42
+ {{- '<|im_end|>\n' }}
43
+ {%- else %}
44
+ {%- for content in message['content'] %}
45
+ {%- if content['type'] == 'image' or 'image' in content or 'image_url' in content %}
46
+ {%- set image_count.value = image_count.value + 1 %}
47
+ {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}
48
+ <|vision_start|><|image_pad|><|vision_end|>
49
+ {%- elif content['type'] == 'video' or 'video' in content %}
50
+ {%- set video_count.value = video_count.value + 1 %}
51
+ {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}
52
+ <|vision_start|><|video_pad|><|vision_end|>
53
+ {%- elif 'text' in content %}
54
+ {{- content['text'] }}
55
+ {%- endif %}
56
+ {%- endfor %}
57
+ {{- '<|im_end|>\n' }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {%- endfor %}
61
+ {%- if add_generation_prompt %}
62
+ {{- '<|im_start|>assistant\n' }}
63
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3.jinja ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {%- set reasoning_content = '' %}
35
+ {%- if message.reasoning_content is string %}
36
+ {%- set reasoning_content = message.reasoning_content %}
37
+ {%- else %}
38
+ {%- if '</think>' in content %}
39
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
40
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
41
+ {%- endif %}
42
+ {%- endif %}
43
+ {%- if loop.index0 > ns.last_query_index %}
44
+ {%- if loop.last or (not loop.last and reasoning_content) %}
45
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
46
+ {%- else %}
47
+ {{- '<|im_start|>' + message.role + '\n' + content }}
48
+ {%- endif %}
49
+ {%- else %}
50
+ {{- '<|im_start|>' + message.role + '\n' + content }}
51
+ {%- endif %}
52
+ {%- if message.tool_calls %}
53
+ {%- for tool_call in message.tool_calls %}
54
+ {%- if (loop.first and content) or (not loop.first) %}
55
+ {{- '\n' }}
56
+ {%- endif %}
57
+ {%- if tool_call.function %}
58
+ {%- set tool_call = tool_call.function %}
59
+ {%- endif %}
60
+ {{- '<tool_call>\n{"name": "' }}
61
+ {{- tool_call.name }}
62
+ {{- '", "arguments": ' }}
63
+ {%- if tool_call.arguments is string %}
64
+ {{- tool_call.arguments }}
65
+ {%- else %}
66
+ {{- tool_call.arguments | tojson }}
67
+ {%- endif %}
68
+ {{- '}\n</tool_call>' }}
69
+ {%- endfor %}
70
+ {%- endif %}
71
+ {{- '<|im_end|>\n' }}
72
+ {%- elif message.role == "tool" %}
73
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
74
+ {{- '<|im_start|>user' }}
75
+ {%- endif %}
76
+ {{- '\n<tool_response>\n' }}
77
+ {{- content }}
78
+ {{- '\n</tool_response>' }}
79
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
80
+ {{- '<|im_end|>\n' }}
81
+ {%- endif %}
82
+ {%- endif %}
83
+ {%- endfor %}
84
+ {%- if add_generation_prompt %}
85
+ {{- '<|im_start|>assistant\n' }}
86
+ {%- if enable_thinking is defined and enable_thinking is false %}
87
+ {{- '<think>\n\n</think>\n\n' }}
88
+ {%- endif %}
89
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_5_nothink.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if loop.index0 > ns.last_query_index %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is true %}
150
+ {{- '<think>\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n\n</think>\n\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_5_nothink_training.jinja ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Qwen3.5 chat template, NoThink flavor (see qwen3_5_nothink.jinja for the original).
2
+ Modifications vs the original:
3
+ - {%- if '</think>' in content %} → {%- if '<think>' in content and '</think>' in content %}
4
+ Always check for both tags to avoid edge cases where the model generates only one tag.
5
+ - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block.
6
+ This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition.
7
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
8
+ assistant-only loss masking in SFT training.
9
+ -#}
10
+ {%- set image_count = namespace(value=0) %}
11
+ {%- set video_count = namespace(value=0) %}
12
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
13
+ {%- if content is string %}
14
+ {{- content }}
15
+ {%- elif content is iterable and content is not mapping %}
16
+ {%- for item in content %}
17
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
18
+ {%- if is_system_content %}
19
+ {{- raise_exception('System message cannot contain images.') }}
20
+ {%- endif %}
21
+ {%- if do_vision_count %}
22
+ {%- set image_count.value = image_count.value + 1 %}
23
+ {%- endif %}
24
+ {%- if add_vision_id %}
25
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
26
+ {%- endif %}
27
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
28
+ {%- elif 'video' in item or item.type == 'video' %}
29
+ {%- if is_system_content %}
30
+ {{- raise_exception('System message cannot contain videos.') }}
31
+ {%- endif %}
32
+ {%- if do_vision_count %}
33
+ {%- set video_count.value = video_count.value + 1 %}
34
+ {%- endif %}
35
+ {%- if add_vision_id %}
36
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
37
+ {%- endif %}
38
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
39
+ {%- elif 'text' in item %}
40
+ {{- item.text }}
41
+ {%- else %}
42
+ {{- raise_exception('Unexpected item type in content.') }}
43
+ {%- endif %}
44
+ {%- endfor %}
45
+ {%- elif content is none or content is undefined %}
46
+ {{- '' }}
47
+ {%- else %}
48
+ {{- raise_exception('Unexpected content type.') }}
49
+ {%- endif %}
50
+ {%- endmacro %}
51
+ {%- if not messages %}
52
+ {{- raise_exception('No messages provided.') }}
53
+ {%- endif %}
54
+ {%- if tools and tools is iterable and tools is not mapping %}
55
+ {{- '<|im_start|>system\n' }}
56
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
57
+ {%- for tool in tools %}
58
+ {{- "\n" }}
59
+ {{- tool | tojson }}
60
+ {%- endfor %}
61
+ {{- "\n</tools>" }}
62
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
63
+ {%- if messages[0].role == 'system' %}
64
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
65
+ {%- if content %}
66
+ {{- '\n\n' + content }}
67
+ {%- endif %}
68
+ {%- endif %}
69
+ {{- '<|im_end|>\n' }}
70
+ {%- else %}
71
+ {%- if messages[0].role == 'system' %}
72
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
73
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
74
+ {%- endif %}
75
+ {%- endif %}
76
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
77
+ {%- for message in messages[::-1] %}
78
+ {%- set index = (messages|length - 1) - loop.index0 %}
79
+ {%- if ns.multi_step_tool and message.role == "user" %}
80
+ {%- set content = render_content(message.content, false)|trim %}
81
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
82
+ {%- set ns.multi_step_tool = false %}
83
+ {%- set ns.last_query_index = index %}
84
+ {%- endif %}
85
+ {%- endif %}
86
+ {%- endfor %}
87
+ {%- if ns.multi_step_tool %}
88
+ {{- raise_exception('No user query found in messages.') }}
89
+ {%- endif %}
90
+ {%- for message in messages %}
91
+ {%- set content = render_content(message.content, true)|trim %}
92
+ {%- if message.role == "system" %}
93
+ {%- if not loop.first %}
94
+ {{- raise_exception('System message must be at the beginning.') }}
95
+ {%- endif %}
96
+ {%- elif message.role == "user" %}
97
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
98
+ {%- elif message.role == "assistant" %}
99
+ {%- set reasoning_content = '' %}
100
+ {%- if message.reasoning_content is string %}
101
+ {%- set reasoning_content = message.reasoning_content %}
102
+ {%- else %}
103
+ {%- if '<think>' in content and '</think>' in content %}
104
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
105
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
106
+ {%- endif %}
107
+ {%- endif %}
108
+ {%- set reasoning_content = reasoning_content|trim %}
109
+ {{- '<|im_start|>' + message.role + '\n' }}
110
+ {%- generation %}
111
+ {{- '<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
112
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
113
+ {%- for tool_call in message.tool_calls %}
114
+ {%- if tool_call.function is defined %}
115
+ {%- set tool_call = tool_call.function %}
116
+ {%- endif %}
117
+ {%- if loop.first %}
118
+ {%- if content|trim %}
119
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
120
+ {%- else %}
121
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
122
+ {%- endif %}
123
+ {%- else %}
124
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
125
+ {%- endif %}
126
+ {%- if tool_call.arguments is defined %}
127
+ {%- for args_name, args_value in tool_call.arguments|items %}
128
+ {{- '<parameter=' + args_name + '>\n' }}
129
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
130
+ {{- args_value }}
131
+ {{- '\n</parameter>\n' }}
132
+ {%- endfor %}
133
+ {%- endif %}
134
+ {{- '</function>\n</tool_call>' }}
135
+ {%- endfor %}
136
+ {%- endif %}
137
+ {{- '<|im_end|>\n' }}
138
+ {%- endgeneration %}
139
+ {%- elif message.role == "tool" %}
140
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
141
+ {{- '<|im_start|>user' }}
142
+ {%- endif %}
143
+ {{- '\n<tool_response>\n' }}
144
+ {{- content }}
145
+ {{- '\n</tool_response>' }}
146
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
147
+ {{- '<|im_end|>\n' }}
148
+ {%- elif loop.last %}
149
+ {{- '<|im_end|>\n' }}
150
+ {%- endif %}
151
+ {%- else %}
152
+ {{- raise_exception('Unexpected message role.') }}
153
+ {%- endif %}
154
+ {%- endfor %}
155
+ {%- if add_generation_prompt %}
156
+ {{- '<|im_start|>assistant\n' }}
157
+ {%- if enable_thinking is defined and enable_thinking is true %}
158
+ {{- '<think>\n' }}
159
+ {%- else %}
160
+ {{- '<think>\n\n</think>\n\n' }}
161
+ {%- endif %}
162
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_5_think.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if loop.index0 > ns.last_query_index %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is false %}
150
+ {{- '<think>\n\n</think>\n\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_5_think_training.jinja ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Qwen3.5 chat template, Think flavor (see qwen3_5_think.jinja for the original).
2
+ Modifications vs the original:
3
+ - {%- if '</think>' in content %} → {%- if '<think>' in content and '</think>' in content %}
4
+ Always check for both tags to avoid edge cases where the model generates only one tag.
5
+ - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block.
6
+ This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition.
7
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
8
+ assistant-only loss masking in SFT training.
9
+ -#}
10
+ {%- set image_count = namespace(value=0) %}
11
+ {%- set video_count = namespace(value=0) %}
12
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
13
+ {%- if content is string %}
14
+ {{- content }}
15
+ {%- elif content is iterable and content is not mapping %}
16
+ {%- for item in content %}
17
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
18
+ {%- if is_system_content %}
19
+ {{- raise_exception('System message cannot contain images.') }}
20
+ {%- endif %}
21
+ {%- if do_vision_count %}
22
+ {%- set image_count.value = image_count.value + 1 %}
23
+ {%- endif %}
24
+ {%- if add_vision_id %}
25
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
26
+ {%- endif %}
27
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
28
+ {%- elif 'video' in item or item.type == 'video' %}
29
+ {%- if is_system_content %}
30
+ {{- raise_exception('System message cannot contain videos.') }}
31
+ {%- endif %}
32
+ {%- if do_vision_count %}
33
+ {%- set video_count.value = video_count.value + 1 %}
34
+ {%- endif %}
35
+ {%- if add_vision_id %}
36
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
37
+ {%- endif %}
38
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
39
+ {%- elif 'text' in item %}
40
+ {{- item.text }}
41
+ {%- else %}
42
+ {{- raise_exception('Unexpected item type in content.') }}
43
+ {%- endif %}
44
+ {%- endfor %}
45
+ {%- elif content is none or content is undefined %}
46
+ {{- '' }}
47
+ {%- else %}
48
+ {{- raise_exception('Unexpected content type.') }}
49
+ {%- endif %}
50
+ {%- endmacro %}
51
+ {%- if not messages %}
52
+ {{- raise_exception('No messages provided.') }}
53
+ {%- endif %}
54
+ {%- if tools and tools is iterable and tools is not mapping %}
55
+ {{- '<|im_start|>system\n' }}
56
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
57
+ {%- for tool in tools %}
58
+ {{- "\n" }}
59
+ {{- tool | tojson }}
60
+ {%- endfor %}
61
+ {{- "\n</tools>" }}
62
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
63
+ {%- if messages[0].role == 'system' %}
64
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
65
+ {%- if content %}
66
+ {{- '\n\n' + content }}
67
+ {%- endif %}
68
+ {%- endif %}
69
+ {{- '<|im_end|>\n' }}
70
+ {%- else %}
71
+ {%- if messages[0].role == 'system' %}
72
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
73
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
74
+ {%- endif %}
75
+ {%- endif %}
76
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
77
+ {%- for message in messages[::-1] %}
78
+ {%- set index = (messages|length - 1) - loop.index0 %}
79
+ {%- if ns.multi_step_tool and message.role == "user" %}
80
+ {%- set content = render_content(message.content, false)|trim %}
81
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
82
+ {%- set ns.multi_step_tool = false %}
83
+ {%- set ns.last_query_index = index %}
84
+ {%- endif %}
85
+ {%- endif %}
86
+ {%- endfor %}
87
+ {%- if ns.multi_step_tool %}
88
+ {{- raise_exception('No user query found in messages.') }}
89
+ {%- endif %}
90
+ {%- for message in messages %}
91
+ {%- set content = render_content(message.content, true)|trim %}
92
+ {%- if message.role == "system" %}
93
+ {%- if not loop.first %}
94
+ {{- raise_exception('System message must be at the beginning.') }}
95
+ {%- endif %}
96
+ {%- elif message.role == "user" %}
97
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
98
+ {%- elif message.role == "assistant" %}
99
+ {%- set reasoning_content = '' %}
100
+ {%- if message.reasoning_content is string %}
101
+ {%- set reasoning_content = message.reasoning_content %}
102
+ {%- else %}
103
+ {%- if '<think>' in content and '</think>' in content %}
104
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
105
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
106
+ {%- endif %}
107
+ {%- endif %}
108
+ {%- set reasoning_content = reasoning_content|trim %}
109
+ {{- '<|im_start|>' + message.role + '\n' }}
110
+ {%- generation %}
111
+ {{- '<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
112
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
113
+ {%- for tool_call in message.tool_calls %}
114
+ {%- if tool_call.function is defined %}
115
+ {%- set tool_call = tool_call.function %}
116
+ {%- endif %}
117
+ {%- if loop.first %}
118
+ {%- if content|trim %}
119
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
120
+ {%- else %}
121
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
122
+ {%- endif %}
123
+ {%- else %}
124
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
125
+ {%- endif %}
126
+ {%- if tool_call.arguments is defined %}
127
+ {%- for args_name, args_value in tool_call.arguments|items %}
128
+ {{- '<parameter=' + args_name + '>\n' }}
129
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
130
+ {{- args_value }}
131
+ {{- '\n</parameter>\n' }}
132
+ {%- endfor %}
133
+ {%- endif %}
134
+ {{- '</function>\n</tool_call>' }}
135
+ {%- endfor %}
136
+ {%- endif %}
137
+ {{- '<|im_end|>\n' }}
138
+ {%- endgeneration %}
139
+ {%- elif message.role == "tool" %}
140
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
141
+ {{- '<|im_start|>user' }}
142
+ {%- endif %}
143
+ {{- '\n<tool_response>\n' }}
144
+ {{- content }}
145
+ {{- '\n</tool_response>' }}
146
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
147
+ {{- '<|im_end|>\n' }}
148
+ {%- elif loop.last %}
149
+ {{- '<|im_end|>\n' }}
150
+ {%- endif %}
151
+ {%- else %}
152
+ {{- raise_exception('Unexpected message role.') }}
153
+ {%- endif %}
154
+ {%- endfor %}
155
+ {%- if add_generation_prompt %}
156
+ {{- '<|im_start|>assistant\n' }}
157
+ {%- if enable_thinking is defined and enable_thinking is false %}
158
+ {{- '<think>\n\n</think>\n\n' }}
159
+ {%- else %}
160
+ {{- '<think>\n' }}
161
+ {%- endif %}
162
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_6.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if (preserve_thinking is defined and preserve_thinking is true) or (loop.index0 > ns.last_query_index) %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is false %}
150
+ {{- '<think>\n\n</think>\n\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_6_training.jinja ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Qwen3.6 chat template (see qwen3_6.jinja for the original).
2
+ Modifications vs the original:
3
+ - {%- if '</think>' in content %} → {%- if '<think>' in content and '</think>' in content %}
4
+ Always check for both tags to avoid edge cases where the model generates only one tag.
5
+ - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block.
6
+ This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition.
7
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
8
+ assistant-only loss masking in SFT training.
9
+ -#}
10
+ {%- set image_count = namespace(value=0) %}
11
+ {%- set video_count = namespace(value=0) %}
12
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
13
+ {%- if content is string %}
14
+ {{- content }}
15
+ {%- elif content is iterable and content is not mapping %}
16
+ {%- for item in content %}
17
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
18
+ {%- if is_system_content %}
19
+ {{- raise_exception('System message cannot contain images.') }}
20
+ {%- endif %}
21
+ {%- if do_vision_count %}
22
+ {%- set image_count.value = image_count.value + 1 %}
23
+ {%- endif %}
24
+ {%- if add_vision_id %}
25
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
26
+ {%- endif %}
27
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
28
+ {%- elif 'video' in item or item.type == 'video' %}
29
+ {%- if is_system_content %}
30
+ {{- raise_exception('System message cannot contain videos.') }}
31
+ {%- endif %}
32
+ {%- if do_vision_count %}
33
+ {%- set video_count.value = video_count.value + 1 %}
34
+ {%- endif %}
35
+ {%- if add_vision_id %}
36
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
37
+ {%- endif %}
38
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
39
+ {%- elif 'text' in item %}
40
+ {{- item.text }}
41
+ {%- else %}
42
+ {{- raise_exception('Unexpected item type in content.') }}
43
+ {%- endif %}
44
+ {%- endfor %}
45
+ {%- elif content is none or content is undefined %}
46
+ {{- '' }}
47
+ {%- else %}
48
+ {{- raise_exception('Unexpected content type.') }}
49
+ {%- endif %}
50
+ {%- endmacro %}
51
+ {%- if not messages %}
52
+ {{- raise_exception('No messages provided.') }}
53
+ {%- endif %}
54
+ {%- if tools and tools is iterable and tools is not mapping %}
55
+ {{- '<|im_start|>system\n' }}
56
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
57
+ {%- for tool in tools %}
58
+ {{- "\n" }}
59
+ {{- tool | tojson }}
60
+ {%- endfor %}
61
+ {{- "\n</tools>" }}
62
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
63
+ {%- if messages[0].role == 'system' %}
64
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
65
+ {%- if content %}
66
+ {{- '\n\n' + content }}
67
+ {%- endif %}
68
+ {%- endif %}
69
+ {{- '<|im_end|>\n' }}
70
+ {%- else %}
71
+ {%- if messages[0].role == 'system' %}
72
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
73
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
74
+ {%- endif %}
75
+ {%- endif %}
76
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
77
+ {%- for message in messages[::-1] %}
78
+ {%- set index = (messages|length - 1) - loop.index0 %}
79
+ {%- if ns.multi_step_tool and message.role == "user" %}
80
+ {%- set content = render_content(message.content, false)|trim %}
81
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
82
+ {%- set ns.multi_step_tool = false %}
83
+ {%- set ns.last_query_index = index %}
84
+ {%- endif %}
85
+ {%- endif %}
86
+ {%- endfor %}
87
+ {%- if ns.multi_step_tool %}
88
+ {{- raise_exception('No user query found in messages.') }}
89
+ {%- endif %}
90
+ {%- for message in messages %}
91
+ {%- set content = render_content(message.content, true)|trim %}
92
+ {%- if message.role == "system" %}
93
+ {%- if not loop.first %}
94
+ {{- raise_exception('System message must be at the beginning.') }}
95
+ {%- endif %}
96
+ {%- elif message.role == "user" %}
97
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
98
+ {%- elif message.role == "assistant" %}
99
+ {%- set reasoning_content = '' %}
100
+ {%- if message.reasoning_content is string %}
101
+ {%- set reasoning_content = message.reasoning_content %}
102
+ {%- else %}
103
+ {%- if '<think>' in content and '</think>' in content %}
104
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
105
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
106
+ {%- endif %}
107
+ {%- endif %}
108
+ {%- set reasoning_content = reasoning_content|trim %}
109
+ {{- '<|im_start|>' + message.role + '\n' }}
110
+ {%- generation %}
111
+ {{- '<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
112
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
113
+ {%- for tool_call in message.tool_calls %}
114
+ {%- if tool_call.function is defined %}
115
+ {%- set tool_call = tool_call.function %}
116
+ {%- endif %}
117
+ {%- if loop.first %}
118
+ {%- if content|trim %}
119
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
120
+ {%- else %}
121
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
122
+ {%- endif %}
123
+ {%- else %}
124
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
125
+ {%- endif %}
126
+ {%- if tool_call.arguments is defined %}
127
+ {%- for args_name, args_value in tool_call.arguments|items %}
128
+ {{- '<parameter=' + args_name + '>\n' }}
129
+ {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
130
+ {{- args_value }}
131
+ {{- '\n</parameter>\n' }}
132
+ {%- endfor %}
133
+ {%- endif %}
134
+ {{- '</function>\n</tool_call>' }}
135
+ {%- endfor %}
136
+ {%- endif %}
137
+ {{- '<|im_end|>\n' }}
138
+ {%- endgeneration %}
139
+ {%- elif message.role == "tool" %}
140
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
141
+ {{- '<|im_start|>user' }}
142
+ {%- endif %}
143
+ {{- '\n<tool_response>\n' }}
144
+ {{- content }}
145
+ {{- '\n</tool_response>' }}
146
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
147
+ {{- '<|im_end|>\n' }}
148
+ {%- elif loop.last %}
149
+ {{- '<|im_end|>\n' }}
150
+ {%- endif %}
151
+ {%- else %}
152
+ {{- raise_exception('Unexpected message role.') }}
153
+ {%- endif %}
154
+ {%- endfor %}
155
+ {%- if add_generation_prompt %}
156
+ {{- '<|im_start|>assistant\n' }}
157
+ {%- if enable_thinking is defined and enable_thinking is false %}
158
+ {{- '<think>\n\n</think>\n\n' }}
159
+ {%- else %}
160
+ {{- '<think>\n' }}
161
+ {%- endif %}
162
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_instruct_2507.jinja ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- for message in messages %}
18
+ {%- if message.content is string %}
19
+ {%- set content = message.content %}
20
+ {%- else %}
21
+ {%- set content = '' %}
22
+ {%- endif %}
23
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
24
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
25
+ {%- elif message.role == "assistant" %}
26
+ {{- '<|im_start|>' + message.role + '\n' + content }}
27
+ {%- if message.tool_calls %}
28
+ {%- for tool_call in message.tool_calls %}
29
+ {%- if (loop.first and content) or (not loop.first) %}
30
+ {{- '\n' }}
31
+ {%- endif %}
32
+ {%- if tool_call.function %}
33
+ {%- set tool_call = tool_call.function %}
34
+ {%- endif %}
35
+ {{- '<tool_call>\n{"name": "' }}
36
+ {{- tool_call.name }}
37
+ {{- '", "arguments": ' }}
38
+ {%- if tool_call.arguments is string %}
39
+ {{- tool_call.arguments }}
40
+ {%- else %}
41
+ {{- tool_call.arguments | tojson }}
42
+ {%- endif %}
43
+ {{- '}\n</tool_call>' }}
44
+ {%- endfor %}
45
+ {%- endif %}
46
+ {{- '<|im_end|>\n' }}
47
+ {%- elif message.role == "tool" %}
48
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
49
+ {{- '<|im_start|>user' }}
50
+ {%- endif %}
51
+ {{- '\n<tool_response>\n' }}
52
+ {{- content }}
53
+ {{- '\n</tool_response>' }}
54
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
55
+ {{- '<|im_end|>\n' }}
56
+ {%- endif %}
57
+ {%- endif %}
58
+ {%- endfor %}
59
+ {%- if add_generation_prompt %}
60
+ {{- '<|im_start|>assistant\n' }}
61
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_instruct_2507_training.jinja ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Qwen3-Instruct-2507 chat template (see qwen3_instruct_2507.jinja for the original).
2
+ This is for models like Qwen3-4B-Instruct-2507 that ship without the reasoning_content /
3
+ multi_step_tool / enable_thinking logic present in later Qwen3 revisions.
4
+ Modifications vs the original:
5
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
6
+ assistant-only loss masking in SFT training.
7
+ -#}
8
+ {%- if tools %}
9
+ {{- '<|im_start|>system\n' }}
10
+ {%- if messages[0].role == 'system' %}
11
+ {{- messages[0].content + '\n\n' }}
12
+ {%- endif %}
13
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
14
+ {%- for tool in tools %}
15
+ {{- "\n" }}
16
+ {{- tool | tojson }}
17
+ {%- endfor %}
18
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
19
+ {%- else %}
20
+ {%- if messages[0].role == 'system' %}
21
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
22
+ {%- endif %}
23
+ {%- endif %}
24
+ {%- for message in messages %}
25
+ {%- if message.content is string %}
26
+ {%- set content = message.content %}
27
+ {%- else %}
28
+ {%- set content = '' %}
29
+ {%- endif %}
30
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
31
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
32
+ {%- elif message.role == "assistant" %}
33
+ {{- '<|im_start|>' + message.role + '\n' }}
34
+ {%- generation %}
35
+ {{- content }}
36
+ {%- if message.tool_calls %}
37
+ {%- for tool_call in message.tool_calls %}
38
+ {%- if (loop.first and content) or (not loop.first) %}
39
+ {{- '\n' }}
40
+ {%- endif %}
41
+ {%- if tool_call.function %}
42
+ {%- set tool_call = tool_call.function %}
43
+ {%- endif %}
44
+ {{- '<tool_call>\n{"name": "' }}
45
+ {{- tool_call.name }}
46
+ {{- '", "arguments": ' }}
47
+ {%- if tool_call.arguments is string %}
48
+ {{- tool_call.arguments }}
49
+ {%- else %}
50
+ {{- tool_call.arguments | tojson }}
51
+ {%- endif %}
52
+ {{- '}\n</tool_call>' }}
53
+ {%- endfor %}
54
+ {%- endif %}
55
+ {{- '<|im_end|>\n' }}
56
+ {%- endgeneration %}
57
+ {%- elif message.role == "tool" %}
58
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
59
+ {{- '<|im_start|>user' }}
60
+ {%- endif %}
61
+ {{- '\n<tool_response>\n' }}
62
+ {{- content }}
63
+ {{- '\n</tool_response>' }}
64
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
65
+ {{- '<|im_end|>\n' }}
66
+ {%- endif %}
67
+ {%- endif %}
68
+ {%- endfor %}
69
+ {%- if add_generation_prompt %}
70
+ {{- '<|im_start|>assistant\n' }}
71
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_training.jinja ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Qwen3 chat template (see qwen3.jinja for the original).
2
+ Modifications vs the original:
3
+ - {%- if '</think>' in content %} → {%- if '<think>' in content and '</think>' in content %}
4
+ Always check for both tags to avoid edge cases where the model generates only one tag.
5
+ - Removed the loop.index0 > ns.last_query_index conditional; always include thinking block.
6
+ This makes the template prefix-preserving for the [user, assistant] → [user, assistant, tool] transition.
7
+ - Added {% generation %} / {% endgeneration %} around assistant message output to support
8
+ assistant-only loss masking in SFT training.
9
+ -#}
10
+ {%- if tools %}
11
+ {{- '<|im_start|>system\n' }}
12
+ {%- if messages[0].role == 'system' %}
13
+ {{- messages[0].content + '\n\n' }}
14
+ {%- endif %}
15
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
16
+ {%- for tool in tools %}
17
+ {{- "\n" }}
18
+ {{- tool | tojson }}
19
+ {%- endfor %}
20
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
21
+ {%- else %}
22
+ {%- if messages[0].role == 'system' %}
23
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
24
+ {%- endif %}
25
+ {%- endif %}
26
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
27
+ {%- for message in messages[::-1] %}
28
+ {%- set index = (messages|length - 1) - loop.index0 %}
29
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
30
+ {%- set ns.multi_step_tool = false %}
31
+ {%- set ns.last_query_index = index %}
32
+ {%- endif %}
33
+ {%- endfor %}
34
+ {%- for message in messages %}
35
+ {%- if message.content is string %}
36
+ {%- set content = message.content %}
37
+ {%- else %}
38
+ {%- set content = '' %}
39
+ {%- endif %}
40
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
41
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
42
+ {%- elif message.role == "assistant" %}
43
+ {%- set reasoning_content = '' %}
44
+ {%- if message.reasoning_content is string %}
45
+ {%- set reasoning_content = message.reasoning_content %}
46
+ {%- else %}
47
+ {%- if '<think>' in content and '</think>' in content %}
48
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
49
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
50
+ {%- endif %}
51
+ {%- endif %}
52
+ {{- '<|im_start|>' + message.role + '\n' }}
53
+ {%- generation %}
54
+ {{- '<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
55
+ {%- if message.tool_calls %}
56
+ {%- for tool_call in message.tool_calls %}
57
+ {%- if (loop.first and content) or (not loop.first) %}
58
+ {{- '\n' }}
59
+ {%- endif %}
60
+ {%- if tool_call.function %}
61
+ {%- set tool_call = tool_call.function %}
62
+ {%- endif %}
63
+ {{- '<tool_call>\n{"name": "' }}
64
+ {{- tool_call.name }}
65
+ {{- '", "arguments": ' }}
66
+ {%- if tool_call.arguments is string %}
67
+ {{- tool_call.arguments }}
68
+ {%- else %}
69
+ {{- tool_call.arguments | tojson }}
70
+ {%- endif %}
71
+ {{- '}\n</tool_call>' }}
72
+ {%- endfor %}
73
+ {%- endif %}
74
+ {{- '<|im_end|>\n' }}
75
+ {%- endgeneration %}
76
+ {%- elif message.role == "tool" %}
77
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
78
+ {{- '<|im_start|>user' }}
79
+ {%- endif %}
80
+ {{- '\n<tool_response>\n' }}
81
+ {{- content }}
82
+ {{- '\n</tool_response>' }}
83
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
84
+ {{- '<|im_end|>\n' }}
85
+ {%- endif %}
86
+ {%- endif %}
87
+ {%- endfor %}
88
+ {%- if add_generation_prompt %}
89
+ {{- '<|im_start|>assistant\n' }}
90
+ {%- if enable_thinking is defined and enable_thinking is false %}
91
+ {{- '<think>\n\n</think>\n\n' }}
92
+ {%- endif %}
93
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_vl.jinja ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {%- if messages[0].content is string %}
5
+ {{- messages[0].content }}
6
+ {%- else %}
7
+ {%- for content in messages[0].content %}
8
+ {%- if 'text' in content %}
9
+ {{- content.text }}
10
+ {%- endif %}
11
+ {%- endfor %}
12
+ {%- endif %}
13
+ {{- '\n\n' }}
14
+ {%- endif %}
15
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
16
+ {%- for tool in tools %}
17
+ {{- "\n" }}
18
+ {{- tool | tojson }}
19
+ {%- endfor %}
20
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
21
+ {%- else %}
22
+ {%- if messages[0].role == 'system' %}
23
+ {{- '<|im_start|>system\n' }}
24
+ {%- if messages[0].content is string %}
25
+ {{- messages[0].content }}
26
+ {%- else %}
27
+ {%- for content in messages[0].content %}
28
+ {%- if 'text' in content %}
29
+ {{- content.text }}
30
+ {%- endif %}
31
+ {%- endfor %}
32
+ {%- endif %}
33
+ {{- '<|im_end|>\n' }}
34
+ {%- endif %}
35
+ {%- endif %}
36
+ {%- set image_count = namespace(value=0) %}
37
+ {%- set video_count = namespace(value=0) %}
38
+ {%- for message in messages %}
39
+ {%- if message.role == "user" %}
40
+ {{- '<|im_start|>' + message.role + '\n' }}
41
+ {%- if message.content is string %}
42
+ {{- message.content }}
43
+ {%- else %}
44
+ {%- for content in message.content %}
45
+ {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}
46
+ {%- set image_count.value = image_count.value + 1 %}
47
+ {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}
48
+ <|vision_start|><|image_pad|><|vision_end|>
49
+ {%- elif content.type == 'video' or 'video' in content %}
50
+ {%- set video_count.value = video_count.value + 1 %}
51
+ {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}
52
+ <|vision_start|><|video_pad|><|vision_end|>
53
+ {%- elif 'text' in content %}
54
+ {{- content.text }}
55
+ {%- endif %}
56
+ {%- endfor %}
57
+ {%- endif %}
58
+ {{- '<|im_end|>\n' }}
59
+ {%- elif message.role == "assistant" %}
60
+ {{- '<|im_start|>' + message.role + '\n' }}
61
+ {%- if message.content is string %}
62
+ {{- message.content }}
63
+ {%- else %}
64
+ {%- for content_item in message.content %}
65
+ {%- if 'text' in content_item %}
66
+ {{- content_item.text }}
67
+ {%- endif %}
68
+ {%- endfor %}
69
+ {%- endif %}
70
+ {%- if message.tool_calls %}
71
+ {%- for tool_call in message.tool_calls %}
72
+ {%- if (loop.first and message.content) or (not loop.first) %}
73
+ {{- '\n' }}
74
+ {%- endif %}
75
+ {%- if tool_call.function %}
76
+ {%- set tool_call = tool_call.function %}
77
+ {%- endif %}
78
+ {{- '<tool_call>\n{"name": "' }}
79
+ {{- tool_call.name }}
80
+ {{- '", "arguments": ' }}
81
+ {%- if tool_call.arguments is string %}
82
+ {{- tool_call.arguments }}
83
+ {%- else %}
84
+ {{- tool_call.arguments | tojson }}
85
+ {%- endif %}
86
+ {{- '}\n</tool_call>' }}
87
+ {%- endfor %}
88
+ {%- endif %}
89
+ {{- '<|im_end|>\n' }}
90
+ {%- elif message.role == "tool" %}
91
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
92
+ {{- '<|im_start|>user' }}
93
+ {%- endif %}
94
+ {{- '\n<tool_response>\n' }}
95
+ {%- if message.content is string %}
96
+ {{- message.content }}
97
+ {%- else %}
98
+ {%- for content in message.content %}
99
+ {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}
100
+ {%- set image_count.value = image_count.value + 1 %}
101
+ {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}
102
+ <|vision_start|><|image_pad|><|vision_end|>
103
+ {%- elif content.type == 'video' or 'video' in content %}
104
+ {%- set video_count.value = video_count.value + 1 %}
105
+ {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}
106
+ <|vision_start|><|video_pad|><|vision_end|>
107
+ {%- elif 'text' in content %}
108
+ {{- content.text }}
109
+ {%- endif %}
110
+ {%- endfor %}
111
+ {%- endif %}
112
+ {{- '\n</tool_response>' }}
113
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
114
+ {{- '<|im_end|>\n' }}
115
+ {%- endif %}
116
+ {%- endif %}
117
+ {%- endfor %}
118
+ {%- if add_generation_prompt %}
119
+ {{- '<|im_start|>assistant\n' }}
120
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/chat_templates/qwen3_vl_training.jinja ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Training variant of the Qwen 3 VL chat template (see qwen3_vl.jinja for the original).
2
+ Modifications vs the original:
3
+ - Added {% generation %} / {% endgeneration %} around assistant message content to
4
+ support assistant-only loss masking in SFT training.
5
+ -#}
6
+ {%- if tools %}
7
+ {{- '<|im_start|>system\n' }}
8
+ {%- if messages[0].role == 'system' %}
9
+ {%- if messages[0].content is string %}
10
+ {{- messages[0].content }}
11
+ {%- else %}
12
+ {%- for content in messages[0].content %}
13
+ {%- if 'text' in content %}
14
+ {{- content.text }}
15
+ {%- endif %}
16
+ {%- endfor %}
17
+ {%- endif %}
18
+ {{- '\n\n' }}
19
+ {%- endif %}
20
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
21
+ {%- for tool in tools %}
22
+ {{- "\n" }}
23
+ {{- tool | tojson }}
24
+ {%- endfor %}
25
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
26
+ {%- else %}
27
+ {%- if messages[0].role == 'system' %}
28
+ {{- '<|im_start|>system\n' }}
29
+ {%- if messages[0].content is string %}
30
+ {{- messages[0].content }}
31
+ {%- else %}
32
+ {%- for content in messages[0].content %}
33
+ {%- if 'text' in content %}
34
+ {{- content.text }}
35
+ {%- endif %}
36
+ {%- endfor %}
37
+ {%- endif %}
38
+ {{- '<|im_end|>\n' }}
39
+ {%- endif %}
40
+ {%- endif %}
41
+ {%- set image_count = namespace(value=0) %}
42
+ {%- set video_count = namespace(value=0) %}
43
+ {%- for message in messages %}
44
+ {%- if message.role == "user" %}
45
+ {{- '<|im_start|>' + message.role + '\n' }}
46
+ {%- if message.content is string %}
47
+ {{- message.content }}
48
+ {%- else %}
49
+ {%- for content in message.content %}
50
+ {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}
51
+ {%- set image_count.value = image_count.value + 1 %}
52
+ {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}
53
+ <|vision_start|><|image_pad|><|vision_end|>
54
+ {%- elif content.type == 'video' or 'video' in content %}
55
+ {%- set video_count.value = video_count.value + 1 %}
56
+ {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}
57
+ <|vision_start|><|video_pad|><|vision_end|>
58
+ {%- elif 'text' in content %}
59
+ {{- content.text }}
60
+ {%- endif %}
61
+ {%- endfor %}
62
+ {%- endif %}
63
+ {{- '<|im_end|>\n' }}
64
+ {%- elif message.role == "assistant" %}
65
+ {{- '<|im_start|>' + message.role + '\n' }}
66
+ {%- generation -%}
67
+ {%- if message.content is string %}
68
+ {{- message.content }}
69
+ {%- else %}
70
+ {%- for content_item in message.content %}
71
+ {%- if 'text' in content_item %}
72
+ {{- content_item.text }}
73
+ {%- endif %}
74
+ {%- endfor %}
75
+ {%- endif %}
76
+ {%- if message.tool_calls %}
77
+ {%- for tool_call in message.tool_calls %}
78
+ {%- if (loop.first and message.content) or (not loop.first) %}
79
+ {{- '\n' }}
80
+ {%- endif %}
81
+ {%- if tool_call.function %}
82
+ {%- set tool_call = tool_call.function %}
83
+ {%- endif %}
84
+ {{- '<tool_call>\n{"name": "' }}
85
+ {{- tool_call.name }}
86
+ {{- '", "arguments": ' }}
87
+ {%- if tool_call.arguments is string %}
88
+ {{- tool_call.arguments }}
89
+ {%- else %}
90
+ {{- tool_call.arguments | tojson }}
91
+ {%- endif %}
92
+ {{- '}\n</tool_call>' }}
93
+ {%- endfor %}
94
+ {%- endif %}
95
+ {{- '<|im_end|>\n' }}
96
+ {%- endgeneration -%}
97
+ {%- elif message.role == "tool" %}
98
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
99
+ {{- '<|im_start|>user' }}
100
+ {%- endif %}
101
+ {{- '\n<tool_response>\n' }}
102
+ {%- if message.content is string %}
103
+ {{- message.content }}
104
+ {%- else %}
105
+ {%- for content in message.content %}
106
+ {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}
107
+ {%- set image_count.value = image_count.value + 1 %}
108
+ {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}
109
+ <|vision_start|><|image_pad|><|vision_end|>
110
+ {%- elif content.type == 'video' or 'video' in content %}
111
+ {%- set video_count.value = video_count.value + 1 %}
112
+ {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}
113
+ <|vision_start|><|video_pad|><|vision_end|>
114
+ {%- elif 'text' in content %}
115
+ {{- content.text }}
116
+ {%- endif %}
117
+ {%- endfor %}
118
+ {%- endif %}
119
+ {{- '\n</tool_response>' }}
120
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
121
+ {{- '<|im_end|>\n' }}
122
+ {%- endif %}
123
+ {%- endif %}
124
+ {%- endfor %}
125
+ {%- if add_generation_prompt %}
126
+ {{- '<|im_start|>assistant\n' }}
127
+ {%- endif %}
tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .main import main
16
+
17
+
18
+ __all__ = ["main"]
tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/accelerate_config.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import importlib.resources as resources
16
+ from pathlib import Path
17
+
18
+
19
+ def resolve_accelerate_config_argument(launch_args: list[str]) -> list[str]:
20
+ """
21
+ Resolve `--accelerate_config` from CLI arguments into `accelerate --config_file`.
22
+
23
+ The function supports either a filesystem path or a predefined config name shipped in `trl/accelerate_configs`
24
+ (without the `.yaml` suffix).
25
+ """
26
+ if "--accelerate_config" not in launch_args:
27
+ return launch_args
28
+
29
+ config_index = launch_args.index("--accelerate_config")
30
+ if config_index + 1 >= len(launch_args):
31
+ raise ValueError("Expected a value after `--accelerate_config`.")
32
+
33
+ config_name = launch_args[config_index + 1]
34
+ if Path(config_name).is_file():
35
+ accelerate_config_path = config_name
36
+ else:
37
+ candidate = resources.files("trl.accelerate_configs").joinpath(f"{config_name}.yaml")
38
+ if not candidate.exists():
39
+ raise ValueError(
40
+ f"Accelerate config {config_name} is neither a file nor a valid config in the `trl` package. "
41
+ "Please provide a valid config name or a path to a config file."
42
+ )
43
+ accelerate_config_path = candidate
44
+
45
+ # Remove '--accelerate_config <value>'.
46
+ launch_args = launch_args[:config_index] + launch_args[config_index + 2 :]
47
+ return ["--config_file", str(accelerate_config_path)] + launch_args
tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/accelerate_launcher.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import importlib.resources as resources
16
+ from collections.abc import Callable
17
+ from typing import Any
18
+
19
+ from accelerate.commands.launch import launch_command, launch_command_parser
20
+
21
+
22
+ def launch_training_script(
23
+ script_name: str,
24
+ launch_args: list[str],
25
+ training_script_args: list[str],
26
+ *,
27
+ launch_command_fn: Callable[[Any], None] = launch_command,
28
+ launch_parser_fn: Callable[[], Any] = launch_command_parser,
29
+ ) -> None:
30
+ """
31
+ Launch a TRL training script through `accelerate launch`.
32
+
33
+ Parameters:
34
+ script_name (`str`):
35
+ Script filename in `trl/scripts`, e.g. `"dpo.py"`.
36
+ launch_args (`list[str]`):
37
+ Arguments consumed by `accelerate launch`.
38
+ training_script_args (`list[str]`):
39
+ Arguments forwarded to the training script.
40
+ launch_command_fn (`Callable[[Any], None]`, *optional*):
41
+ Function used to execute accelerate launch.
42
+ launch_parser_fn (`Callable[[], Any]`, *optional*):
43
+ Factory creating the accelerate launch parser.
44
+ """
45
+ training_script = resources.files("trl.scripts").joinpath(script_name)
46
+ accelerate_args = launch_parser_fn().parse_args(launch_args + [str(training_script)] + training_script_args)
47
+ launch_command_fn(accelerate_args)
tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/commands/__init__.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .base import Command
16
+ from .env import EnvCommand
17
+ from .skills import SkillsCommand
18
+ from .training import TrainingCommand
19
+ from .vllm_serve import VllmServeCommand
20
+
21
+
22
+ def get_commands() -> list[Command]:
23
+ """Return all registered top-level TRL CLI commands."""
24
+ return [
25
+ TrainingCommand("dpo"),
26
+ EnvCommand(),
27
+ TrainingCommand("grpo"),
28
+ TrainingCommand("kto"),
29
+ TrainingCommand("reward"),
30
+ TrainingCommand("rloo"),
31
+ TrainingCommand("sft"),
32
+ SkillsCommand(),
33
+ VllmServeCommand(),
34
+ ]
35
+
36
+
37
+ __all__ = ["Command", "get_commands"]
tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/commands/base.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from abc import ABC, abstractmethod
16
+ from argparse import Namespace
17
+ from dataclasses import dataclass
18
+
19
+
20
+ @dataclass(slots=True)
21
+ class CommandContext:
22
+ """Context shared by CLI commands during execution."""
23
+
24
+ argv: list[str]
25
+
26
+ def argv_after(self, token: str) -> list[str]:
27
+ """
28
+ Return CLI tokens after the first occurrence of `token`.
29
+
30
+ Parameters:
31
+ token (`str`):
32
+ Subcommand name as it appears in `argv`.
33
+ """
34
+ try:
35
+ index = self.argv.index(token)
36
+ except ValueError:
37
+ return []
38
+ return self.argv[index + 1 :]
39
+
40
+
41
+ class Command(ABC):
42
+ """
43
+ Base command definition for the TRL CLI.
44
+
45
+ Parameters:
46
+ name (`str`):
47
+ Subcommand name exposed by the CLI.
48
+ help_text (`str`):
49
+ Short description displayed in help output.
50
+ """
51
+
52
+ def __init__(self, name: str, help_text: str):
53
+ self.name = name
54
+ self.help_text = help_text
55
+
56
+ @abstractmethod
57
+ def register(self, subparsers) -> None:
58
+ """Register this command parser in the subparser collection."""
59
+
60
+ @abstractmethod
61
+ def run(self, args: Namespace, context: CommandContext) -> int:
62
+ """Execute the command."""
tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/commands/env.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from argparse import Namespace
16
+
17
+ from .base import Command, CommandContext
18
+
19
+
20
+ class EnvCommand(Command):
21
+ """CLI command that prints TRL environment information."""
22
+
23
+ def __init__(self):
24
+ super().__init__(name="env", help_text="Print the environment information")
25
+
26
+ def register(self, subparsers) -> None:
27
+ subparsers.add_parser(self.name, help=self.help_text)
28
+
29
+ def run(self, args: Namespace, context: CommandContext) -> int:
30
+ from ...scripts.env import print_env
31
+
32
+ print_env()
33
+ return 0
tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/commands/skills.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from argparse import Namespace
16
+
17
+ from ...skills.cli import add_skills_subcommands
18
+ from .base import Command, CommandContext
19
+
20
+
21
+ class SkillsCommand(Command):
22
+ """CLI command that manages TRL agent skills."""
23
+
24
+ def __init__(self):
25
+ super().__init__(name="skills", help_text="Manage TRL agent skills")
26
+ self._skills_parser = None
27
+
28
+ def register(self, subparsers) -> None:
29
+ self._skills_parser = subparsers.add_parser(self.name, help=self.help_text)
30
+ skills_subparsers = self._skills_parser.add_subparsers(dest="skills_command", help="Skills commands")
31
+ add_skills_subcommands(skills_subparsers)
32
+
33
+ def run(self, args: Namespace, context: CommandContext) -> int:
34
+ if getattr(args, "skills_command", None):
35
+ if hasattr(args, "func"):
36
+ return args.func(args)
37
+ print("Error: Unknown skills command")
38
+ return 1
39
+
40
+ if self._skills_parser is not None:
41
+ self._skills_parser.print_help()
42
+ return 0
tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/commands/training.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import importlib
16
+ from argparse import Namespace
17
+
18
+ from .base import Command, CommandContext
19
+
20
+
21
+ def _subtract_subsequence(lst: list[str], subseq: list[str]) -> list[str]:
22
+ """Return lst with the ordered subsequence subseq removed."""
23
+ sub_iter = iter(subseq)
24
+ current = next(sub_iter, None)
25
+ result = []
26
+ for item in lst:
27
+ if current is not None and item == current:
28
+ current = next(sub_iter, None)
29
+ else:
30
+ result.append(item)
31
+ return result
32
+
33
+
34
+ class TrainingCommand(Command):
35
+ """
36
+ Generic CLI command that launches a training script with accelerate.
37
+
38
+ The script `trl/scripts/<name>.py` must expose a `make_parser()` function.
39
+
40
+ Parameters:
41
+ name (`str`):
42
+ CLI subcommand name (e.g. `"dpo"`).
43
+ """
44
+
45
+ def __init__(self, name: str):
46
+ super().__init__(name=name, help_text=f"Run the {name} training script")
47
+
48
+ def register(self, subparsers) -> None:
49
+ subparsers.add_parser(self.name, help=self.help_text, add_help=False)
50
+
51
+ def run(self, args: Namespace, context: CommandContext) -> int:
52
+ from ..accelerate_config import resolve_accelerate_config_argument
53
+ from ..accelerate_launcher import launch_training_script
54
+
55
+ module = importlib.import_module(f"...scripts.{self.name}", package=__package__)
56
+ all_args = context.argv_after(self.name)
57
+ parser = module.make_parser(prog=f"trl {self.name}")
58
+
59
+ # Handles -h (exits). Returns config_remaining and cli_remaining separately.
60
+ # cli_remaining is an ordered subsequence of all_args; config_remaining is not.
61
+ *_, config_remaining, cli_remaining = parser.parse_args_and_config(
62
+ all_args, return_remaining_strings=True, separate_remaining_strings=True
63
+ )
64
+ launch_args = resolve_accelerate_config_argument(config_remaining + cli_remaining)
65
+ training_script_args = _subtract_subsequence(all_args, cli_remaining)
66
+
67
+ launch_training_script(
68
+ script_name=f"{self.name}.py",
69
+ launch_args=launch_args,
70
+ training_script_args=training_script_args,
71
+ )
72
+ return 0
tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/commands/vllm_serve.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from argparse import Namespace
16
+
17
+ from .base import Command, CommandContext
18
+
19
+
20
+ class VllmServeCommand(Command):
21
+ """CLI command for serving TRL models with vLLM."""
22
+
23
+ def __init__(self):
24
+ super().__init__(name="vllm-serve", help_text="Serve a model with vLLM")
25
+
26
+ def register(self, subparsers) -> None:
27
+ subparsers.add_parser(self.name, help=self.help_text, add_help=False)
28
+
29
+ def run(self, args: Namespace, context: CommandContext) -> int:
30
+ from ...scripts.vllm_serve import main as vllm_serve_main
31
+ from ...scripts.vllm_serve import make_parser as make_vllm_serve_parser
32
+
33
+ parser = make_vllm_serve_parser(prog="trl vllm-serve")
34
+ (script_args,) = parser.parse_args_and_config(args=context.argv_after(self.name))
35
+ vllm_serve_main(script_args)
36
+ return 0
tasks/tasksmith-5b4f21a2a450/environment/source/trl/cli/main.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import sys
16
+ from argparse import ArgumentParser
17
+
18
+ from .commands import get_commands
19
+ from .commands.base import Command, CommandContext
20
+
21
+
22
+ def _build_parser(commands: list[Command]) -> ArgumentParser:
23
+ parser = ArgumentParser(prog="trl", allow_abbrev=False)
24
+ subparsers = parser.add_subparsers(help="available commands", dest="command")
25
+
26
+ for command in commands:
27
+ command.register(subparsers)
28
+
29
+ return parser
30
+
31
+
32
+ def main(argv: list[str] | None = None) -> int:
33
+ """Run the TRL CLI."""
34
+ commands = get_commands()
35
+ commands_by_name = {command.name: command for command in commands}
36
+ parser = _build_parser(commands)
37
+ argv = list(sys.argv[1:] if argv is None else argv)
38
+
39
+ args, _ = parser.parse_known_args(argv)
40
+ command_name = getattr(args, "command", None)
41
+ if command_name is None:
42
+ parser.print_help()
43
+ return 0
44
+
45
+ command = commands_by_name[command_name]
46
+ context = CommandContext(argv=argv)
47
+ return command.run(args, context)
48
+
49
+
50
+ if __name__ == "__main__":
51
+ raise SystemExit(main())
tasks/tasksmith-5b4f21a2a450/environment/source/trl/data_utils.py ADDED
@@ -0,0 +1,977 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import copy
16
+ from collections import defaultdict, deque
17
+ from collections.abc import Callable, Sequence
18
+ from itertools import takewhile
19
+ from typing import Any, Literal, TypeVar
20
+
21
+ import numpy as np
22
+ import pyarrow as pa
23
+ import pyarrow.compute as pc
24
+ import pyarrow.types
25
+ from datasets import Dataset, DatasetDict, IterableDataset, IterableDatasetDict
26
+ from transformers import PreTrainedTokenizerBase, ProcessorMixin
27
+
28
+
29
+ DatasetType = TypeVar("DatasetType", Dataset, DatasetDict)
30
+ IterableDatasetType = TypeVar("IterableDatasetType", IterableDataset, IterableDatasetDict)
31
+
32
+
33
+ def prepare_multimodal_messages(messages: list[dict[str, Any]], images: list | None = None) -> list[dict[str, Any]]:
34
+ # docstyle-ignore # because <Image> is not parsable in the code block
35
+ """
36
+ Convert messages into a structured multimodal format and inject the provided images into the message contents.
37
+
38
+ Args:
39
+ messages (`list[dict[str, Any]]`):
40
+ Messages with `"role"`, `"content"` (or `"tool_calls"`). Content may be a raw string before transformation.
41
+ List of messages with a `"role"` key (`"system"`, `"user"`, `"assistant"`, or `"tool"`) and a `"content"` key containing
42
+ either a string or a list of structured blocks if already prepared. Optionally, the `"content"` might
43
+ be `None` or not provided in favour of `"tool_calls"` in the `"assistant"` turns if applicable.
44
+ images (`list`, *optional*):
45
+ List of image objects to insert in the messages.
46
+
47
+ Returns:
48
+ `list[dict[str, Any]]`: A new list of messages where every `"content"` value is a list of structured
49
+ content blocks, and all `"image"` placeholders are populated with the corresponding image objects. If the
50
+ assistant turns contains `"tool_calls"`, then the `"content"` might be empty.
51
+
52
+ Notes:
53
+ - When the input `messages` isn't already in the structured format, (i.e., all `"content"` values are strings),
54
+ the function transforms them into the structured format by wrapping text in `{"type": "text", "text": ...}`
55
+ and inserting `{"type": "image"}` placeholders for the images *before* the first user message.
56
+ If the number of placeholders does not match the number of provided images, an error is raised.
57
+ - Existing image blocks that already include an `"image"` payload are preserved as-is. Only unfilled image
58
+ placeholders are counted and populated from `images`.
59
+
60
+ Example:
61
+ ```python
62
+ # Input
63
+ [
64
+ {"role": "user", "content": "What's in this image?"},
65
+ {"role": "assistant", "content": "It looks like a cat."},
66
+ ]
67
+
68
+ # Output, one image provided
69
+ [
70
+ {"role": "user", "content": [{"type": "image", "image": <PIL.Image.Image>}, {"type": "text", "text": "What's in this image?"}]},
71
+ {"role": "assistant", "content": [{"type": "text", "text": "It looks like a cat."}]},
72
+ ]
73
+ ```
74
+ """
75
+ images = images or []
76
+
77
+ # First, convert all messages to the structured format if needed, and insert image placeholders if needed.
78
+ # Build new message dicts only when transforming string content to avoid modifying the originals.
79
+ new_messages = []
80
+ images_included = False
81
+ for message in messages:
82
+ if message["role"] == "user":
83
+ if isinstance(message["content"], str) and not images_included:
84
+ image_entries = [{"type": "image"} for _ in range(len(images))]
85
+ message = {**message, "content": [*image_entries, {"type": "text", "text": message["content"]}]}
86
+ images_included = True
87
+ elif isinstance(message["content"], str):
88
+ message = {**message, "content": [{"type": "text", "text": message["content"]}]}
89
+ elif message["role"] in {"assistant", "system", "tool"}:
90
+ if isinstance(message.get("content"), str):
91
+ message = {**message, "content": [{"type": "text", "text": message["content"]}]}
92
+ else:
93
+ raise ValueError(
94
+ f"Invalid role in message: {message['role']}. Expected 'system', 'user', 'assistant', or 'tool'."
95
+ )
96
+ new_messages.append(message)
97
+
98
+ # Then, check that the number of image placeholders matches the number of images provided
99
+ num_placeholders = sum(
100
+ sum(1 for part in message["content"] if part["type"] == "image" and "image" not in part)
101
+ for message in new_messages
102
+ if message.get("content") and message["role"] != "tool"
103
+ )
104
+ if num_placeholders != len(images):
105
+ raise ValueError(
106
+ f"Number of images provided ({len(images)}) does not match number of image placeholders ({num_placeholders})."
107
+ )
108
+
109
+ # Then, fill in the actual images in the placeholders
110
+ if images:
111
+ img_idx = 0
112
+ for i, message in enumerate(new_messages):
113
+ if not message.get("content") or message["role"] == "tool":
114
+ continue
115
+ new_content = []
116
+ for part in message["content"]:
117
+ if part["type"] == "image" and "image" not in part:
118
+ new_content.append({**part, "image": images[img_idx]})
119
+ img_idx += 1
120
+ else:
121
+ new_content.append(part)
122
+ new_messages[i] = {**message, "content": new_content}
123
+
124
+ return new_messages
125
+
126
+
127
+ def prepare_multimodal_messages_vllm(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
128
+ # docstyle-ignore # because <Image> is not parsable in the code block
129
+ """
130
+ Convert structured multimodal messages into a format compatible with vLLM. Replaces `"type": "image"` blocks with
131
+ `"type": "image_pil"` blocks, and `"image": Image` with `"image_pil": Image`.
132
+
133
+ Args:
134
+ messages (`list[dict[str, Any]]`):
135
+ Messages with `"role"` and `"content"`. Content is expected to be a list of structured blocks.
136
+
137
+ Returns:
138
+ `list[dict[str, Any]]`:
139
+ A deep-copied list of messages compatible with vLLM's expected input format.
140
+
141
+ Example:
142
+ ```python
143
+ # Input
144
+ [{"role": "user", "content": [{"type": "image", "image": <PIL.Image.Image>}, {"type": "text", "text": "What's in this image?"}]}]
145
+
146
+ # Output
147
+ [{"role": "user", "content": [{"type": "image_pil", "image_pil": <PIL.Image.Image>}, {"type": "text", "text": "What's in this image?"}]}]
148
+ ```
149
+ """
150
+ messages = copy.deepcopy(messages) # avoid modifying the original messages
151
+ for message in messages:
152
+ if isinstance(message["content"], list):
153
+ for part in message["content"]:
154
+ if part["type"] == "image":
155
+ part["type"] = "image_pil" # vLLM expects 'image_pil' key for images
156
+ part["image_pil"] = part.pop("image")
157
+ return messages
158
+
159
+
160
+ def is_conversational(example: dict[str, Any]) -> bool:
161
+ r"""
162
+ Check if the example is in a conversational format.
163
+
164
+ Args:
165
+ example (`dict[str, Any]`):
166
+ A single data entry of a dataset. The example can have different keys depending on the dataset type.
167
+
168
+ Returns:
169
+ `bool`:
170
+ `True` if the data is in a conversational format, `False` otherwise.
171
+
172
+ Examples:
173
+
174
+ ```python
175
+ >>> example = {"prompt": [{"role": "user", "content": "What color is the sky?"}]}
176
+ >>> is_conversational(example)
177
+ True
178
+
179
+ >>> example = {"prompt": "The sky is"}
180
+ >>> is_conversational(example)
181
+ False
182
+ ```
183
+ """
184
+ supported_keys = ["prompt", "chosen", "rejected", "completion", "messages"]
185
+ example_keys = {key for key in example.keys() if key in supported_keys}
186
+
187
+ # It must have one of the supported keys
188
+ if example_keys:
189
+ key = example_keys.pop() # take the first supported key
190
+ maybe_messages = example[key]
191
+ # It must be a list of messages
192
+ if isinstance(maybe_messages, list):
193
+ maybe_message = maybe_messages[0]
194
+ # Each message must a list of dictionaries with keys "role" and "content"
195
+ if isinstance(maybe_message, dict) and "role" in maybe_message:
196
+ return True
197
+
198
+ return False
199
+
200
+
201
+ def apply_chat_template(
202
+ example: dict[str, list[dict[str, str]]],
203
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin,
204
+ tools: list[dict | Callable] | None = None,
205
+ **template_kwargs,
206
+ ) -> dict[str, str]:
207
+ r"""
208
+ Apply a chat template to a conversational example along with the schema for a list of functions in `tools`.
209
+
210
+ For more details, see [`maybe_apply_chat_template`].
211
+ """
212
+ tools = tools or None # `or None`: Llama bug: it renders tool boilerplate for tools=[]
213
+ # Check that the example has the correct keys
214
+ supported_keys = ["prompt", "chosen", "rejected", "completion", "messages", "label"]
215
+ example_keys = {key for key in example.keys() if key in supported_keys}
216
+ if example_keys not in [
217
+ {"messages"}, # language modeling
218
+ {"prompt"}, # prompt-only
219
+ {"prompt", "completion"}, # prompt-completion
220
+ {"prompt", "chosen", "rejected"}, # preference
221
+ {"chosen", "rejected"}, # preference with implicit prompt
222
+ {"prompt", "completion", "label"}, # unpaired preference
223
+ ]:
224
+ raise KeyError(f"Invalid keys in the example: {example_keys}")
225
+
226
+ # Apply the chat template to the whole conversation
227
+ if "messages" in example:
228
+ messages = processing_class.apply_chat_template(
229
+ example["messages"],
230
+ tools=tools,
231
+ tokenize=False,
232
+ **example.get("chat_template_kwargs", {}),
233
+ **template_kwargs,
234
+ )
235
+
236
+ # Apply the chat template to the prompt, adding the generation prompt
237
+ if "prompt" in example:
238
+ last_role = example["prompt"][-1]["role"]
239
+ if last_role in ["user", "tool"]:
240
+ add_generation_prompt = True
241
+ continue_final_message = False
242
+ elif last_role == "assistant":
243
+ add_generation_prompt = False
244
+ continue_final_message = True
245
+ else:
246
+ raise ValueError(f"Invalid role in the last message: {last_role}")
247
+ prompt = processing_class.apply_chat_template(
248
+ example["prompt"],
249
+ tools=tools,
250
+ continue_final_message=continue_final_message,
251
+ tokenize=False,
252
+ add_generation_prompt=add_generation_prompt,
253
+ **example.get("chat_template_kwargs", {}),
254
+ **template_kwargs,
255
+ )
256
+
257
+ # Apply the chat template to the entire prompt + completion
258
+ if "prompt" in example: # explicit prompt and prompt-completion case
259
+ if "chosen" in example:
260
+ prompt_chosen = processing_class.apply_chat_template(
261
+ example["prompt"] + example["chosen"],
262
+ tools=tools,
263
+ tokenize=False,
264
+ **example.get("chat_template_kwargs", {}),
265
+ **template_kwargs,
266
+ )
267
+ # DeepSeek-R1 inserts a <tool_call> token when using `add_generation_prompt`, which can cause discrepancies
268
+ # between the prompt alone and the combined prompt+completion. To ensure consistency, we extract the
269
+ # common prefix between the two. In most cases, this is a no-op.
270
+ prompt = "".join(x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt, prompt_chosen, strict=False)))
271
+
272
+ chosen = prompt_chosen[len(prompt) :]
273
+ if "rejected" in example and "prompt" in example: # explicit prompt
274
+ prompt_rejected = processing_class.apply_chat_template(
275
+ example["prompt"] + example["rejected"],
276
+ tools=tools,
277
+ tokenize=False,
278
+ **example.get("chat_template_kwargs", {}),
279
+ **template_kwargs,
280
+ )
281
+ # Handle DeepSeek-R1 <tool_call> token, see the above comment for details
282
+ prompt = "".join(
283
+ x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt, prompt_rejected, strict=False))
284
+ )
285
+ rejected = prompt_rejected[len(prompt) :]
286
+ if "completion" in example:
287
+ prompt_completion = processing_class.apply_chat_template(
288
+ example["prompt"] + example["completion"],
289
+ tools=tools,
290
+ tokenize=False,
291
+ **example.get("chat_template_kwargs", {}),
292
+ **template_kwargs,
293
+ )
294
+ # Handle DeepSeek-R1 <tool_call> token, see the above comment for details
295
+ prompt = "".join(
296
+ x for x, _ in takewhile(lambda x: x[0] == x[1], zip(prompt, prompt_completion, strict=False))
297
+ )
298
+ completion = prompt_completion[len(prompt) :]
299
+ else: # implicit prompt case
300
+ if "chosen" in example:
301
+ chosen = processing_class.apply_chat_template(
302
+ example["chosen"],
303
+ tools=tools,
304
+ tokenize=False,
305
+ **example.get("chat_template_kwargs", {}),
306
+ **template_kwargs,
307
+ )
308
+ if "rejected" in example:
309
+ rejected = processing_class.apply_chat_template(
310
+ example["rejected"],
311
+ tools=tools,
312
+ tokenize=False,
313
+ **example.get("chat_template_kwargs", {}),
314
+ **template_kwargs,
315
+ )
316
+
317
+ # Extract the completion by removing the prompt part from the prompt-completion string
318
+ output = {}
319
+ if "messages" in example:
320
+ output["text"] = messages
321
+ if "prompt" in example:
322
+ output["prompt"] = prompt
323
+ if "chosen" in example:
324
+ output["chosen"] = chosen
325
+ if "rejected" in example:
326
+ output["rejected"] = rejected
327
+ if "completion" in example:
328
+ output["completion"] = completion
329
+ if "label" in example:
330
+ output["label"] = example["label"]
331
+
332
+ return output
333
+
334
+
335
+ def maybe_apply_chat_template(
336
+ example: dict[str, list[dict[str, str]]],
337
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin,
338
+ tools: list[dict | Callable] | None = None,
339
+ **template_kwargs: Any,
340
+ ) -> dict[str, str]:
341
+ r"""
342
+ If the example is in a conversational format, apply a chat template to it.
343
+
344
+ Args:
345
+ example (`dict[str, list[dict[str, str]]`):
346
+ Dictionary representing a single data entry of a conversational dataset. Each data entry can have different
347
+ keys depending on the dataset type. The supported dataset types are:
348
+
349
+ - Language modeling dataset: `"messages"`.
350
+ - Prompt-only dataset: `"prompt"`.
351
+ - Prompt-completion dataset: `"prompt"` and `"completion"`.
352
+ - Preference dataset: `"prompt"`, `"chosen"`, and `"rejected"`.
353
+ - Preference dataset with implicit prompt: `"chosen"` and `"rejected"`.
354
+ - Unpaired preference dataset: `"prompt"`, `"completion"`, and `"label"`.
355
+
356
+ For keys `"messages"`, `"prompt"`, `"chosen"`, `"rejected"`, and `"completion"`, the values are lists of
357
+ messages, where each message is a dictionary with keys `"role"` and `"content"`. Additionally, the example
358
+ may contain a `"chat_template_kwargs"` key, which is a dictionary of additional keyword arguments to pass
359
+ to the chat template renderer.
360
+ processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]):
361
+ Tokenizer to apply the chat template with.
362
+ tools (`list[dict | Callable]`, *optional*):
363
+ A list of tools (callable functions) that will be accessible to the model. If the template does not support
364
+ function calling, this argument will have no effect.
365
+ **template_kwargs (`Any`, *optional*):
366
+ Additional kwargs to pass to the template renderer. Will be accessible by the chat template.
367
+
368
+ Returns:
369
+ `dict[str, str]`:
370
+ Formatted example with the chat template applied.
371
+
372
+ Notes:
373
+ - This function does not alter the keys, except for Language modeling dataset, where `"messages"` is replaced
374
+ by `"text"`.
375
+
376
+ - In case of prompt-only data, if the last role is `"user"`, the generation prompt is added to the prompt.
377
+ Else, if the last role is `"assistant"`, the final message is continued.
378
+
379
+ Example:
380
+
381
+ ```python
382
+ >>> from transformers import AutoTokenizer
383
+
384
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct")
385
+ >>> example = {
386
+ ... "prompt": [{"role": "user", "content": "What color is the sky?"}],
387
+ ... "completion": [{"role": "assistant", "content": "It is blue."}],
388
+ ... }
389
+ >>> apply_chat_template(example, tokenizer)
390
+ {'prompt': '<|user|>\nWhat color is the sky?<|end|>\n<|assistant|>\n', 'completion': 'It is blue.<|end|>\n'}
391
+ ```
392
+ """
393
+ if is_conversational(example):
394
+ return apply_chat_template(example, processing_class, tools, **template_kwargs)
395
+ else:
396
+ return example
397
+
398
+
399
+ def _unpair_row(batch: dict[str, list[Any]]) -> dict[str, list[Any]]:
400
+ batch_size = len(batch["chosen"])
401
+ new_batch = {
402
+ "completion": batch["chosen"] + batch["rejected"],
403
+ "label": [True] * batch_size + [False] * batch_size,
404
+ }
405
+ if "prompt" in batch:
406
+ new_batch["prompt"] = batch["prompt"] + batch["prompt"]
407
+ return new_batch
408
+
409
+
410
+ def unpair_preference_dataset(
411
+ dataset: DatasetType | IterableDatasetType, **map_kwargs
412
+ ) -> DatasetType | IterableDatasetType:
413
+ # docstyle-ignore
414
+ """
415
+ Unpair a preference dataset.
416
+
417
+ The output contains only `"prompt"`, `"completion"`, and `"label"`; all other columns are dropped.
418
+
419
+ Args:
420
+ dataset ([`~datasets.Dataset`] or [`~datasets.DatasetDict`] or [`~datasets.IterableDataset`] or [`~datasets.IterableDatasetDict`]):
421
+ Preference dataset to unpair. The dataset must have columns `"chosen"`, `"rejected"` and optionally
422
+ `"prompt"`.
423
+ **map_kwargs (`dict`, *optional*):
424
+ Additional keyword arguments to pass to the dataset's map method when unpairing preferences.
425
+
426
+ Returns:
427
+ [`~datasets.Dataset`] or [`~datasets.DatasetDict`] or [`~datasets.IterableDataset`] or [`~datasets.IterableDatasetDict`]:
428
+ The unpaired preference dataset.
429
+
430
+ Example:
431
+
432
+ ```python
433
+ >>> from datasets import Dataset
434
+
435
+ >>> dataset_dict = {
436
+ ... "prompt": ["The sky is", "The sun is"],
437
+ ... "chosen": [" blue.", "in the sky."],
438
+ ... "rejected": [" green.", " in the sea."],
439
+ ... }
440
+ >>> dataset = Dataset.from_dict(dataset_dict)
441
+ >>> dataset = unpair_preference_dataset(dataset)
442
+ >>> dataset
443
+ Dataset({
444
+ features: ['prompt', 'completion', 'label'],
445
+ num_rows: 4
446
+ })
447
+
448
+ >>> dataset[0]
449
+ {'prompt': 'The sky is', 'completion': ' blue.', 'label': True}
450
+ ```
451
+ """
452
+ if isinstance(dataset, DatasetDict):
453
+ column_names = next(iter(dataset.values())).column_names
454
+ elif isinstance(dataset, Dataset):
455
+ column_names = dataset.column_names
456
+ else: # IterableDataset
457
+ column_names = dataset.column_names or list(next(iter(dataset)).keys())
458
+ return dataset.map(_unpair_row, batched=True, remove_columns=column_names, **map_kwargs)
459
+
460
+
461
+ def maybe_unpair_preference_dataset(
462
+ dataset: DatasetType, num_proc: int | None = None, desc: str | None = None
463
+ ) -> DatasetType:
464
+ r"""
465
+ Unpair a preference dataset if it is paired.
466
+
467
+ Args:
468
+ dataset ([`~datasets.Dataset`] or [`~datasets.DatasetDict`]):
469
+ Preference dataset to unpair. The dataset must have columns `"chosen"`, `"rejected"` and optionally
470
+ `"prompt"`.
471
+ num_proc (`int`, *optional*):
472
+ Number of processes to use for processing the dataset.
473
+ desc (`str`, *optional*):
474
+ Meaningful description to be displayed alongside with the progress bar while mapping examples.
475
+
476
+ Returns:
477
+ [`~datasets.Dataset`] or [`~datasets.DatasetDict`]: The unpaired preference dataset if it was paired, otherwise
478
+ the original dataset.
479
+
480
+ Example:
481
+
482
+ ```python
483
+ >>> from datasets import Dataset
484
+
485
+ >>> dataset_dict = {
486
+ ... "prompt": ["The sky is", "The sun is"],
487
+ ... "chosen": [" blue.", "in the sky."],
488
+ ... "rejected": [" green.", " in the sea."],
489
+ ... }
490
+ >>> dataset = Dataset.from_dict(dataset_dict)
491
+ >>> dataset = unpair_preference_dataset(dataset)
492
+ >>> dataset
493
+ Dataset({
494
+ features: ['prompt', 'completion', 'label'],
495
+ num_rows: 4
496
+ })
497
+
498
+ >>> dataset[0]
499
+ {'prompt': 'The sky is', 'completion': ' blue.', 'label': True}
500
+ ```
501
+ """
502
+ if isinstance(dataset, DatasetDict):
503
+ column_names = dataset[list(dataset.keys())[0]].column_names
504
+ else:
505
+ column_names = dataset.column_names
506
+ if "chosen" in column_names and "rejected" in column_names:
507
+ return unpair_preference_dataset(dataset, num_proc=num_proc, desc=desc)
508
+ else:
509
+ return dataset
510
+
511
+
512
+ def extract_prompt(example: dict[str, Sequence]) -> dict[str, Sequence]:
513
+ r"""
514
+ Extracts the shared prompt from a preference data example, where the prompt is implicit within both the chosen and
515
+ rejected completions.
516
+
517
+ The function identifies the longest common sequence (prefix) of conversation turns between the "chosen" and
518
+ "rejected" completions and extracts this as the prompt. It then removes this prompt from the respective "chosen"
519
+ and "rejected" completions.
520
+
521
+ Args:
522
+ example (`dict[str, list]`):
523
+ A dictionary representing a single data entry in the preference dataset. It must contain the keys
524
+ `"chosen"` and `"rejected"`, where each value is either conversational or standard (`str`).
525
+
526
+ Returns:
527
+ `dict[str, list]`: A dictionary containing:
528
+ - `"prompt"`: The longest common prefix between the "chosen" and "rejected" completions.
529
+ - `"chosen"`: The remainder of the "chosen" completion, with the prompt removed.
530
+ - `"rejected"`: The remainder of the "rejected" completion, with the prompt removed.
531
+
532
+ Examples:
533
+
534
+ ```python
535
+ >>> example = {
536
+ ... "chosen": [
537
+ ... {"role": "user", "content": "What color is the sky?"},
538
+ ... {"role": "assistant", "content": "It is blue."},
539
+ ... ],
540
+ ... "rejected": [
541
+ ... {"role": "user", "content": "What color is the sky?"},
542
+ ... {"role": "assistant", "content": "It is green."},
543
+ ... ],
544
+ ... }
545
+ >>> extract_prompt(example)
546
+ {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}],
547
+ 'chosen': [{'role': 'assistant', 'content': 'It is blue.'}],
548
+ 'rejected': [{'role': 'assistant', 'content': 'It is green.'}]}
549
+ ```
550
+
551
+ Or, with the `map` method of [`~datasets.Dataset`]:
552
+
553
+ ```python
554
+ >>> from trl import extract_prompt
555
+ >>> from datasets import Dataset
556
+
557
+ >>> dataset_dict = {
558
+ ... "chosen": [
559
+ ... [
560
+ ... {"role": "user", "content": "What color is the sky?"},
561
+ ... {"role": "assistant", "content": "It is blue."},
562
+ ... ],
563
+ ... [
564
+ ... {"role": "user", "content": "Where is the sun?"},
565
+ ... {"role": "assistant", "content": "In the sky."},
566
+ ... ],
567
+ ... ],
568
+ ... "rejected": [
569
+ ... [
570
+ ... {"role": "user", "content": "What color is the sky?"},
571
+ ... {"role": "assistant", "content": "It is green."},
572
+ ... ],
573
+ ... [
574
+ ... {"role": "user", "content": "Where is the sun?"},
575
+ ... {"role": "assistant", "content": "In the sea."},
576
+ ... ],
577
+ ... ],
578
+ ... }
579
+ >>> dataset = Dataset.from_dict(dataset_dict)
580
+ >>> dataset = dataset.map(extract_prompt)
581
+ >>> dataset[0]
582
+ {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}],
583
+ 'chosen': [{'role': 'assistant', 'content': 'It is blue.'}],
584
+ 'rejected': [{'role': 'assistant', 'content': 'It is green.'}]}
585
+ ```
586
+ """
587
+ for idx in range(min(len(example["chosen"]), len(example["rejected"]))):
588
+ if example["chosen"][idx] != example["rejected"][idx]:
589
+ if example["chosen"][idx - 1] == " ": # remove space before the prompt
590
+ idx -= 1
591
+ break
592
+ return {
593
+ "prompt": example["chosen"][:idx],
594
+ "chosen": example["chosen"][idx:],
595
+ "rejected": example["rejected"][idx:],
596
+ }
597
+
598
+
599
+ def maybe_extract_prompt(example: dict[str, list]) -> dict[str, list]:
600
+ r"""
601
+ Extracts the shared prompt from a preference data example, where the prompt is implicit within both the chosen and
602
+ rejected completions.
603
+
604
+ If the example already contains a `"prompt"` key, the function returns the example as is. For more details, see
605
+ [`extract_prompt`].
606
+ ```
607
+ """
608
+ # Some dataset add a `"prompt"` column, even though the prompt is implicit and included in the "chosen" and
609
+ # "rejected" completions. E.g.:
610
+ # {"prompt": "What color is the sky?",
611
+ # "chosen": [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}],
612
+ # "rejected": [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}]}
613
+ # That's why we check if the prompt is also conversational before deciding not to extract it.
614
+ if "chosen" not in example or "rejected" not in example: # not a preference example
615
+ return example
616
+ if "prompt" in example:
617
+ # Both conversational or both non-conversational
618
+ chosen_conv = is_conversational({"chosen": example["chosen"]})
619
+ prompt_conv = is_conversational({"prompt": example["prompt"]})
620
+ if (chosen_conv and prompt_conv) or (not chosen_conv and not prompt_conv):
621
+ return example
622
+ return extract_prompt({"chosen": example["chosen"], "rejected": example["rejected"]})
623
+
624
+
625
+ def _get_dataset_format(dataset: DatasetType) -> dict[str, Any]:
626
+ if isinstance(dataset, (DatasetDict, IterableDatasetDict)):
627
+ dataset = dataset[next(iter(dataset))]
628
+ if isinstance(dataset, Dataset):
629
+ format = dataset.format
630
+ else:
631
+ format_type = dataset._formatting.format_type if dataset._formatting is not None else None
632
+ format = {"type": format_type}
633
+ format.update(format.pop("format_kwargs", {}))
634
+ return format
635
+
636
+
637
+ def _check_if_columns_can_be_packed(columns: list[pa.Array]):
638
+ first_column_offsets = None
639
+ for idx, column in enumerate(columns):
640
+ if not (pyarrow.types.is_list(column.type) or pyarrow.types.is_large_list(column.type)):
641
+ raise TypeError("Packing requires all columns to be lists of lists.")
642
+
643
+ if idx == 0:
644
+ first_column_offsets = column.offsets
645
+ elif not first_column_offsets.equals(column.offsets):
646
+ raise ValueError("All columns must have values of the same length.")
647
+
648
+
649
+ class _SegmentTree:
650
+ """
651
+ A segment tree data structure that, when initialized as `_SegmentTree(maxval)`, efficiently finds the next larger
652
+ value for a given input within the range [1, maxval].
653
+
654
+ See [Fewer Truncations Improve Language Modeling](https://huggingface.co/papers/2404.10830) for more details.
655
+ """
656
+
657
+ def __init__(self, maxval: int):
658
+ self.maxval = maxval
659
+ # For non-power-of-2 values, we need to round up to the next power of 2 for the tree size
660
+ self.tree_size = 1 << (maxval - 1).bit_length()
661
+ self.tree = [0] * (2 * self.tree_size)
662
+
663
+ def add(self, val):
664
+ assert 0 < val <= self.maxval
665
+ i = self.tree_size + val - 1
666
+ self.tree[i] = val
667
+ while i > 1:
668
+ i >>= 1
669
+ left, right = self.tree[i << 1], self.tree[(i << 1) + 1]
670
+ # Compare the values using if-else otherwise repeated calls to `builtins.max` become the bottleneck
671
+ self.tree[i] = left if left >= right else right
672
+
673
+ def remove(self, val):
674
+ assert 0 < val <= self.maxval
675
+ i = self.tree_size + val - 1
676
+ self.tree[i] = 0
677
+ while i > 1:
678
+ i >>= 1
679
+ left, right = self.tree[i << 1], self.tree[(i << 1) + 1]
680
+ # Compare the values using if-else otherwise repeated calls to `builtins.max` become the bottleneck
681
+ self.tree[i] = left if left >= right else right
682
+
683
+ def search(self, val):
684
+ assert 0 < val <= self.maxval
685
+ i = 1
686
+ while i < self.tree_size:
687
+ if self.tree[i << 1] >= val:
688
+ i = i << 1
689
+ else:
690
+ i = (i << 1) + 1
691
+ return self.tree[i]
692
+
693
+
694
+ def _pack_bfd(
695
+ examples: pa.Table, seq_length: int, on_seq_length_overflow: Literal["truncate", "split"] = "truncate"
696
+ ) -> pa.Table:
697
+ """Pack sequences in a pyarrow Table using Best Fit Decreasing strategy."""
698
+ columns = [column.chunks[0] for column in examples.combine_chunks().columns]
699
+ _check_if_columns_can_be_packed(columns)
700
+ assert len(columns) > 0
701
+
702
+ lengths = pc.list_value_length(columns[0])
703
+
704
+ # Filter out empty sequences
705
+ non_empty_mask = pc.greater(lengths, 0)
706
+ columns = [pc.filter(column, non_empty_mask) for column in columns]
707
+ lengths = pc.filter(lengths, non_empty_mask)
708
+
709
+ if on_seq_length_overflow == "truncate":
710
+ columns = [pc.list_slice(column, 0, seq_length) for column in columns]
711
+ elif on_seq_length_overflow == "split":
712
+ lengths = lengths.to_numpy()
713
+ # Split the sequences longer than `seq_length` into chunks (of length `seq_length` or less) while respecting sequence boundaries
714
+ num_fragments = np.ceil(lengths / seq_length).astype(int)
715
+ offsets = np.arange(np.sum(num_fragments) + 1, dtype=columns[0].offsets.type.to_pandas_dtype()) * seq_length
716
+ # "Left-shift" the offsets to account for the last fragment of each original sequence possibly being shorter than `seq_length`
717
+ diff = np.zeros_like(offsets)
718
+ diff[np.cumsum(num_fragments)] = -lengths % seq_length
719
+ diff = np.cumsum(diff)
720
+ offsets -= diff
721
+ columns = [
722
+ type(column).from_arrays(offsets.astype(column.offsets.type.to_pandas_dtype()), column.values)
723
+ for column in columns
724
+ ]
725
+ else:
726
+ raise ValueError(f"Invalid `on_seq_length_overflow`: {on_seq_length_overflow}. Use 'truncate' or 'split'.")
727
+
728
+ examples = pa.Table.from_arrays(columns, names=examples.column_names)
729
+ lengths = pc.list_value_length(columns[0])
730
+ examples = examples.append_column("seq_lengths", lengths) # Allows us to later construct `position_ids`
731
+ ids = np.arange(len(examples))
732
+ lengths = pc.make_struct(lengths, ids)
733
+ lengths = lengths.sort("descending", by=0)
734
+
735
+ # Greedy BFD binning using a segment tree to quickly find best-fit remaining space.
736
+ segment_tree = _SegmentTree(seq_length)
737
+ segment_tree.add(seq_length) # the max, `seq_length` bin is always available
738
+ space_to_bin = defaultdict(deque)
739
+
740
+ # Bin is represented as a dict (of example ids and sum of their lengths) to allow in-place updates
741
+ bins: list[dict] = []
742
+ for length, idx in zip(lengths.field(0).to_numpy(), lengths.field(1).to_numpy(), strict=True):
743
+ space = segment_tree.search(length)
744
+
745
+ if space < seq_length:
746
+ # Use existing bin with exactly this amount of space
747
+ bin = space_to_bin[space].popleft()
748
+ else:
749
+ # Create a new bin
750
+ bin = {"ids": [], "length": 0}
751
+ bins.append(bin)
752
+
753
+ bin["ids"].append(idx)
754
+ bin["length"] += length
755
+ if space < seq_length and not space_to_bin[space]:
756
+ segment_tree.remove(space)
757
+
758
+ space = space - length
759
+ space_to_bin[space].append(bin)
760
+ if space > 0:
761
+ segment_tree.add(space)
762
+
763
+ examples = pc.take(examples, [id_ for bin in bins for id_ in bin["ids"]])
764
+ offsets = np.cumsum([0] + [bin["length"] for bin in bins])
765
+
766
+ assert all(
767
+ column.num_chunks == 1 for column in examples.columns
768
+ ) # `pc.take` returns a ChunkedArray with a single chunk
769
+
770
+ lengths = examples["seq_lengths"].chunks[0]
771
+ examples = examples.drop_columns("seq_lengths")
772
+ lengths = pa.ListArray.from_arrays(np.cumsum([0] + [len(bin["ids"]) for bin in bins], dtype=np.int32), lengths)
773
+
774
+ columns = []
775
+ for column in examples.columns:
776
+ column = column.chunks[0]
777
+ assert pa.types.is_list(column.type) or pa.types.is_large_list(column.type)
778
+ dtype = column.offsets.type.to_pandas_dtype()
779
+ column = type(column).from_arrays(offsets.astype(dtype), column.values)
780
+ columns.append(column)
781
+ return pa.Table.from_arrays(columns + [lengths], names=examples.column_names + ["seq_lengths"])
782
+
783
+
784
+ def _pack_wrapped(examples: pa.Table, seq_length: int) -> pa.Table:
785
+ """Pack sequences in a pyarrow Table using a wrapped strategy."""
786
+ columns = [column.chunks[0] for column in examples.combine_chunks().columns]
787
+ _check_if_columns_can_be_packed(columns)
788
+ offsets, values = columns[0].offsets, columns[0].values
789
+ values = values[offsets[0].as_py() : offsets[-1].as_py()]
790
+ num_elements = len(values)
791
+ offsets = np.arange(0, num_elements, seq_length, dtype=columns[0].offsets.type.to_pandas_dtype())
792
+ offsets = np.concatenate((offsets, [num_elements]))
793
+ columns = [
794
+ type(column).from_arrays(offsets.astype(column.offsets.type.to_pandas_dtype()), column.values)
795
+ for column in columns
796
+ ]
797
+ return pa.Table.from_arrays(columns, names=examples.column_names)
798
+
799
+
800
+ def pack_dataset(
801
+ dataset: DatasetType,
802
+ seq_length: int,
803
+ strategy: str = "bfd",
804
+ map_kwargs: dict[str, Any] | None = None,
805
+ ) -> DatasetType:
806
+ r"""
807
+ Pack sequences in a dataset into chunks of size `seq_length`.
808
+
809
+ Args:
810
+ dataset ([`~datasets.Dataset`] or [`~datasets.DatasetDict`]):
811
+ Dataset to pack
812
+ seq_length (`int`):
813
+ Target sequence length to pack to.
814
+ strategy (`str`, *optional*, defaults to `"bfd"`):
815
+ Packing strategy to use. Can be either:
816
+
817
+ - `"bfd"` (Best Fit Decreasing): Preserves sequence boundaries and truncates sequences that exceed
818
+ `seq_length`, discarding overflow tokens. Ideal for SFT and conversational datasets where maintaining
819
+ conversation structure is important.
820
+ - `"bfd_split"`: Similar to `"bfd"` but splits overflow sequences for packing into other examples. Prevents
821
+ token loss for pre-training or long documents, but may break conversation structure in SFT datasets.
822
+ - `"wrapped"`: Faster but more aggressive. Ignores sequence boundaries and will cut sequences in the middle
823
+ to completely fill each packed sequence with data.
824
+ map_kwargs (`dict`, *optional*):
825
+ Additional keyword arguments to pass to the dataset's map method when packing examples.
826
+
827
+ Returns:
828
+ [`~datasets.Dataset`] or [`~datasets.DatasetDict`]: The dataset with packed sequences. The number of examples
829
+ may decrease as sequences are combined.
830
+
831
+ Example:
832
+ ```python
833
+ >>> from datasets import Dataset
834
+ >>> from trl import pack_dataset
835
+
836
+ >>> examples = {
837
+ ... "input_ids": [[1, 2, 3, 4, 5], [6, 7], [8, 9, 10], [11]],
838
+ ... "attention_mask": [[1, 1, 1, 0, 0], [1, 0], [1, 1, 0], [1]],
839
+ ... }
840
+ >>> dataset = Dataset.from_dict(examples)
841
+ >>> # Default "bfd" strategy (SFT-friendly): truncates long sequences
842
+ >>> packed_dataset = pack_dataset(dataset, seq_length=4, strategy="bfd")
843
+ >>> packed_dataset[:]
844
+ {'input_ids': [[1, 2, 3, 4], [8, 9, 10, 11], [6, 7]],
845
+ 'attention_mask': [[1, 1, 1, 0], [1, 1, 0, 1], [1, 0]],
846
+ 'seq_lengths': [[4], [3, 1], [2]]}
847
+
848
+ >>> # "bfd_split" strategy: preserves all tokens
849
+ >>> packed_dataset = pack_dataset(dataset, seq_length=4, strategy="bfd_split")
850
+ >>> packed_dataset[:]
851
+ {'input_ids': [[1, 2, 3, 4], [8, 9, 10, 5], [6, 7, 11]],
852
+ 'attention_mask': [[1, 1, 1, 0], [1, 1, 0, 0], [1, 0, 1]],
853
+ 'seq_lengths': [[4], [3, 1], [2, 1]]}
854
+ ```
855
+ """
856
+ if map_kwargs is None:
857
+ map_kwargs = {}
858
+
859
+ valid_strategies = ("bfd", "bfd_split", "wrapped")
860
+ if strategy not in valid_strategies:
861
+ raise ValueError(f"Invalid packing strategy '{strategy}', must be one of {valid_strategies}.")
862
+ format = _get_dataset_format(dataset)
863
+ dataset = dataset.with_format("arrow")
864
+ if strategy == "bfd":
865
+ dataset = dataset.map(
866
+ _pack_bfd,
867
+ batched=True,
868
+ fn_kwargs={"seq_length": seq_length, "on_seq_length_overflow": "truncate"},
869
+ **map_kwargs,
870
+ )
871
+ elif strategy == "bfd_split":
872
+ dataset = dataset.map(
873
+ _pack_bfd,
874
+ batched=True,
875
+ fn_kwargs={"seq_length": seq_length, "on_seq_length_overflow": "split"},
876
+ **map_kwargs,
877
+ )
878
+ elif strategy == "wrapped":
879
+ dataset = dataset.map(_pack_wrapped, batched=True, fn_kwargs={"seq_length": seq_length}, **map_kwargs)
880
+ else:
881
+ raise ValueError(f"Invalid packing strategy: '{strategy}', must be one of {valid_strategies}.")
882
+
883
+ if strategy in {"bfd", "bfd_split"} and "columns" in format:
884
+ format["columns"] = format["columns"] + ["seq_lengths"]
885
+
886
+ dataset = dataset.with_format(**format)
887
+ return dataset
888
+
889
+
890
+ def is_conversational_from_value(example: dict[str, Any]) -> bool:
891
+ r"""
892
+ Check if the example is in a conversational format (from/value). Note that this format isn't recommended. Prefer
893
+ the ChatML format (role/content)
894
+
895
+ Args:
896
+ example (`dict[str, Any]`):
897
+ A single data entry of a dataset. The example can have different keys depending on the dataset type.
898
+
899
+ Returns:
900
+ `bool`:
901
+ `True` if the data is in a conversational Chatformat, `False` otherwise.
902
+
903
+ Examples:
904
+
905
+ ```python
906
+ >>> example = {"conversations": [{"from": "user", "value": "What color is the sky?"}]}
907
+ >>> is_conversational_from_value(example)
908
+ True
909
+
910
+ >>> example = {"conversations": [{"role": "user", "content": "What color is the sky?"}]}
911
+ >>> is_conversational_from_value(example)
912
+ False
913
+
914
+ >>> example = {"conversations": "The sky is"}
915
+ >>> is_conversational_from_value(example)
916
+ False
917
+ ```
918
+ """
919
+ maybe_messages = example.get("conversations")
920
+ # It must be a list of messages
921
+ if isinstance(maybe_messages, list):
922
+ maybe_message = maybe_messages[0]
923
+ # Each message must a list of dictionaries with keys "from" and "value"
924
+ if isinstance(maybe_message, dict) and "from" in maybe_message and "value" in maybe_message:
925
+ return True
926
+
927
+ return False
928
+
929
+
930
+ def maybe_convert_to_chatml(example: dict[str, list]) -> dict[str, list]:
931
+ """
932
+ Convert a conversational dataset with fields `from` and `value` to ChatML format.
933
+
934
+ This function modifies conversational data to align with OpenAI's ChatML format:
935
+ - Replaces the key `"from"` with `"role"` in message dictionaries.
936
+ - Replaces the key `"value"` with `"content"` in message dictionaries.
937
+ - Renames `"conversations"` to `"messages"` for consistency with ChatML.
938
+
939
+ Args:
940
+ example (`dict[str, list]`):
941
+ A single data entry containing a list of messages.
942
+
943
+ Returns:
944
+ `dict[str, list]`:
945
+ Example reformatted to ChatML style.
946
+
947
+ Example:
948
+ ```python
949
+ >>> from trl import maybe_convert_to_chatml
950
+
951
+ >>> example = {
952
+ ... "conversations": [
953
+ ... {"from": "user", "value": "What color is the sky?"},
954
+ ... {"from": "assistant", "value": "It is blue."},
955
+ ... ]
956
+ ... }
957
+ >>> maybe_convert_to_chatml(example)
958
+ {'messages': [{'role': 'user', 'content': 'What color is the sky?'},
959
+ {'role': 'assistant', 'content': 'It is blue.'}]}
960
+ ```
961
+ """
962
+ # List of possible keys containing message lists
963
+ for key in ["prompt", "completion", "chosen", "rejected", "messages", "conversations"]:
964
+ if key in example and isinstance(example[key], list):
965
+ messages = example[key]
966
+ for message in messages:
967
+ if isinstance(message, dict):
968
+ if "from" in message:
969
+ message["role"] = message.pop("from")
970
+ if "value" in message:
971
+ message["content"] = message.pop("value")
972
+
973
+ # Rename "conversations" to "messages"
974
+ if "conversations" in example:
975
+ example["messages"] = example.pop("conversations")
976
+
977
+ return example
tasks/tasksmith-5b4f21a2a450/environment/source/trl/distributed.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
+ """Distributed training backend abstraction."""
16
+
17
+ from contextlib import contextmanager
18
+
19
+
20
+ class DistributedBackend:
21
+ """Abstracts distributed backend specifics (DeepSpeed ZeRO, FSDP) behind a uniform API.
22
+
23
+ Detects the active backend once at construction from ``accelerator.state``, then provides context managers that are
24
+ no-ops on backends where the operation is not needed.
25
+
26
+ Args:
27
+ accelerator ([`~accelerate.Accelerator`]):
28
+ The accelerator instance managing the distributed state.
29
+
30
+ Example:
31
+
32
+ ```python
33
+ >>> dist = DistributedBackend(accelerator)
34
+ >>> with dist.gather_params(list(model.parameters())):
35
+ ... model.merge_adapter()
36
+ >>> with dist.summon_full_params(model, recurse=False):
37
+ ... outputs = model.generate(inputs)
38
+ ```
39
+ """
40
+
41
+ def __init__(self, accelerator):
42
+ ds_plugin = accelerator.state.deepspeed_plugin
43
+ fsdp_plugin = getattr(accelerator.state, "fsdp_plugin", None)
44
+ self.zero_stage = ds_plugin.zero_stage if ds_plugin else 0
45
+ self.fsdp_version = getattr(fsdp_plugin, "fsdp_version", None) if fsdp_plugin else None
46
+
47
+ @property
48
+ def is_zero3(self) -> bool:
49
+ """Whether DeepSpeed ZeRO Stage 3 is active."""
50
+ return self.zero_stage == 3
51
+
52
+ @property
53
+ def is_fsdp(self) -> bool:
54
+ """Whether FSDP (any version) is active."""
55
+ return self.fsdp_version is not None
56
+
57
+ @contextmanager
58
+ def gather_params(self, params):
59
+ """Gather sharded parameters under DeepSpeed ZeRO-3; no-op otherwise.
60
+
61
+ Args:
62
+ params (iterable of `torch.nn.Parameter`):
63
+ Parameters to gather.
64
+ """
65
+ if self.is_zero3:
66
+ import deepspeed
67
+
68
+ with deepspeed.zero.GatheredParameters(params):
69
+ yield
70
+ else:
71
+ yield
72
+
73
+ @contextmanager
74
+ def summon_full_params(self, module, **kwargs):
75
+ """Materialize full FSDP v1 parameters; no-op for FSDP v2 or non-FSDP backends.
76
+
77
+ FSDP v2 parameters are always accessible and require no explicit materialization.
78
+
79
+ Args:
80
+ module (`torch.nn.Module`):
81
+ The FSDP-wrapped module.
82
+ **kwargs:
83
+ Forwarded to ``FSDP.summon_full_params`` (e.g. ``recurse``, ``writeback``).
84
+ """
85
+ if self.fsdp_version == 1:
86
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
87
+
88
+ with FSDP.summon_full_params(module, **kwargs):
89
+ yield
90
+ else:
91
+ yield
tasks/tasksmith-5b4f21a2a450/environment/source/trl/experimental/__init__.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Experimental submodule for TRL.
17
+
18
+ This submodule contains unstable or incubating features. Anything here may change (or be removed) in any release
19
+ without deprecation. Use at your own risk.
20
+
21
+ To silence this notice set environment variable TRL_EXPERIMENTAL_SILENCE=1.
22
+ """
23
+
24
+ import os
25
+ import warnings
26
+
27
+ from ..import_utils import TRLExperimentalWarning
28
+
29
+
30
+ if not os.environ.get("TRL_EXPERIMENTAL_SILENCE"):
31
+ warnings.warn(
32
+ "You are importing from 'trl.experimental'. APIs here are unstable and may change or be removed without "
33
+ "notice. Silence this warning by setting environment variable TRL_EXPERIMENTAL_SILENCE=1.",
34
+ TRLExperimentalWarning,
35
+ stacklevel=2,
36
+ )
tasks/tasksmith-5b4f21a2a450/environment/source/trl/experimental/a2po/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .a2po_config import A2POConfig
16
+ from .a2po_trainer import A2POTrainer
tasks/tasksmith-5b4f21a2a450/environment/source/trl/experimental/a2po/a2po_config.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 trl.trainer.base_config import _BaseConfig
18
+
19
+
20
+ @dataclass
21
+ class A2POConfig(_BaseConfig):
22
+ # docstyle-ignore
23
+ r"""
24
+ Configuration class for the [`A2POTrainer`].
25
+
26
+ This class includes only the parameters that are specific to A2PO training. For a full list of training arguments,
27
+ please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
28
+ differ from those in [`~transformers.TrainingArguments`].
29
+
30
+ Parameters:
31
+ > Parameters that control the model and reference model
32
+
33
+ model_init_kwargs (`dict[str, Any]`, *optional*):
34
+ Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model`
35
+ argument of the [`A2POTrainer`] is provided as a string.
36
+
37
+ > Parameters that control the data preprocessing
38
+
39
+ remove_unused_columns (`bool`, *optional*, defaults to `False`):
40
+ Whether to only keep the column `"prompt"` in the dataset. If you use a custom reward function that
41
+ requires any column other than `"prompts"` and `"completions"`, you should keep this to `False`.
42
+
43
+ > Parameters that control generation
44
+
45
+ max_prompt_length (`int` or `None`, *optional*, defaults to `512`):
46
+ Maximum length of the prompt. If the prompt is longer than this, it is left-truncated.
47
+ max_completion_length (`int` or `None`, *optional*, defaults to `256`):
48
+ Maximum length of the generated completion.
49
+ temperature (`float`, *optional*, defaults to `1.0`):
50
+ Sampling temperature, used in both Stage 1 and Stage 2 generation.
51
+ top_p (`float`, *optional*, defaults to `1.0`):
52
+ Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to
53
+ `1.0` to consider all tokens.
54
+ top_k (`int` or `None`, *optional*):
55
+ Number of highest-probability vocabulary tokens to keep. If `None`, top-k filtering is disabled.
56
+
57
+ > Parameters that control Stage 1 (offline optimal value estimation)
58
+
59
+ num_value_samples (`int`, *optional*, defaults to `8`):
60
+ Number of samples drawn from the reference policy per prompt to estimate `V*`.
61
+ beta1 (`float`, *optional*, defaults to `0.5`):
62
+ KL temperature used to estimate `V*` in Stage 1.
63
+ filter_all_incorrect (`bool`, *optional*, defaults to `True`):
64
+ Whether to drop prompts for which all reference samples are incorrect.
65
+
66
+ > Parameters that control Stage 2 (on-policy regression)
67
+
68
+ beta2 (`float`, *optional*, defaults to `1e-3`):
69
+ KL temperature used in the Stage 2 regression target.
70
+ reward_weights (`list[float]`, *optional*):
71
+ Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are
72
+ weighted equally with weight `1.0`.
73
+ """
74
+
75
+ _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
76
+
77
+ # Parameters that control the model and reference model
78
+ model_init_kwargs: dict | None = field(
79
+ default=None,
80
+ metadata={
81
+ "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of "
82
+ "the `A2POTrainer` is provided as a string."
83
+ },
84
+ )
85
+
86
+ # Parameters that control the data preprocessing
87
+ remove_unused_columns: bool = field(
88
+ default=False,
89
+ metadata={
90
+ "help": "Whether to only keep the column 'prompt' in the dataset. If you use a custom reward function "
91
+ "that requires any column other than 'prompts' and 'completions', you should keep this to `False`."
92
+ },
93
+ )
94
+
95
+ # Parameters that control generation
96
+ max_prompt_length: int | None = field(
97
+ default=512,
98
+ metadata={"help": "Maximum length of the prompt. If the prompt is longer than this, it is left-truncated."},
99
+ )
100
+ max_completion_length: int | None = field(
101
+ default=256, metadata={"help": "Maximum length of the generated completion."}
102
+ )
103
+ temperature: float = field(
104
+ default=1.0,
105
+ metadata={"help": "Sampling temperature, used in both Stage 1 and Stage 2 generation."},
106
+ )
107
+ top_p: float = field(
108
+ default=1.0,
109
+ metadata={
110
+ "help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. "
111
+ "Set to `1.0` to consider all tokens."
112
+ },
113
+ )
114
+ top_k: int | None = field(
115
+ default=None,
116
+ metadata={
117
+ "help": "Number of highest-probability vocabulary tokens to keep. If `None`, top-k filtering is disabled."
118
+ },
119
+ )
120
+
121
+ # Parameters that control Stage 1 (offline optimal value estimation)
122
+ num_value_samples: int = field(
123
+ default=8,
124
+ metadata={"help": "Number of samples drawn from the reference policy per prompt to estimate `V*`."},
125
+ )
126
+ beta1: float = field(
127
+ default=0.5,
128
+ metadata={"help": "KL temperature used to estimate `V*` in Stage 1."},
129
+ )
130
+ filter_all_incorrect: bool = field(
131
+ default=True,
132
+ metadata={"help": "Whether to drop prompts for which all reference samples are incorrect."},
133
+ )
134
+
135
+ # Parameters that control Stage 2 (on-policy regression)
136
+ beta2: float = field(
137
+ default=1e-3,
138
+ metadata={"help": "KL temperature used in the Stage 2 regression target."},
139
+ )
140
+ reward_weights: list[float] | None = field(
141
+ default=None,
142
+ metadata={
143
+ "help": "Weights for each reward function. Must match the number of reward functions. If `None`, all "
144
+ "rewards are weighted equally with weight `1.0`."
145
+ },
146
+ )